renpho-api 0.3.0__tar.gz → 0.4.0__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 (26) hide show
  1. {renpho_api-0.3.0 → renpho_api-0.4.0}/PKG-INFO +42 -12
  2. {renpho_api-0.3.0 → renpho_api-0.4.0}/README.md +39 -11
  3. {renpho_api-0.3.0 → renpho_api-0.4.0}/pyproject.toml +17 -2
  4. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/__init__.py +9 -0
  5. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/cli.py +13 -6
  6. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/client.py +89 -64
  7. renpho_api-0.4.0/renpho/py.typed +0 -0
  8. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/PKG-INFO +42 -12
  9. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/SOURCES.txt +3 -1
  10. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/requires.txt +1 -0
  11. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_client.py +9 -6
  12. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_crypto.py +0 -1
  13. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_export.py +0 -1
  14. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_hardening.py +91 -20
  15. renpho_api-0.4.0/tests/test_public_api.py +70 -0
  16. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/constants.py +0 -0
  17. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/crypto.py +0 -0
  18. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/export.py +0 -0
  19. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho/girth.py +0 -0
  20. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/dependency_links.txt +0 -0
  21. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/entry_points.txt +0 -0
  22. {renpho_api-0.3.0 → renpho_api-0.4.0}/renpho_api.egg-info/top_level.txt +0 -0
  23. {renpho_api-0.3.0 → renpho_api-0.4.0}/setup.cfg +0 -0
  24. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_constants.py +0 -0
  25. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_friends.py +0 -0
  26. {renpho_api-0.3.0 → renpho_api-0.4.0}/tests/test_girth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: renpho-api
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Unofficial Python client for the Renpho Health API — pull body composition data from Renpho smart scales and body girth data from smart tape measures.
5
5
  Author: danvaneijck
6
6
  License-Expression: MIT
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
17
  Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Typing :: Typed
18
19
  Requires-Python: >=3.10
19
20
  Description-Content-Type: text/markdown
20
21
  Requires-Dist: requests>=2.28
@@ -23,6 +24,7 @@ Provides-Extra: dotenv
23
24
  Requires-Dist: python-dotenv>=1.0; extra == "dotenv"
24
25
  Provides-Extra: dev
25
26
  Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: ruff==0.17.3; extra == "dev"
26
28
 
27
29
  # renpho-api
28
30
 
@@ -66,8 +68,9 @@ recent, and save everything to `renpho_data/` as JSON and CSV. If the account ha
66
68
  a smart tape measure it also writes `girth.json` / `girth.csv`; accounts without
67
69
  one simply report no girth records.
68
70
 
69
- Family members linked to the account are saved to `family_members.json`, and
70
- measurements are tagged with a `userName` field.
71
+ The CLI exports measurements for you and every family member on the account.
72
+ Each row is tagged with a `userName` field, and the family profiles are saved to
73
+ `family_members.json`.
71
74
 
72
75
  ### Environment variables
73
76
 
@@ -87,11 +90,15 @@ from renpho import RenphoClient
87
90
  client = RenphoClient("user@example.com", "password")
88
91
  client.login()
89
92
 
90
- # Fetch all measurements in one call
93
+ # All of your measurements, newest first. Family members who share the scale
94
+ # are not included (see "Family members" below).
91
95
  measurements = client.get_all_measurements()
92
96
 
93
97
  for m in measurements:
94
98
  print(m["weight"], m.get("bodyfat"), m.get("muscle"))
99
+
100
+ import renpho
101
+ print(renpho.__version__)
95
102
  ```
96
103
 
97
104
  ### Step-by-step control
@@ -106,11 +113,13 @@ client.login()
106
113
  device_info = client.get_device_info()
107
114
  scales = device_info["scale"]
108
115
 
109
- # Fetch from a specific scale table
116
+ # Fetch your rows from a scale table that lists you. The server only returns
117
+ # rows for the user id you pass, even on a table shared with family members.
110
118
  # Use get_body_composition_measurements() for scales with impedance sensors
111
- # (body fat, muscle, etc.) — the server-side count is unreliable for these.
112
- # Fall back to get_measurements() for weight-only scales.
113
- table = scales[0]
119
+ # (body fat, muscle, etc.) and fall back to get_measurements() when it comes
120
+ # back empty. Don't pass the table's "count" as a total: it counts every
121
+ # person on that table.
122
+ table = next(s for s in scales if str(client.user_id) in map(str, s["userIds"]))
114
123
  measurements = client.get_body_composition_measurements(
115
124
  table_name=table["tableName"],
116
125
  user_id=client.user_id,
@@ -119,7 +128,6 @@ if not measurements:
119
128
  measurements = client.get_measurements(
120
129
  table_name=table["tableName"],
121
130
  user_id=client.user_id,
122
- total_count=table["count"],
123
131
  )
124
132
 
125
133
  # Export
@@ -145,6 +153,18 @@ Each entry is a full profile dict. Its `id` matches the `userIds` listed per
145
153
  scale in `get_device_info()` and the `bUserId` field on measurement records.
146
154
  Compare IDs as strings, since they arrive as both `int` and `str`.
147
155
 
156
+ To fetch a family member's measurements, pass their `id`:
157
+
158
+ ```python
159
+ family = client.get_family_members()
160
+
161
+ # One person instead of you:
162
+ kid = client.get_all_measurements(profile_user_id=family[0]["id"])
163
+
164
+ # You plus everyone; bUserId says whose each row is:
165
+ everyone = client.get_all_measurements(extra_user_ids=[m["id"] for m in family])
166
+ ```
167
+
148
168
  ### Reading through a friend account
149
169
 
150
170
  Renpho allows one active session per account, so logging in with your main
@@ -207,6 +227,14 @@ measurements = client.get_all_measurements(
207
227
  The library locates that user's rows, fetches them, and dedupes by
208
228
  `(table, id)` so you get a single combined timeline.
209
229
 
230
+ A password login can land on either account. If you know which one you want,
231
+ pass its ID to `login()`. On a mismatch the session is cleared and
232
+ `RenphoAPIError` is raised, so nothing reads the wrong account's data:
233
+
234
+ ```python
235
+ client.login(expected_user_id="5975813831868809088")
236
+ ```
237
+
210
238
  **How the lookup works.** Measurements are sharded across 24 tables,
211
239
  `measurements_info_0` through `measurements_info_23`, and a user's rows live in
212
240
  `measurements_info_<user_id % 24>`. `device/count` only names the table for the
@@ -426,7 +454,9 @@ renpho-api/
426
454
  │ ├── constants.py # API endpoints, device types, metrics, girth sites
427
455
  │ ├── crypto.py # AES encryption/decryption
428
456
  │ ├── export.py # JSON/CSV export helpers
429
- │ └── girth.py # Smart Tape Measure (body girth) helpers
430
- ├── tests/ # Unit tests
431
- └── .github/workflows/ # CI + PyPI release automation
457
+ │ ├── girth.py # Smart Tape Measure (body girth) helpers
458
+ │ └── py.typed # Marks the package as typed for type checkers
459
+ ├── tests/ # Unit tests (network access is blocked)
460
+ ├── Makefile # make test / make lint / make check
461
+ └── .github/workflows/ # CI (ruff + tests) and PyPI release automation
432
462
  ```
@@ -40,8 +40,9 @@ recent, and save everything to `renpho_data/` as JSON and CSV. If the account ha
40
40
  a smart tape measure it also writes `girth.json` / `girth.csv`; accounts without
41
41
  one simply report no girth records.
42
42
 
43
- Family members linked to the account are saved to `family_members.json`, and
44
- measurements are tagged with a `userName` field.
43
+ The CLI exports measurements for you and every family member on the account.
44
+ Each row is tagged with a `userName` field, and the family profiles are saved to
45
+ `family_members.json`.
45
46
 
46
47
  ### Environment variables
47
48
 
@@ -61,11 +62,15 @@ from renpho import RenphoClient
61
62
  client = RenphoClient("user@example.com", "password")
62
63
  client.login()
63
64
 
64
- # Fetch all measurements in one call
65
+ # All of your measurements, newest first. Family members who share the scale
66
+ # are not included (see "Family members" below).
65
67
  measurements = client.get_all_measurements()
66
68
 
67
69
  for m in measurements:
68
70
  print(m["weight"], m.get("bodyfat"), m.get("muscle"))
71
+
72
+ import renpho
73
+ print(renpho.__version__)
69
74
  ```
70
75
 
71
76
  ### Step-by-step control
@@ -80,11 +85,13 @@ client.login()
80
85
  device_info = client.get_device_info()
81
86
  scales = device_info["scale"]
82
87
 
83
- # Fetch from a specific scale table
88
+ # Fetch your rows from a scale table that lists you. The server only returns
89
+ # rows for the user id you pass, even on a table shared with family members.
84
90
  # Use get_body_composition_measurements() for scales with impedance sensors
85
- # (body fat, muscle, etc.) — the server-side count is unreliable for these.
86
- # Fall back to get_measurements() for weight-only scales.
87
- table = scales[0]
91
+ # (body fat, muscle, etc.) and fall back to get_measurements() when it comes
92
+ # back empty. Don't pass the table's "count" as a total: it counts every
93
+ # person on that table.
94
+ table = next(s for s in scales if str(client.user_id) in map(str, s["userIds"]))
88
95
  measurements = client.get_body_composition_measurements(
89
96
  table_name=table["tableName"],
90
97
  user_id=client.user_id,
@@ -93,7 +100,6 @@ if not measurements:
93
100
  measurements = client.get_measurements(
94
101
  table_name=table["tableName"],
95
102
  user_id=client.user_id,
96
- total_count=table["count"],
97
103
  )
98
104
 
99
105
  # Export
@@ -119,6 +125,18 @@ Each entry is a full profile dict. Its `id` matches the `userIds` listed per
119
125
  scale in `get_device_info()` and the `bUserId` field on measurement records.
120
126
  Compare IDs as strings, since they arrive as both `int` and `str`.
121
127
 
128
+ To fetch a family member's measurements, pass their `id`:
129
+
130
+ ```python
131
+ family = client.get_family_members()
132
+
133
+ # One person instead of you:
134
+ kid = client.get_all_measurements(profile_user_id=family[0]["id"])
135
+
136
+ # You plus everyone; bUserId says whose each row is:
137
+ everyone = client.get_all_measurements(extra_user_ids=[m["id"] for m in family])
138
+ ```
139
+
122
140
  ### Reading through a friend account
123
141
 
124
142
  Renpho allows one active session per account, so logging in with your main
@@ -181,6 +199,14 @@ measurements = client.get_all_measurements(
181
199
  The library locates that user's rows, fetches them, and dedupes by
182
200
  `(table, id)` so you get a single combined timeline.
183
201
 
202
+ A password login can land on either account. If you know which one you want,
203
+ pass its ID to `login()`. On a mismatch the session is cleared and
204
+ `RenphoAPIError` is raised, so nothing reads the wrong account's data:
205
+
206
+ ```python
207
+ client.login(expected_user_id="5975813831868809088")
208
+ ```
209
+
184
210
  **How the lookup works.** Measurements are sharded across 24 tables,
185
211
  `measurements_info_0` through `measurements_info_23`, and a user's rows live in
186
212
  `measurements_info_<user_id % 24>`. `device/count` only names the table for the
@@ -400,7 +426,9 @@ renpho-api/
400
426
  │ ├── constants.py # API endpoints, device types, metrics, girth sites
401
427
  │ ├── crypto.py # AES encryption/decryption
402
428
  │ ├── export.py # JSON/CSV export helpers
403
- │ └── girth.py # Smart Tape Measure (body girth) helpers
404
- ├── tests/ # Unit tests
405
- └── .github/workflows/ # CI + PyPI release automation
429
+ │ ├── girth.py # Smart Tape Measure (body girth) helpers
430
+ │ └── py.typed # Marks the package as typed for type checkers
431
+ ├── tests/ # Unit tests (network access is blocked)
432
+ ├── Makefile # make test / make lint / make check
433
+ └── .github/workflows/ # CI (ruff + tests) and PyPI release automation
406
434
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "renpho-api"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Unofficial Python client for the Renpho Health API — pull body composition data from Renpho smart scales and body girth data from smart tape measures."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -29,6 +29,7 @@ classifiers = [
29
29
  "Programming Language :: Python :: 3.13",
30
30
  "Programming Language :: Python :: 3.14",
31
31
  "Topic :: Software Development :: Libraries",
32
+ "Typing :: Typed",
32
33
  ]
33
34
  dependencies = [
34
35
  "requests>=2.28",
@@ -37,7 +38,9 @@ dependencies = [
37
38
 
38
39
  [project.optional-dependencies]
39
40
  dotenv = ["python-dotenv>=1.0"]
40
- dev = ["pytest>=7.0"]
41
+ # ruff is pinned exactly: new releases add lint rules and would otherwise
42
+ # break CI without any change here.
43
+ dev = ["pytest>=7.0", "ruff==0.17.3"]
41
44
 
42
45
  [project.urls]
43
46
  Repository = "https://github.com/danvaneijck/renpho-api"
@@ -50,6 +53,18 @@ renpho = "renpho.cli:main"
50
53
  [tool.setuptools]
51
54
  packages = ["renpho"]
52
55
 
56
+ [tool.setuptools.package-data]
57
+ renpho = ["py.typed"]
58
+
59
+ [tool.ruff]
60
+ target-version = "py310"
61
+
62
+ [tool.ruff.lint]
63
+ # pycodestyle, pyflakes, import order, bugbear, pyupgrade. Line length is
64
+ # left to review rather than enforced.
65
+ select = ["E", "W", "F", "I", "B", "UP"]
66
+ ignore = ["E501"]
67
+
53
68
  [dependency-groups]
54
69
  dev = [
55
70
  "pytest-cov>=7.1.0",
@@ -13,6 +13,9 @@ Quick start::
13
13
  girths = client.get_girth_measurements() # smart tape measure
14
14
  """
15
15
 
16
+ from importlib.metadata import PackageNotFoundError
17
+ from importlib.metadata import version as _version
18
+
16
19
  from .client import RenphoAPIError, RenphoClient
17
20
  from .export import (
18
21
  format_girth,
@@ -23,7 +26,13 @@ from .export import (
23
26
  )
24
27
  from .girth import build_girth_record, girth_date, normalize_girth
25
28
 
29
+ try:
30
+ __version__ = _version("renpho-api")
31
+ except PackageNotFoundError: # imported from a source tree that isn't installed
32
+ __version__ = "0+unknown"
33
+
26
34
  __all__ = [
35
+ "__version__",
27
36
  "RenphoClient",
28
37
  "RenphoAPIError",
29
38
  "format_measurement",
@@ -86,11 +86,18 @@ def main(argv: list[str] | None = None) -> None:
86
86
  )
87
87
  print(f" [{i}] table={table}, records={count}, users=[{users}]")
88
88
 
89
- # Step 3: Fetch measurements. get_all_measurements() tries the body
90
- # composition endpoint before the legacy one, so it also reads tables whose
91
- # count device/count reports as 0 (common for impedance scales).
92
- print("\nFetching measurements...")
93
- all_measurements = client.get_all_measurements(device_info=device_info)
89
+ # Step 3: Fetch measurements for you and everyone else on the account:
90
+ # family members, plus anyone listed on a scale (so a failed family lookup
91
+ # does not drop people). The server only returns the rows of the user id
92
+ # asked for, so each person is queried separately.
93
+ others: list = []
94
+ for uid in [m.get("id") for m in family] + [
95
+ u for scale in scales for u in scale.get("userIds", [])
96
+ ]:
97
+ if uid is not None and str(uid) != str(client.user_id) and str(uid) not in map(str, others):
98
+ others.append(uid)
99
+ print(f"\nFetching measurements for you and {len(others)} other profile(s)...")
100
+ all_measurements = client.get_all_measurements(others, device_info=device_info)
94
101
  for m in all_measurements:
95
102
  name = user_names.get(str(m.get("bUserId", client.user_id)))
96
103
  if name:
@@ -161,7 +168,7 @@ def _fetch_friend(client: RenphoClient, friend_id: str, output_dir: Path) -> Non
161
168
  return
162
169
 
163
170
  print(f"Total: {len(records)} day(s), newest {records[0]['day']}")
164
- for i, r in enumerate(records[:5]):
171
+ for r in records[:5]:
165
172
  print(f"\n{'=' * 55}")
166
173
  print(f" Day {r['day']}")
167
174
  print(f"{'=' * 55}")
@@ -1,7 +1,6 @@
1
1
  """Renpho API client for fetching scale measurements."""
2
2
 
3
3
  import json
4
- import sys
5
4
  import time
6
5
 
7
6
  import requests
@@ -170,13 +169,21 @@ class RenphoClient:
170
169
 
171
170
  # ----- public API -----
172
171
 
173
- def login(self) -> dict:
172
+ def login(self, *, expected_user_id=None) -> dict:
174
173
  """Authenticate and store the session token.
175
174
 
176
175
  Returns the full decrypted login response (includes user profile).
177
176
 
177
+ Args:
178
+ expected_user_id: If given, the login must land on this user id.
179
+ Some emails have two Renpho accounts (e.g. one left over from a
180
+ Google SSO migration), and a password login can reach the wrong
181
+ one. On a mismatch the session is cleared and an error raised,
182
+ so no later call reads the wrong account's data.
183
+
178
184
  Raises:
179
- RenphoAPIError: If the API rejects the credentials.
185
+ RenphoAPIError: If the API rejects the credentials, or the account
186
+ is not *expected_user_id*.
180
187
  requests.HTTPError: On transport-level failures.
181
188
  """
182
189
  login_payload = {
@@ -212,6 +219,15 @@ class RenphoClient:
212
219
  if not self.token:
213
220
  raise RenphoAPIError("Login", None, "No token in login response")
214
221
 
222
+ if expected_user_id is not None and str(self.user_id) != str(expected_user_id):
223
+ actual = self.user_id
224
+ self.token = self.user_id = self.user_info = None
225
+ raise RenphoAPIError(
226
+ "Login",
227
+ None,
228
+ f"logged in as user {actual}, expected {expected_user_id}",
229
+ )
230
+
215
231
  return user_data
216
232
 
217
233
  def get_device_info(self) -> dict:
@@ -248,17 +264,31 @@ class RenphoClient:
248
264
  return [v for v in value if v is not None]
249
265
  return [value]
250
266
 
251
- def _scale_owner(self, user_ids: list):
252
- """The id to query a scale table with.
267
+ @classmethod
268
+ def _tables_listing(cls, scales: list, user_id) -> list[str]:
269
+ """Names of the scale tables in *scales* whose ``userIds`` include *user_id*.
270
+
271
+ IDs arrive as both int and str, so they are compared as strings.
272
+ """
273
+ tables: list[str] = []
274
+ for scale in scales:
275
+ table = scale.get("tableName") if isinstance(scale, dict) else None
276
+ if not table or table in tables:
277
+ continue
278
+ if any(str(u) == str(user_id) for u in cls._normalize_user_ids(scale.get("userIds"))):
279
+ tables.append(table)
280
+ return tables
281
+
282
+ def _fetch_table(self, table: str, user_id) -> list[dict]:
283
+ """All of *user_id*'s rows in *table*: body composition endpoint, then legacy.
253
284
 
254
- The logged-in user if the scale lists them, otherwise the first listed
255
- id. IDs arrive as both int and str, so they are compared as strings: a
256
- plain ``in`` check silently fell through to someone else's id whenever
257
- the types differed.
285
+ Some accounts answer empty on the body composition endpoint while the
286
+ legacy one holds every row, so an empty first answer is not the end.
258
287
  """
259
- if not user_ids or any(str(u) == str(self.user_id) for u in user_ids):
260
- return self.user_id
261
- return user_ids[0]
288
+ rows = self.get_body_composition_measurements(table, user_id)
289
+ if not rows:
290
+ rows = self.get_measurements(table, user_id)
291
+ return rows
262
292
 
263
293
  @staticmethod
264
294
  def _take_new(records: list[dict], seen: set) -> list[dict]:
@@ -575,31 +605,37 @@ class RenphoClient:
575
605
  extra_user_ids: list | None = None,
576
606
  *,
577
607
  device_info: dict | None = None,
608
+ profile_user_id=None,
578
609
  ) -> list[dict]:
579
- """High-level helper: fetch device info then pull all measurements.
610
+ """Fetch all measurements for one person, plus any *extra_user_ids*.
611
+
612
+ The person is the logged-in user unless *profile_user_id* names someone
613
+ else. The server filters every table by the user id in the query, so a
614
+ scale shared with family members only returns the rows of the person
615
+ asked for; their rows carry that id in ``bUserId``.
580
616
 
581
- Tries the body composition endpoint first (used by impedance scales).
582
- Falls back to the basic measurements endpoint for weight-only scales.
583
- The server-side count in device info is unreliable for body composition
584
- scales (often reports 0), so this method always attempts a fetch.
617
+ Each table :meth:`get_device_info` lists for the person is read, from
618
+ the body composition endpoint first and the legacy one if that comes
619
+ back empty. The device count is not used to decide, because it is
620
+ unreliable for body composition scales (often 0).
585
621
 
586
622
  Calls :meth:`login` first if no token is set.
587
623
 
588
624
  Args:
589
- extra_user_ids: Additional user IDs to fetch measurements for. The
590
- Renpho API allows a logged-in user to read measurements belonging
591
- to other linked accounts (e.g. a separate account from before a
592
- Google SSO migration). Each id is probed against all known
593
- measurement tables. Pass these when you have multiple Renpho
594
- accounts associated with the same physical scale.
625
+ extra_user_ids: More people to include, e.g. family members
626
+ (``[m["id"] for m in client.get_family_members()]``) or another
627
+ account on the same email (such as one left over from a Google
628
+ SSO migration). Tables that device info lists for an id are used
629
+ directly; otherwise they are located with
630
+ :meth:`discover_user_tables`.
595
631
  device_info: A result of :meth:`get_device_info` to reuse instead
596
632
  of fetching it again.
633
+ profile_user_id: Fetch this person instead of the logged-in user,
634
+ e.g. a family member's ``id`` from :meth:`get_family_members`.
597
635
 
598
636
  Returns:
599
- List of measurement dicts sorted by timestamp (newest first). When
600
- *extra_user_ids* is used, records are deduped by ``(table, id)`` —
601
- the same table can be reached both from device info and from
602
- probing, but row ids are only unique within a table.
637
+ Measurement dicts sorted newest first, deduped by ``(table, id)``
638
+ (row ids are only unique within a table).
603
639
  """
604
640
  if not self.token:
605
641
  self.login()
@@ -608,47 +644,36 @@ class RenphoClient:
608
644
  device_info = self.get_device_info()
609
645
  scales = device_info.get("scale") or []
610
646
 
647
+ primary = self.user_id if profile_user_id is None else profile_user_id
648
+
611
649
  fetched: set = set()
650
+ done: set = set()
612
651
  all_measurements: list[dict] = []
613
652
 
614
- def collect(table_name, uid, records):
615
- """Add *records*, skipping rows already seen from the same table."""
616
- for m in records:
617
- rid = m.get("id")
618
- key = (table_name, rid)
619
- if rid is not None:
620
- if key in fetched:
621
- continue
622
- fetched.add(key)
623
- all_measurements.append(m)
624
-
625
- for scale in scales:
626
- table_name = scale.get("tableName")
627
- count = scale.get("count") or 0
628
- user_ids = self._normalize_user_ids(scale.get("userIds"))
629
-
630
- if not table_name:
653
+ for uid in [primary, *(extra_user_ids or [])]:
654
+ if uid is None or str(uid) in done:
631
655
  continue
632
-
633
- uid = self._scale_owner(user_ids)
634
-
635
- # Try body composition endpoint first; it handles both newer
636
- # impedance scales and cases where count is incorrectly zero.
637
- measurements = self.get_body_composition_measurements(table_name, uid)
638
- if not measurements and count > 0:
639
- measurements = self.get_measurements(table_name, uid, count)
640
-
641
- collect(table_name, uid, measurements)
642
-
643
- for extra_uid in extra_user_ids or []:
644
- for table in self.discover_user_tables(extra_uid):
645
- # Same two-endpoint fallback as the main loop above: accounts
646
- # that answer empty on the body composition endpoint still have
647
- # their rows on the legacy one.
648
- measurements = self.get_body_composition_measurements(table, extra_uid)
649
- if not measurements:
650
- measurements = self.get_measurements(table, extra_uid)
651
- collect(table, extra_uid, measurements)
656
+ done.add(str(uid))
657
+
658
+ tables = self._tables_listing(scales, uid)
659
+ if not tables:
660
+ if uid is primary:
661
+ # Not on any scale: try the shard their id maps to, without
662
+ # sweeping all 24 tables for someone who may have no data.
663
+ shard = self.measurement_table_for(uid)
664
+ tables = [shard] if shard else []
665
+ else:
666
+ tables = self.discover_user_tables(uid)
667
+
668
+ for table in tables:
669
+ for m in self._fetch_table(table, uid):
670
+ rid = m.get("id")
671
+ if rid is not None:
672
+ key = (table, str(rid))
673
+ if key in fetched:
674
+ continue
675
+ fetched.add(key)
676
+ all_measurements.append(m)
652
677
 
653
678
  all_measurements.sort(
654
679
  key=lambda m: m.get("timeStamp", 0) or 0,
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: renpho-api
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Unofficial Python client for the Renpho Health API — pull body composition data from Renpho smart scales and body girth data from smart tape measures.
5
5
  Author: danvaneijck
6
6
  License-Expression: MIT
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
17
  Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Typing :: Typed
18
19
  Requires-Python: >=3.10
19
20
  Description-Content-Type: text/markdown
20
21
  Requires-Dist: requests>=2.28
@@ -23,6 +24,7 @@ Provides-Extra: dotenv
23
24
  Requires-Dist: python-dotenv>=1.0; extra == "dotenv"
24
25
  Provides-Extra: dev
25
26
  Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: ruff==0.17.3; extra == "dev"
26
28
 
27
29
  # renpho-api
28
30
 
@@ -66,8 +68,9 @@ recent, and save everything to `renpho_data/` as JSON and CSV. If the account ha
66
68
  a smart tape measure it also writes `girth.json` / `girth.csv`; accounts without
67
69
  one simply report no girth records.
68
70
 
69
- Family members linked to the account are saved to `family_members.json`, and
70
- measurements are tagged with a `userName` field.
71
+ The CLI exports measurements for you and every family member on the account.
72
+ Each row is tagged with a `userName` field, and the family profiles are saved to
73
+ `family_members.json`.
71
74
 
72
75
  ### Environment variables
73
76
 
@@ -87,11 +90,15 @@ from renpho import RenphoClient
87
90
  client = RenphoClient("user@example.com", "password")
88
91
  client.login()
89
92
 
90
- # Fetch all measurements in one call
93
+ # All of your measurements, newest first. Family members who share the scale
94
+ # are not included (see "Family members" below).
91
95
  measurements = client.get_all_measurements()
92
96
 
93
97
  for m in measurements:
94
98
  print(m["weight"], m.get("bodyfat"), m.get("muscle"))
99
+
100
+ import renpho
101
+ print(renpho.__version__)
95
102
  ```
96
103
 
97
104
  ### Step-by-step control
@@ -106,11 +113,13 @@ client.login()
106
113
  device_info = client.get_device_info()
107
114
  scales = device_info["scale"]
108
115
 
109
- # Fetch from a specific scale table
116
+ # Fetch your rows from a scale table that lists you. The server only returns
117
+ # rows for the user id you pass, even on a table shared with family members.
110
118
  # Use get_body_composition_measurements() for scales with impedance sensors
111
- # (body fat, muscle, etc.) — the server-side count is unreliable for these.
112
- # Fall back to get_measurements() for weight-only scales.
113
- table = scales[0]
119
+ # (body fat, muscle, etc.) and fall back to get_measurements() when it comes
120
+ # back empty. Don't pass the table's "count" as a total: it counts every
121
+ # person on that table.
122
+ table = next(s for s in scales if str(client.user_id) in map(str, s["userIds"]))
114
123
  measurements = client.get_body_composition_measurements(
115
124
  table_name=table["tableName"],
116
125
  user_id=client.user_id,
@@ -119,7 +128,6 @@ if not measurements:
119
128
  measurements = client.get_measurements(
120
129
  table_name=table["tableName"],
121
130
  user_id=client.user_id,
122
- total_count=table["count"],
123
131
  )
124
132
 
125
133
  # Export
@@ -145,6 +153,18 @@ Each entry is a full profile dict. Its `id` matches the `userIds` listed per
145
153
  scale in `get_device_info()` and the `bUserId` field on measurement records.
146
154
  Compare IDs as strings, since they arrive as both `int` and `str`.
147
155
 
156
+ To fetch a family member's measurements, pass their `id`:
157
+
158
+ ```python
159
+ family = client.get_family_members()
160
+
161
+ # One person instead of you:
162
+ kid = client.get_all_measurements(profile_user_id=family[0]["id"])
163
+
164
+ # You plus everyone; bUserId says whose each row is:
165
+ everyone = client.get_all_measurements(extra_user_ids=[m["id"] for m in family])
166
+ ```
167
+
148
168
  ### Reading through a friend account
149
169
 
150
170
  Renpho allows one active session per account, so logging in with your main
@@ -207,6 +227,14 @@ measurements = client.get_all_measurements(
207
227
  The library locates that user's rows, fetches them, and dedupes by
208
228
  `(table, id)` so you get a single combined timeline.
209
229
 
230
+ A password login can land on either account. If you know which one you want,
231
+ pass its ID to `login()`. On a mismatch the session is cleared and
232
+ `RenphoAPIError` is raised, so nothing reads the wrong account's data:
233
+
234
+ ```python
235
+ client.login(expected_user_id="5975813831868809088")
236
+ ```
237
+
210
238
  **How the lookup works.** Measurements are sharded across 24 tables,
211
239
  `measurements_info_0` through `measurements_info_23`, and a user's rows live in
212
240
  `measurements_info_<user_id % 24>`. `device/count` only names the table for the
@@ -426,7 +454,9 @@ renpho-api/
426
454
  │ ├── constants.py # API endpoints, device types, metrics, girth sites
427
455
  │ ├── crypto.py # AES encryption/decryption
428
456
  │ ├── export.py # JSON/CSV export helpers
429
- │ └── girth.py # Smart Tape Measure (body girth) helpers
430
- ├── tests/ # Unit tests
431
- └── .github/workflows/ # CI + PyPI release automation
457
+ │ ├── girth.py # Smart Tape Measure (body girth) helpers
458
+ │ └── py.typed # Marks the package as typed for type checkers
459
+ ├── tests/ # Unit tests (network access is blocked)
460
+ ├── Makefile # make test / make lint / make check
461
+ └── .github/workflows/ # CI (ruff + tests) and PyPI release automation
432
462
  ```
@@ -7,6 +7,7 @@ renpho/constants.py
7
7
  renpho/crypto.py
8
8
  renpho/export.py
9
9
  renpho/girth.py
10
+ renpho/py.typed
10
11
  renpho_api.egg-info/PKG-INFO
11
12
  renpho_api.egg-info/SOURCES.txt
12
13
  renpho_api.egg-info/dependency_links.txt
@@ -19,4 +20,5 @@ tests/test_crypto.py
19
20
  tests/test_export.py
20
21
  tests/test_friends.py
21
22
  tests/test_girth.py
22
- tests/test_hardening.py
23
+ tests/test_hardening.py
24
+ tests/test_public_api.py
@@ -3,6 +3,7 @@ pycryptodome>=3.15
3
3
 
4
4
  [dev]
5
5
  pytest>=7.0
6
+ ruff==0.17.3
6
7
 
7
8
  [dotenv]
8
9
  python-dotenv>=1.0
@@ -1,6 +1,5 @@
1
1
  """Tests for renpho.client — RenphoClient unit tests."""
2
2
 
3
- import json
4
3
  from unittest.mock import MagicMock, patch
5
4
 
6
5
  import pytest
@@ -13,9 +12,8 @@ from renpho.constants import (
13
12
  MEASUREMENT_TABLE_NAMES,
14
13
  PLATFORM,
15
14
  REQUEST_TIMEOUT,
16
- SUCCESS_CODES,
17
15
  )
18
- from renpho.crypto import aes_decrypt, encrypt_request
16
+ from renpho.crypto import encrypt_request
19
17
 
20
18
 
21
19
  class TestCheckResponse:
@@ -317,7 +315,9 @@ class TestGetAllMeasurementsCountZero:
317
315
  patch.object(client, "get_measurements", return_value=records) as mock_get,
318
316
  ):
319
317
  result = client.get_all_measurements()
320
- mock_get.assert_called_once_with("measurements_info_8", 123, 5)
318
+ # No total is passed: device/count's count covers every user in the
319
+ # table, so it is not this user's total.
320
+ mock_get.assert_called_once_with("measurements_info_8", 123)
321
321
  assert result == records
322
322
 
323
323
 
@@ -513,14 +513,17 @@ class TestGetAllMeasurementsExtraUsers:
513
513
  device_info = {"scale": []}
514
514
  legacy = [{"id": 7, "weight": 80.0, "timeStamp": 2000}]
515
515
 
516
+ def legacy_rows(table, uid, *args, **kwargs):
517
+ return legacy if uid == "999" else []
518
+
516
519
  with (
517
520
  patch.object(client, "get_device_info", return_value=device_info),
518
521
  patch.object(client, "get_body_composition_measurements", return_value=[]),
519
- patch.object(client, "get_measurements", return_value=legacy) as mock_legacy,
522
+ patch.object(client, "get_measurements", side_effect=legacy_rows) as mock_legacy,
520
523
  patch.object(client, "discover_user_tables", return_value=["measurements_info_9"]),
521
524
  ):
522
525
  result = client.get_all_measurements(extra_user_ids=["999"])
523
- mock_legacy.assert_called_once_with("measurements_info_9", "999")
526
+ mock_legacy.assert_any_call("measurements_info_9", "999")
524
527
  assert result == legacy
525
528
 
526
529
  def test_same_table_reached_twice_is_deduped(self):
@@ -11,7 +11,6 @@ from renpho.crypto import (
11
11
  encrypt_request,
12
12
  )
13
13
 
14
-
15
14
  # Produced independently with OpenSSL, so a change in the crypto library that
16
15
  # still round-trips but no longer matches what Renpho's server expects fails:
17
16
  # printf '%s' '{"pageNum":1,"pageSize":50}' \
@@ -1,7 +1,6 @@
1
1
  """Tests for renpho.export — formatting and file export."""
2
2
 
3
3
  import json
4
- from pathlib import Path
5
4
 
6
5
  from renpho.export import format_measurement, format_timestamp, save_csv, save_json
7
6
 
@@ -6,7 +6,7 @@ import pytest
6
6
  import requests
7
7
 
8
8
  from renpho.cli import main
9
- from renpho.client import RenphoClient
9
+ from renpho.client import RenphoAPIError, RenphoClient
10
10
  from renpho.crypto import encrypt_request
11
11
 
12
12
 
@@ -43,37 +43,108 @@ class TestUserIdsNormalization:
43
43
  assert client.get_device_info()["scale"][0]["userIds"] == [42]
44
44
 
45
45
 
46
- class TestScaleOwner:
47
- def test_string_ids_still_match_int_login_id(self):
48
- """A list of str ids must not fall through to someone else's id."""
49
- client = _client(user_id=42)
50
- assert client._scale_owner(["7", "42"]) == 42
46
+ class TestTablesListing:
47
+ def test_string_ids_match_int_user_id(self):
48
+ scales = [{"tableName": "t", "userIds": ["7", "42"]}]
49
+ assert RenphoClient._tables_listing(scales, 42) == ["t"]
50
+
51
+ def test_int_ids_match_string_user_id(self):
52
+ scales = [{"tableName": "t", "userIds": [7, 42]}]
53
+ assert RenphoClient._tables_listing(scales, "42") == ["t"]
54
+
55
+ def test_only_tables_listing_the_user(self):
56
+ scales = [
57
+ {"tableName": "a", "userIds": [42]},
58
+ {"tableName": "b", "userIds": [7]},
59
+ {"tableName": "c", "userIds": 42},
60
+ ]
61
+ assert RenphoClient._tables_listing(scales, 42) == ["a", "c"]
62
+
63
+
64
+ # Mirrors a live account: a family member shares the owner's table, and two
65
+ # more tables list only family members. The server returns only the rows of
66
+ # the user id queried.
67
+ SHARED = {"scale": [
68
+ {"tableName": "measurements_info_8", "count": 33, "userIds": [9, 42]},
69
+ {"tableName": "measurements_info_16", "count": 3, "userIds": [16, 40]},
70
+ ]}
71
+
72
+
73
+ def _rows_for(table, uid, *args, **kwargs):
74
+ return [{"id": f"{table}-{uid}", "bUserId": uid, "timeStamp": int(str(uid))}]
51
75
 
52
- def test_int_ids_match_string_login_id(self):
53
- client = _client(user_id="42")
54
- assert client._scale_owner([7, 42]) == "42"
55
76
 
56
- def test_falls_back_to_first_listed_id(self):
57
- assert _client(user_id=42)._scale_owner(["7", "8"]) == "7"
77
+ class TestProfiles:
78
+ def _fetch(self, client, **kwargs):
79
+ with patch.object(client, "get_body_composition_measurements", return_value=[]), \
80
+ patch.object(client, "get_measurements", side_effect=_rows_for) as legacy:
81
+ rows = client.get_all_measurements(device_info=SHARED, **kwargs)
82
+ return rows, [c.args[:2] for c in legacy.call_args_list]
58
83
 
59
- def test_no_ids_means_logged_in_user(self):
60
- assert _client(user_id=42)._scale_owner([]) == 42
84
+ def test_default_returns_only_the_logged_in_user(self):
85
+ """A table that doesn't list you must not fall back to someone else."""
86
+ rows, calls = self._fetch(_client(user_id=42))
87
+ assert calls == [("measurements_info_8", 42)]
88
+ assert {r["bUserId"] for r in rows} == {42}
61
89
 
62
- def test_get_all_measurements_queries_logged_in_user(self):
90
+ def test_profile_user_id_fetches_that_person(self):
91
+ rows, calls = self._fetch(_client(user_id=42), profile_user_id=16)
92
+ assert calls == [("measurements_info_16", 16)]
93
+ assert {r["bUserId"] for r in rows} == {16}
94
+
95
+ def test_extra_user_ids_listed_on_scales_skip_discovery(self):
63
96
  client = _client(user_id=42)
64
- info = {"scale": [{"tableName": "t", "count": 1, "userIds": ["7", "42"]}]}
65
- with patch.object(client, "get_body_composition_measurements", return_value=[]) as bc, \
66
- patch.object(client, "get_measurements", return_value=[]):
67
- client.get_all_measurements(device_info=info)
68
- assert bc.call_args.args == ("t", 42)
97
+ with patch.object(client, "discover_user_tables") as discover:
98
+ rows, calls = self._fetch(client, extra_user_ids=[9, "16", 40])
99
+ discover.assert_not_called()
100
+ assert {str(r["bUserId"]) for r in rows} == {"42", "9", "16", "40"}
101
+ assert ("measurements_info_8", 9) in calls
102
+
103
+ def test_duplicate_ids_are_fetched_once(self):
104
+ rows, calls = self._fetch(_client(user_id=42), extra_user_ids=["42", 42])
105
+ assert calls == [("measurements_info_8", 42)]
106
+
107
+ def test_unlisted_user_tries_their_computed_shard_only(self):
108
+ client = _client(user_id=50) # 50 % 24 == 2
109
+ with patch.object(client, "discover_user_tables") as discover:
110
+ rows, calls = self._fetch(client)
111
+ discover.assert_not_called()
112
+ assert calls == [("measurements_info_2", 50)]
69
113
 
70
114
  def test_null_count_does_not_crash(self):
71
115
  client = _client()
72
116
  info = {"scale": [{"tableName": "t", "count": None, "userIds": [42]}]}
73
- with patch.object(client, "get_body_composition_measurements", return_value=[]):
117
+ with patch.object(client, "get_body_composition_measurements", return_value=[]), \
118
+ patch.object(client, "get_measurements", return_value=[]):
74
119
  assert client.get_all_measurements(device_info=info) == []
75
120
 
76
121
 
122
+ class TestExpectedUserId:
123
+ @staticmethod
124
+ def _login(client, user_id, **kwargs):
125
+ response = _encrypted({"login": {"token": "tok", "id": user_id}})
126
+ with patch.object(client, "_post", return_value=response):
127
+ return client.login(**kwargs)
128
+
129
+ def test_matching_id_logs_in(self):
130
+ client = RenphoClient("a@b.com", "p")
131
+ self._login(client, 42, expected_user_id="42")
132
+ assert client.token == "tok"
133
+
134
+ def test_mismatch_raises_and_clears_the_session(self):
135
+ client = RenphoClient("a@b.com", "p")
136
+ with pytest.raises(RenphoAPIError, match="expected 7"):
137
+ self._login(client, 42, expected_user_id=7)
138
+ assert client.token is None
139
+ assert client.user_id is None
140
+ assert client.user_info is None
141
+
142
+ def test_not_checked_by_default(self):
143
+ client = RenphoClient("a@b.com", "p")
144
+ self._login(client, 42)
145
+ assert client.user_id == 42
146
+
147
+
77
148
  class TestRepeatedPages:
78
149
  """A server that ignores pageNum must not cause an endless loop."""
79
150
 
@@ -0,0 +1,70 @@
1
+ """Public API contract: removing or renaming any of these is a breaking change.
2
+
3
+ Adding to the API is fine. If a test here fails because something was removed
4
+ on purpose, that change needs a major version bump and a release note.
5
+ """
6
+
7
+ import inspect
8
+
9
+ import renpho
10
+ from renpho import RenphoClient
11
+
12
+ EXPORTS = {
13
+ "__version__",
14
+ "RenphoClient",
15
+ "RenphoAPIError",
16
+ "format_measurement",
17
+ "format_timestamp",
18
+ "save_csv",
19
+ "save_json",
20
+ "build_girth_record",
21
+ "format_girth",
22
+ "girth_date",
23
+ "normalize_girth",
24
+ }
25
+
26
+ # method name -> keyword arguments callers rely on
27
+ CLIENT_METHODS = {
28
+ "__init__": {"email", "password", "debug", "timeout"},
29
+ "login": {"expected_user_id"},
30
+ "get_device_info": set(),
31
+ "get_family_members": set(),
32
+ "get_measurements": {"table_name", "user_id", "total_count", "page_size"},
33
+ "get_body_composition_measurements": {"table_name", "user_id", "page_size"},
34
+ "get_all_measurements": {"extra_user_ids", "device_info", "profile_user_id"},
35
+ "measurement_table_for": {"user_id"},
36
+ "discover_user_tables": {"user_id", "tables"},
37
+ "get_girth_measurements": {"page_size"},
38
+ "upload_girth_measurements": {"records", "time_zone", "zone_id", "device_id", "platform"},
39
+ "get_friends": {"page_size"},
40
+ "get_friend_measure_days": {"friend_id", "time_zone"},
41
+ "get_friend_summary": {"friend_id", "param"},
42
+ "get_friend_trend": {"friend_id", "param", "time_type", "end_time", "time_zone"},
43
+ "get_friend_measurements": {"friend_id", "params", "time_type", "end_time", "time_zone"},
44
+ "local_utc_offset_hours": set(),
45
+ }
46
+
47
+
48
+ def test_package_exports():
49
+ missing = EXPORTS - set(renpho.__all__)
50
+ assert not missing, f"removed from renpho.__all__: {sorted(missing)}"
51
+ for name in EXPORTS:
52
+ assert hasattr(renpho, name), name
53
+
54
+
55
+ def test_version_is_a_string():
56
+ assert isinstance(renpho.__version__, str) and renpho.__version__
57
+
58
+
59
+ def test_client_methods_and_arguments():
60
+ for name, kwargs in CLIENT_METHODS.items():
61
+ method = getattr(RenphoClient, name, None)
62
+ assert callable(method), f"RenphoClient.{name} was removed"
63
+ params = set(inspect.signature(method).parameters)
64
+ missing = kwargs - params
65
+ assert not missing, f"RenphoClient.{name} lost arguments: {sorted(missing)}"
66
+
67
+
68
+ def test_api_error_attributes():
69
+ err = renpho.RenphoAPIError("Login", -114, "Decryption failed")
70
+ assert (err.context, err.code, err.msg) == ("Login", -114, "Decryption failed")
File without changes
File without changes
File without changes
File without changes