cronometer-api-mcp 0.2.2__tar.gz → 0.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. cronometer_api_mcp-0.2.4/.env.example +6 -0
  2. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/PKG-INFO +46 -3
  3. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/README.md +45 -2
  4. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/pyproject.toml +1 -1
  5. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/server.json +14 -2
  6. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/client.py +267 -26
  7. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/server.py +251 -179
  8. cronometer_api_mcp-0.2.4/tests/test_custom_food_edit.py +340 -0
  9. cronometer_api_mcp-0.2.4/tests/test_relative_dates.py +187 -0
  10. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/tests/test_server_import.py +5 -7
  11. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/tests/test_timezone.py +177 -2
  12. cronometer_api_mcp-0.2.4/tests/test_totp.py +107 -0
  13. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/uv.lock +30 -30
  14. cronometer_api_mcp-0.2.2/.env.example +0 -2
  15. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.dockerignore +0 -0
  16. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.github/dependabot.yml +0 -0
  17. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.github/workflows/ci.yml +0 -0
  18. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.github/workflows/docker.yml +0 -0
  19. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.github/workflows/publish.yml +0 -0
  20. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.gitignore +0 -0
  21. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/.python-version +0 -0
  22. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/Dockerfile +0 -0
  23. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/LICENSE +0 -0
  24. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/__init__.py +0 -0
  25. {cronometer_api_mcp-0.2.2 → cronometer_api_mcp-0.2.4}/tests/test_client.py +0 -0
@@ -0,0 +1,6 @@
1
+ CRONOMETER_USERNAME=
2
+ CRONOMETER_PASSWORD=
3
+ # Only for accounts with two-factor authentication: the base32 key shown at 2FA setup
4
+ CRONOMETER_TOTP_SECRET=
5
+ # Optional IANA timezone override, for example America/Los_Angeles
6
+ CRONOMETER_ACCOUNT_TZ=
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cronometer-api-mcp
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: MCP server for Cronometer nutrition data using the mobile REST API
5
5
  Author: Randy
6
6
  License-Expression: MIT
@@ -59,6 +59,20 @@ export CRONOMETER_USERNAME="your@email.com"
59
59
  export CRONOMETER_PASSWORD="your-password"
60
60
  ```
61
61
 
62
+ #### Optional: two-factor authentication
63
+
64
+ If the account has two-factor authentication enabled, `/api/v2/login`
65
+ answers `TOTP_CODE_REQUIRED` unless the request carries the current 6-digit
66
+ code. Give the server the base32 key that Cronometer showed when 2FA was set
67
+ up (the same key you scanned into your authenticator app) and it derives the
68
+ code itself at every login (RFC 6238, SHA-1, 30 s period):
69
+
70
+ ```bash
71
+ export CRONOMETER_TOTP_SECRET="ABCD EFGH IJKL MNOP QRST UVWX YZ23 4567"
72
+ ```
73
+
74
+ Spaces and lowercase are fine. Leave it unset for accounts without 2FA.
75
+
62
76
  #### Optional: override the account timezone
63
77
 
64
78
  Diary entries are stamped in your Cronometer account's timezone, which the
@@ -88,7 +102,9 @@ cached session, so it also overrides a stale cached timezone.
88
102
  "command": ["uvx", "cronometer-api-mcp"],
89
103
  "environment": {
90
104
  "CRONOMETER_USERNAME": "{env:CRONOMETER_USERNAME}",
91
- "CRONOMETER_PASSWORD": "{env:CRONOMETER_PASSWORD}"
105
+ "CRONOMETER_PASSWORD": "{env:CRONOMETER_PASSWORD}",
106
+ "CRONOMETER_TOTP_SECRET": "{env:CRONOMETER_TOTP_SECRET}",
107
+ "CRONOMETER_ACCOUNT_TZ": "{env:CRONOMETER_ACCOUNT_TZ}"
92
108
  },
93
109
  "enabled": true
94
110
  }
@@ -106,7 +122,9 @@ cached session, so it also overrides a stale cached timezone.
106
122
  "args": ["cronometer-api-mcp"],
107
123
  "env": {
108
124
  "CRONOMETER_USERNAME": "your@email.com",
109
- "CRONOMETER_PASSWORD": "your-password"
125
+ "CRONOMETER_PASSWORD": "your-password",
126
+ "CRONOMETER_TOTP_SECRET": "your-base32-key",
127
+ "CRONOMETER_ACCOUNT_TZ": "America/Los_Angeles"
110
128
  }
111
129
  }
112
130
  }
@@ -137,6 +155,8 @@ cached session, so it also overrides a stale cached timezone.
137
155
  | `add_food_entry` | Log a food serving to the diary |
138
156
  | `remove_food_entry` | Remove one or more diary entries |
139
157
  | `add_custom_food` | Create a custom food with specified nutrition |
158
+ | `update_custom_food` | Edit a custom food in place: name, nutrition, or serving size |
159
+ | `delete_custom_food` | Retire a custom food so it leaves search and the Custom Foods list (existing diary entries are kept) |
140
160
  | `add_recipe` | Create a recipe from existing foods referenced by ID and gram weight |
141
161
  | `import_recipe` | Create a recipe from a free-text ingredient list; Cronometer matches each line to a database food and converts the amount to grams |
142
162
  | `copy_day` | Copy all entries from the previous day |
@@ -154,6 +174,29 @@ cached session, so it also overrides a stale cached timezone.
154
174
 
155
175
  All date parameters use `YYYY-MM-DD` format and default to today when omitted.
156
176
 
177
+ ### Relative dates and recent days
178
+
179
+ `get_food_log`, `get_daily_nutrition`, and `get_nutrition_scores` also accept
180
+ `"today"`, `"yesterday"`, and `"N days ago"` as their `date`. These are resolved
181
+ at call time using your Cronometer account timezone, so Claude can pass relative
182
+ inputs without relying on dates from earlier in a long conversation.
183
+
184
+ `get_food_log` and `get_daily_nutrition` accept `days` (1–31, default 1), counting
185
+ back from the inclusive end `date`:
186
+
187
+ ```python
188
+ get_food_log(date="yesterday")
189
+ get_nutrition_scores(date="3 days ago")
190
+ get_daily_nutrition(days=3) # Last 3 days, including today
191
+ get_daily_nutrition(date="yesterday", days=3) # Previous 3 complete calendar days
192
+ get_food_log(days=7) # Recent meals, including today
193
+ ```
194
+
195
+ For “my calories the last few days,” use `get_daily_nutrition(days=3)`.
196
+ Single-day responses retain their existing shape. Multi-day responses contain
197
+ `start_date`, `end_date`, and a `days` list of daily results, oldest first.
198
+ Returned dates are always concrete `YYYY-MM-DD` values.
199
+
157
200
  ## Transport
158
201
 
159
202
  stdio only. For remote/hosted use, the stdio server is wrapped by
@@ -39,6 +39,20 @@ export CRONOMETER_USERNAME="your@email.com"
39
39
  export CRONOMETER_PASSWORD="your-password"
40
40
  ```
41
41
 
42
+ #### Optional: two-factor authentication
43
+
44
+ If the account has two-factor authentication enabled, `/api/v2/login`
45
+ answers `TOTP_CODE_REQUIRED` unless the request carries the current 6-digit
46
+ code. Give the server the base32 key that Cronometer showed when 2FA was set
47
+ up (the same key you scanned into your authenticator app) and it derives the
48
+ code itself at every login (RFC 6238, SHA-1, 30 s period):
49
+
50
+ ```bash
51
+ export CRONOMETER_TOTP_SECRET="ABCD EFGH IJKL MNOP QRST UVWX YZ23 4567"
52
+ ```
53
+
54
+ Spaces and lowercase are fine. Leave it unset for accounts without 2FA.
55
+
42
56
  #### Optional: override the account timezone
43
57
 
44
58
  Diary entries are stamped in your Cronometer account's timezone, which the
@@ -68,7 +82,9 @@ cached session, so it also overrides a stale cached timezone.
68
82
  "command": ["uvx", "cronometer-api-mcp"],
69
83
  "environment": {
70
84
  "CRONOMETER_USERNAME": "{env:CRONOMETER_USERNAME}",
71
- "CRONOMETER_PASSWORD": "{env:CRONOMETER_PASSWORD}"
85
+ "CRONOMETER_PASSWORD": "{env:CRONOMETER_PASSWORD}",
86
+ "CRONOMETER_TOTP_SECRET": "{env:CRONOMETER_TOTP_SECRET}",
87
+ "CRONOMETER_ACCOUNT_TZ": "{env:CRONOMETER_ACCOUNT_TZ}"
72
88
  },
73
89
  "enabled": true
74
90
  }
@@ -86,7 +102,9 @@ cached session, so it also overrides a stale cached timezone.
86
102
  "args": ["cronometer-api-mcp"],
87
103
  "env": {
88
104
  "CRONOMETER_USERNAME": "your@email.com",
89
- "CRONOMETER_PASSWORD": "your-password"
105
+ "CRONOMETER_PASSWORD": "your-password",
106
+ "CRONOMETER_TOTP_SECRET": "your-base32-key",
107
+ "CRONOMETER_ACCOUNT_TZ": "America/Los_Angeles"
90
108
  }
91
109
  }
92
110
  }
@@ -117,6 +135,8 @@ cached session, so it also overrides a stale cached timezone.
117
135
  | `add_food_entry` | Log a food serving to the diary |
118
136
  | `remove_food_entry` | Remove one or more diary entries |
119
137
  | `add_custom_food` | Create a custom food with specified nutrition |
138
+ | `update_custom_food` | Edit a custom food in place: name, nutrition, or serving size |
139
+ | `delete_custom_food` | Retire a custom food so it leaves search and the Custom Foods list (existing diary entries are kept) |
120
140
  | `add_recipe` | Create a recipe from existing foods referenced by ID and gram weight |
121
141
  | `import_recipe` | Create a recipe from a free-text ingredient list; Cronometer matches each line to a database food and converts the amount to grams |
122
142
  | `copy_day` | Copy all entries from the previous day |
@@ -134,6 +154,29 @@ cached session, so it also overrides a stale cached timezone.
134
154
 
135
155
  All date parameters use `YYYY-MM-DD` format and default to today when omitted.
136
156
 
157
+ ### Relative dates and recent days
158
+
159
+ `get_food_log`, `get_daily_nutrition`, and `get_nutrition_scores` also accept
160
+ `"today"`, `"yesterday"`, and `"N days ago"` as their `date`. These are resolved
161
+ at call time using your Cronometer account timezone, so Claude can pass relative
162
+ inputs without relying on dates from earlier in a long conversation.
163
+
164
+ `get_food_log` and `get_daily_nutrition` accept `days` (1–31, default 1), counting
165
+ back from the inclusive end `date`:
166
+
167
+ ```python
168
+ get_food_log(date="yesterday")
169
+ get_nutrition_scores(date="3 days ago")
170
+ get_daily_nutrition(days=3) # Last 3 days, including today
171
+ get_daily_nutrition(date="yesterday", days=3) # Previous 3 complete calendar days
172
+ get_food_log(days=7) # Recent meals, including today
173
+ ```
174
+
175
+ For “my calories the last few days,” use `get_daily_nutrition(days=3)`.
176
+ Single-day responses retain their existing shape. Multi-day responses contain
177
+ `start_date`, `end_date`, and a `days` list of daily results, oldest first.
178
+ Returned dates are always concrete `YYYY-MM-DD` values.
179
+
137
180
  ## Transport
138
181
 
139
182
  stdio only. For remote/hosted use, the stdio server is wrapped by
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cronometer-api-mcp"
7
- version = "0.2.2"
7
+ version = "0.2.4"
8
8
  description = "MCP server for Cronometer nutrition data using the mobile REST API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/rwestergren/cronometer-api-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.2.2",
9
+ "version": "0.2.4",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "pypi",
13
13
  "identifier": "cronometer-api-mcp",
14
- "version": "0.2.2",
14
+ "version": "0.2.4",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -27,6 +27,18 @@
27
27
  "description": "Your Cronometer account password",
28
28
  "isRequired": true,
29
29
  "isSecret": true
30
+ },
31
+ {
32
+ "name": "CRONOMETER_TOTP_SECRET",
33
+ "description": "Base32 key for accounts with two-factor authentication",
34
+ "isRequired": false,
35
+ "isSecret": true
36
+ },
37
+ {
38
+ "name": "CRONOMETER_ACCOUNT_TZ",
39
+ "description": "Optional IANA timezone override, for example America/Los_Angeles",
40
+ "isRequired": false,
41
+ "isSecret": false
30
42
  }
31
43
  ]
32
44
  }
@@ -9,9 +9,14 @@ Frida-based traffic capture that established the auth flow and initial
9
9
  endpoints.
10
10
  """
11
11
 
12
+ import base64
13
+ import copy
14
+ import hashlib
15
+ import hmac
12
16
  import json
13
17
  import logging
14
18
  import os
19
+ import struct
15
20
  import threading
16
21
  import time
17
22
  from datetime import date, datetime
@@ -24,9 +29,9 @@ logger = logging.getLogger(__name__)
24
29
 
25
30
  BASE_URL = "https://mobile.cronometer.com"
26
31
 
27
- # Fallback timezone used only if the account's timezone can't be resolved from
28
- # the login response. Matches the value historically assumed by this client.
29
- _DEFAULT_TIMEZONE = "America/New_York"
32
+ # Only when the zone can't be resolved at all. UTC, not a plausible zone to
33
+ # make fallback more obvious
34
+ _FALLBACK_TIMEZONE = "UTC"
30
35
 
31
36
  # Optional deploy-time override for the account timezone. When set to a valid
32
37
  # IANA zone name it is authoritative over both the login response and any
@@ -120,6 +125,23 @@ class CronometerError(Exception):
120
125
  """Raised when a Cronometer API call fails."""
121
126
 
122
127
 
128
+ def _totp_code(secret: str, for_time: float | None = None) -> str:
129
+ """Current RFC 6238 TOTP code (SHA-1, 30 s period, 6 digits) for `secret`.
130
+
131
+ `secret` is the base32 key shown by Cronometer when enabling two-factor
132
+ authentication; authenticator apps display it grouped and sometimes
133
+ lowercased, so whitespace and case are normalized before decoding.
134
+ """
135
+ normalized = "".join(secret.split()).upper()
136
+ normalized += "=" * (-len(normalized) % 8)
137
+ key = base64.b32decode(normalized)
138
+ counter = int((time.time() if for_time is None else for_time) // 30)
139
+ digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
140
+ offset = digest[-1] & 0x0F
141
+ code = int.from_bytes(digest[offset : offset + 4], "big") & 0x7FFFFFFF
142
+ return f"{code % 1_000_000:06d}"
143
+
144
+
123
145
  class CronometerClient:
124
146
  """Stateful client for the Cronometer mobile API.
125
147
 
@@ -127,8 +149,9 @@ class CronometerClient:
127
149
  Re-authenticates automatically when the session expires.
128
150
 
129
151
  Thread safety: one instance is shared across MCP tool calls, which the SDK
130
- dispatches on worker threads. Only auth state transitions are serialized;
131
- requests still run concurrently. See `_auth_lock`.
152
+ dispatches on worker threads. Auth state transitions are serialized (see
153
+ `_auth_lock`), and edits to a given custom food are serialized per food id
154
+ (see `_food_lock`); everything else runs concurrently.
132
155
  """
133
156
 
134
157
  def __init__(self, *, session_path: Path | None = None) -> None:
@@ -142,6 +165,12 @@ class CronometerClient:
142
165
  # Guards (_user_id, _token, _timezone) and the session file mirroring
143
166
  # them. Reentrant because the auth paths nest: login -> _save_cached_session.
144
167
  self._auth_lock = threading.RLock()
168
+
169
+ # Serialize each food's fetch-modify-save cycle because add_food replaces the
170
+ # entire object. `_food_locks_guard` protects the lock registry.
171
+ self._food_locks: dict[int, threading.Lock] = {}
172
+ self._food_locks_guard = threading.Lock()
173
+
145
174
  # Cache of nutrient definitions (id -> {name, unit, category}).
146
175
  # Definitions are stable for an account, so fetch them once.
147
176
  self._nutrient_defs: dict[int, dict] | None = None
@@ -185,10 +214,13 @@ class CronometerClient:
185
214
  return
186
215
  token = data.get("token")
187
216
  user_id = data.get("user_id")
188
- timezone = data.get("timezone")
189
- # Reject caches that lack a stored timezone (pre-timezone schema) so we
190
- # re-login once and pick up the account zone rather than guessing.
191
- if not isinstance(timezone, str):
217
+ # Missing key is the pre-timezone schema: re-login to learn the zone.
218
+ # Explicit null means the account has none, so honour the cache instead
219
+ # of re-logging in every start against a rate-limited endpoint.
220
+ if "timezone" not in data:
221
+ return
222
+ timezone = data["timezone"]
223
+ if timezone is not None and not isinstance(timezone, str):
192
224
  return
193
225
  if isinstance(token, str) and isinstance(user_id, int):
194
226
  self._user_id = user_id
@@ -251,6 +283,11 @@ class CronometerClient:
251
283
  )
252
284
  return username, password
253
285
 
286
+ @staticmethod
287
+ def _totp_user_code() -> str | None:
288
+ secret = os.getenv("CRONOMETER_TOTP_SECRET")
289
+ return _totp_code(secret) if secret else None
290
+
254
291
  def login(self) -> None:
255
292
  """Authenticate with Cronometer and cache the session token.
256
293
 
@@ -271,7 +308,9 @@ class CronometerClient:
271
308
  # leaves the account setting untouched and the response echoes the
272
309
  # account's real zone.
273
310
  "timezone": None,
274
- "userCode": None,
311
+ # 6-digit TOTP code for accounts with two-factor authentication,
312
+ # derived from CRONOMETER_TOTP_SECRET; null when 2FA is not in use.
313
+ "userCode": self._totp_user_code(),
275
314
  "build": "4.48.2 b2807-a",
276
315
  "device": "Android 14 (SDK 34), Google Pixel 6 Pro",
277
316
  "firebaseToken": "",
@@ -295,6 +334,12 @@ class CronometerClient:
295
334
  data = resp.json()
296
335
 
297
336
  if data.get("result") != "SUCCESS" and "sessionKey" not in data:
337
+ if data.get("error") == "TOTP_CODE_REQUIRED":
338
+ raise CronometerError(
339
+ "Login failed: the account has two-factor authentication "
340
+ "enabled; set CRONOMETER_TOTP_SECRET to the base32 key "
341
+ "shown when 2FA was set up"
342
+ )
298
343
  raise CronometerError(f"Login failed: {data}")
299
344
 
300
345
  self._user_id = data["id"]
@@ -463,38 +508,52 @@ class CronometerClient:
463
508
  return None
464
509
  return name
465
510
 
466
- def _resolve_timezone(self, response_tz: str | None) -> str:
467
- """Resolve the account timezone by priority.
511
+ def _resolve_timezone(self, response_tz: str | None) -> str | None:
512
+ """Env override, else the login response. None when neither is usable.
468
513
 
469
- 1. CRONOMETER_ACCOUNT_TZ env override (authoritative escape hatch).
470
- 2. The value from the login response (trustworthy now that login()
471
- no longer overwrites the account's server-side zone; see #29).
472
- 3. The historical default.
514
+ Validates the response: storing an unknown name defers the failure to
515
+ ``_tzinfo``, where it is no longer attributable to Cronometer.
473
516
  """
474
517
  env = self._env_timezone()
475
518
  if env:
476
519
  return env
477
520
  if isinstance(response_tz, str) and response_tz:
478
- return response_tz
479
- return _DEFAULT_TIMEZONE
521
+ try:
522
+ ZoneInfo(response_tz)
523
+ return response_tz
524
+ except ZoneInfoNotFoundError, ValueError:
525
+ logger.warning(
526
+ "Cronometer reported unknown timezone %r; ignoring", response_tz
527
+ )
528
+ return None
480
529
 
481
530
  def _tzinfo(self) -> ZoneInfo:
482
- """Return the account's timezone, falling back to the default.
531
+ """The account's zone, logging in if that's the only way to learn it.
532
+
533
+ Every consumer funnels through here, so this is where the zone has to
534
+ be guaranteed resolved: callers used to read the clock pre-auth and get
535
+ the fallback, correcting only once something else triggered login.
483
536
 
484
- Resolved from the login response (or restored session cache). If the
485
- stored name is unset or unknown (e.g. a zone missing from the system
486
- tzdata), log once and fall back so stamping never hard-fails.
537
+ Env override first, so an injected zone needs no network.
487
538
  """
488
- name = self._timezone or _DEFAULT_TIMEZONE
539
+ name = self._env_timezone()
540
+ if not name:
541
+ self._ensure_auth()
542
+ name = self._timezone
543
+ if not name:
544
+ logger.warning(
545
+ "No account timezone available; stamping in %s", _FALLBACK_TIMEZONE
546
+ )
547
+ return ZoneInfo(_FALLBACK_TIMEZONE)
489
548
  try:
490
549
  return ZoneInfo(name)
491
550
  except ZoneInfoNotFoundError, ValueError:
492
551
  logger.warning(
493
- "Unknown account timezone %r; falling back to %s",
552
+ "Unknown account timezone %r; stamping in %s",
494
553
  name,
495
- _DEFAULT_TIMEZONE,
554
+ _FALLBACK_TIMEZONE,
496
555
  )
497
- return ZoneInfo(_DEFAULT_TIMEZONE)
556
+ return ZoneInfo(_FALLBACK_TIMEZONE)
498
557
 
499
558
  def now(self) -> datetime:
500
559
  """Current wall-clock time in the account's timezone (aware)."""
@@ -689,6 +748,188 @@ class CronometerClient:
689
748
  logger.info("Created custom food %r (id=%d)", name, food_id)
690
749
  return {"food_id": food_id, "measure_id": None}
691
750
 
751
+ # ------------------------------------------------------------------
752
+ # Custom food edit / retire
753
+ # ------------------------------------------------------------------
754
+
755
+ def _save_custom_food(self, food: dict) -> dict:
756
+ """Re-send a full food object to /api/v2/add_food, which upserts.
757
+
758
+ A non-zero id edits that food in place (verified against the live API:
759
+ the id, measure ids and unchanged nutrients all survive). The server
760
+ tacks FOOD_CHANGED sync messages onto get_food responses; those are not
761
+ food data and are dropped before sending.
762
+ """
763
+ data = copy.deepcopy(food)
764
+ data.pop("messages", None)
765
+ payload = {"data": data, "config": {"call_version": 1}}
766
+ resp = self._request("/api/v2/add_food", payload)
767
+ if resp.get("id") != data["id"]:
768
+ raise CronometerError(f"Failed to save custom food {data['id']}: {resp}")
769
+ return resp
770
+
771
+ def _food_lock(self, food_id: int) -> threading.Lock:
772
+ """The lock serializing edits of one custom food; see __init__."""
773
+ with self._food_locks_guard:
774
+ lock = self._food_locks.get(food_id)
775
+ if lock is None:
776
+ lock = self._food_locks[food_id] = threading.Lock()
777
+ return lock
778
+
779
+ def _get_custom_food(self, food_id: int) -> dict:
780
+ """Fetch a food and refuse anything that isn't a plain custom food.
781
+
782
+ Re-sending a database food through add_food is untested territory (it
783
+ might create a private copy or fail), so only source "Custom" -- what
784
+ get_food reports for user-created foods -- may be edited or retired.
785
+
786
+ User-created recipes report source "Custom" too, but they carry an
787
+ `ingredients` array their nutrient totals are derived from, and their
788
+ measures follow different rules. Editing one as a plain food would
789
+ leave it inconsistent, so recipes are refused as well.
790
+ """
791
+ food = self.get_food(food_id)
792
+ if food.get("source") != "Custom":
793
+ raise CronometerError(
794
+ f"Food {food_id} ({food.get('name')!r}) is not a custom food "
795
+ f"(source={food.get('source')!r}); only custom foods can be edited"
796
+ )
797
+ if food.get("ingredients"):
798
+ raise CronometerError(
799
+ f"Food {food_id} ({food.get('name')!r}) is a recipe; only plain "
800
+ f"custom foods can be edited or deleted"
801
+ )
802
+ return food
803
+
804
+ @staticmethod
805
+ def _default_measure(food: dict) -> dict | None:
806
+ measures = food.get("measures") or []
807
+ for m in measures:
808
+ if m.get("id") == food.get("defaultMeasureId"):
809
+ return m
810
+ return measures[0] if measures else None
811
+
812
+ def update_custom_food(
813
+ self,
814
+ food_id: int,
815
+ *,
816
+ name: str | None = None,
817
+ calories: float | None = None,
818
+ protein_g: float | None = None,
819
+ fat_g: float | None = None,
820
+ carbs_g: float | None = None,
821
+ fiber_g: float | None = None,
822
+ sugar_g: float | None = None,
823
+ sodium_mg: float | None = None,
824
+ saturated_fat_g: float | None = None,
825
+ extra_nutrients: dict[int, float] | None = None,
826
+ serving_name: str | None = None,
827
+ serving_grams: float | None = None,
828
+ ) -> dict:
829
+ """Edit a user-created custom food in place.
830
+
831
+ Only the fields passed (not None) change; everything else is re-sent
832
+ exactly as the server returned it. Nutrient amounts are per serving --
833
+ the default measure's weight, or serving_grams when given -- and are
834
+ normalized to per-100g like create_custom_food. Changing serving_grams
835
+ alone leaves the stored per-100g values as they are, so the food's
836
+ per-serving numbers shift with the new weight.
837
+
838
+ Returns {"food_id": int, "name": str}.
839
+ """
840
+ if extra_nutrients:
841
+ overlap = set(extra_nutrients) & _RESERVED_CUSTOM_FOOD_NUTRIENT_IDS
842
+ if overlap:
843
+ raise ValueError(
844
+ f"extra_nutrients overlaps IDs already set by the named "
845
+ f"macro args: {sorted(overlap)}. Use the named args for "
846
+ f"those instead."
847
+ )
848
+
849
+ with self._food_lock(food_id):
850
+ food = self._get_custom_food(food_id)
851
+
852
+ if name is not None:
853
+ old_name = food.get("name")
854
+ food["name"] = name
855
+ for t in food.get("translations", []):
856
+ if t.get("name") == old_name:
857
+ t["name"] = name
858
+
859
+ measure = self._default_measure(food)
860
+ if measure is not None:
861
+ if serving_name is not None:
862
+ measure["name"] = serving_name
863
+ if serving_grams is not None:
864
+ measure["value"] = serving_grams
865
+ grams = (measure or {}).get("value") or 100.0
866
+ scale = 100.0 / grams if grams > 0 else 1.0
867
+
868
+ per_serving = {
869
+ NUTRIENT_IDS["energy"]: calories,
870
+ NUTRIENT_IDS["protein"]: protein_g,
871
+ NUTRIENT_IDS["fat"]: fat_g,
872
+ NUTRIENT_IDS["carbs"]: carbs_g,
873
+ NUTRIENT_IDS["fiber"]: fiber_g,
874
+ NUTRIENT_IDS["sugar"]: sugar_g,
875
+ NUTRIENT_IDS["sodium"]: sodium_mg,
876
+ NUTRIENT_IDS["saturated_fat"]: saturated_fat_g,
877
+ }
878
+ updates = {
879
+ nid: round(v * scale, 2)
880
+ for nid, v in per_serving.items()
881
+ if v is not None
882
+ }
883
+ for nid, v in (extra_nutrients or {}).items():
884
+ updates[nid] = round(v * scale, 2)
885
+
886
+ nutrients = food.setdefault("nutrients", [])
887
+ by_id = {n["id"]: n for n in nutrients}
888
+
889
+ def set_amount(nid: int, amount: float) -> None:
890
+ entry = by_id.get(nid)
891
+ if entry is None:
892
+ entry = {"id": nid, "amount": amount}
893
+ nutrients.append(entry)
894
+ by_id[nid] = entry
895
+ else:
896
+ entry["amount"] = amount
897
+
898
+ for nid, amount in updates.items():
899
+ set_amount(nid, amount)
900
+
901
+ # Derived duplicates the app stores alongside the macros (see
902
+ # create_custom_food): mirrored protein/fat/carbs and net carbs.
903
+ for src, mirror in ((203, -203), (204, -204), (205, -205)):
904
+ if src in updates:
905
+ set_amount(mirror, updates[src])
906
+ if NUTRIENT_IDS["carbs"] in updates or NUTRIENT_IDS["fiber"] in updates:
907
+ carbs = by_id.get(NUTRIENT_IDS["carbs"], {}).get("amount", 0)
908
+ fiber = by_id.get(NUTRIENT_IDS["fiber"], {}).get("amount", 0)
909
+ set_amount(NUTRIENT_IDS["net_carbs"], round(max(0, carbs - fiber), 2))
910
+
911
+ self._save_custom_food(food)
912
+ logger.info("Updated custom food %r (id=%d)", food["name"], food_id)
913
+ return {"food_id": food_id, "name": food["name"]}
914
+
915
+ def retire_custom_food(self, food_id: int) -> dict:
916
+ """Retire (soft-delete) a user-created custom food.
917
+
918
+ Sets `retired` on the food and saves it. A retired food drops out of
919
+ search and the Custom Foods list but stays readable by id and keeps
920
+ existing diary entries intact. The app's own delete removes the food
921
+ outright through an endpoint this client doesn't know; retiring is the
922
+ closest the known API offers, and it is idempotent.
923
+
924
+ Returns {"food_id": int, "name": str, "retired": True}.
925
+ """
926
+ with self._food_lock(food_id):
927
+ food = self._get_custom_food(food_id)
928
+ food["retired"] = True
929
+ self._save_custom_food(food)
930
+ logger.info("Retired custom food %r (id=%d)", food.get("name"), food_id)
931
+ return {"food_id": food_id, "name": food.get("name"), "retired": True}
932
+
692
933
  # ------------------------------------------------------------------
693
934
  # Recipe creation
694
935
  # ------------------------------------------------------------------