renpho-api 0.2.1__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.2.1 → renpho_api-0.4.0}/PKG-INFO +107 -12
  2. {renpho_api-0.2.1 → renpho_api-0.4.0}/README.md +104 -11
  3. {renpho_api-0.2.1 → renpho_api-0.4.0}/pyproject.toml +17 -2
  4. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/__init__.py +9 -0
  5. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/cli.py +71 -26
  6. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/client.py +351 -80
  7. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/constants.py +12 -0
  8. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/export.py +3 -1
  9. renpho_api-0.4.0/renpho/py.typed +0 -0
  10. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/PKG-INFO +107 -12
  11. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/SOURCES.txt +5 -1
  12. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/requires.txt +1 -0
  13. {renpho_api-0.2.1 → renpho_api-0.4.0}/tests/test_client.py +52 -6
  14. {renpho_api-0.2.1 → renpho_api-0.4.0}/tests/test_crypto.py +13 -0
  15. {renpho_api-0.2.1 → renpho_api-0.4.0}/tests/test_export.py +5 -1
  16. renpho_api-0.4.0/tests/test_friends.py +168 -0
  17. renpho_api-0.4.0/tests/test_hardening.py +218 -0
  18. renpho_api-0.4.0/tests/test_public_api.py +70 -0
  19. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/crypto.py +0 -0
  20. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho/girth.py +0 -0
  21. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/dependency_links.txt +0 -0
  22. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/entry_points.txt +0 -0
  23. {renpho_api-0.2.1 → renpho_api-0.4.0}/renpho_api.egg-info/top_level.txt +0 -0
  24. {renpho_api-0.2.1 → renpho_api-0.4.0}/setup.cfg +0 -0
  25. {renpho_api-0.2.1 → renpho_api-0.4.0}/tests/test_constants.py +0 -0
  26. {renpho_api-0.2.1 → 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.2.1
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,6 +68,10 @@ 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
 
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`.
74
+
69
75
  ### Environment variables
70
76
 
71
77
  | Variable | Required | Description |
@@ -74,6 +80,7 @@ one simply report no girth records.
74
80
  | `RENPHO_PASSWORD` | Yes | Your Renpho account password |
75
81
  | `RENPHO_DEBUG` | No | Set to `1` to print API request/response details |
76
82
  | `RENPHO_OUTPUT_DIR` | No | Output directory (default: `renpho_data`) |
83
+ | `RENPHO_FRIEND_ID` | No | Read this friend's daily data instead of your own (see [Reading through a friend account](#reading-through-a-friend-account)) |
77
84
 
78
85
  ## Library Usage
79
86
 
@@ -83,11 +90,15 @@ from renpho import RenphoClient
83
90
  client = RenphoClient("user@example.com", "password")
84
91
  client.login()
85
92
 
86
- # 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).
87
95
  measurements = client.get_all_measurements()
88
96
 
89
97
  for m in measurements:
90
98
  print(m["weight"], m.get("bodyfat"), m.get("muscle"))
99
+
100
+ import renpho
101
+ print(renpho.__version__)
91
102
  ```
92
103
 
93
104
  ### Step-by-step control
@@ -102,11 +113,13 @@ client.login()
102
113
  device_info = client.get_device_info()
103
114
  scales = device_info["scale"]
104
115
 
105
- # 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.
106
118
  # Use get_body_composition_measurements() for scales with impedance sensors
107
- # (body fat, muscle, etc.) — the server-side count is unreliable for these.
108
- # Fall back to get_measurements() for weight-only scales.
109
- 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"]))
110
123
  measurements = client.get_body_composition_measurements(
111
124
  table_name=table["tableName"],
112
125
  user_id=client.user_id,
@@ -115,7 +128,6 @@ if not measurements:
115
128
  measurements = client.get_measurements(
116
129
  table_name=table["tableName"],
117
130
  user_id=client.user_id,
118
- total_count=table["count"],
119
131
  )
120
132
 
121
133
  # Export
@@ -123,6 +135,79 @@ save_json(measurements, "my_data.json")
123
135
  save_csv(measurements, "my_data.csv")
124
136
  ```
125
137
 
138
+ ### Family members (sub-users)
139
+
140
+ Profiles added under your account in the app (e.g. family members sharing a
141
+ scale) can be listed with `get_family_members()`. The logged-in user is not part
142
+ of that list; their own profile is in `client.user_info`.
143
+
144
+ ```python
145
+ names = {str(client.user_id): client.user_info["accountName"]}
146
+ for member in client.get_family_members():
147
+ names[str(member["id"])] = member["accountName"]
148
+
149
+ # {'5981614576857776000': 'Alice', '5991064042346217344': 'Bob'}
150
+ ```
151
+
152
+ Each entry is a full profile dict. Its `id` matches the `userIds` listed per
153
+ scale in `get_device_info()` and the `bUserId` field on measurement records.
154
+ Compare IDs as strings, since they arrive as both `int` and `str`.
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
+
168
+ ### Reading through a friend account
169
+
170
+ Renpho allows one active session per account, so logging in with your main
171
+ account signs the phone app out. To sync without that, read your data through
172
+ Renpho's friends feature from a second account:
173
+
174
+ 1. Create a second Renpho account with an email and password. An account
175
+ created with "Sign in with Google" or Apple has no password and can't log in
176
+ through the API.
177
+ 2. In the Renpho app, add the second account as a friend of your main account
178
+ and accept the request.
179
+ 3. Log in as the second account and read your main account's data:
180
+
181
+ ```python
182
+ client = RenphoClient("second@example.com", "password")
183
+ friend = client.get_friends()[0] # {"userId", "accountName", ...}
184
+
185
+ days = client.get_friend_measurements(friend["userId"])
186
+ # [{"day": "2026-11-02", "timeStamp": ..., "weight": 79.5, "bodyfat": 20.1, ...}, ...]
187
+ ```
188
+
189
+ With the CLI, set `RENPHO_FRIEND_ID` to the friend's `userId`. It writes
190
+ `friend_daily.json` and `friend_daily.csv` instead of the usual files.
191
+
192
+ `get_friend_trend(friend_id, param)` returns the daily points for a single
193
+ parameter, and `get_friend_summary()` and `get_friend_measure_days()` return
194
+ the server's raw responses.
195
+
196
+ Limits of the friend endpoints:
197
+
198
+ - One value per day (the last weigh-in that day).
199
+ - Body composition values only on days the scale measured them.
200
+ - One call covers a limited window. For older data, move `end_time` (unix
201
+ seconds) back.
202
+ - No segmental or girth data.
203
+ - Days are grouped by a whole-hour UTC offset, by default this machine's
204
+ (`time_zone=` to override).
205
+
206
+ This approach was worked out in
207
+ [#14](https://github.com/danvaneijck/renpho-api/issues/14), with a reference
208
+ implementation at
209
+ [DawidKrynski/renpho-friends](https://github.com/DawidKrynski/renpho-friends).
210
+
126
211
  ### Multiple Renpho accounts on one email
127
212
 
128
213
  Some users end up with **two Renpho accounts under the same email** — for
@@ -142,6 +227,14 @@ measurements = client.get_all_measurements(
142
227
  The library locates that user's rows, fetches them, and dedupes by
143
228
  `(table, id)` so you get a single combined timeline.
144
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
+
145
238
  **How the lookup works.** Measurements are sharded across 24 tables,
146
239
  `measurements_info_0` through `measurements_info_23`, and a user's rows live in
147
240
  `measurements_info_<user_id % 24>`. `device/count` only names the table for the
@@ -204,8 +297,8 @@ Requests time out after 10 s to connect and 30 s to read by default. Pass
204
297
  password, so they cannot log in through the API.
205
298
  - **The phone app logs you out after a sync.** Renpho allows one active
206
299
  session per account, so every `login()` ends the app's session. If you run
207
- scheduled syncs, run them less often or use a separate account
208
- (see [#14](https://github.com/danvaneijck/renpho-api/issues/14)).
300
+ scheduled syncs, read your data from a second account instead (see
301
+ [Reading through a friend account](#reading-through-a-friend-account)).
209
302
 
210
303
  ## Smart Tape Measure (body girth)
211
304
 
@@ -361,7 +454,9 @@ renpho-api/
361
454
  │ ├── constants.py # API endpoints, device types, metrics, girth sites
362
455
  │ ├── crypto.py # AES encryption/decryption
363
456
  │ ├── export.py # JSON/CSV export helpers
364
- │ └── girth.py # Smart Tape Measure (body girth) helpers
365
- ├── tests/ # Unit tests
366
- └── .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
367
462
  ```
@@ -40,6 +40,10 @@ 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
+ 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`.
46
+
43
47
  ### Environment variables
44
48
 
45
49
  | Variable | Required | Description |
@@ -48,6 +52,7 @@ one simply report no girth records.
48
52
  | `RENPHO_PASSWORD` | Yes | Your Renpho account password |
49
53
  | `RENPHO_DEBUG` | No | Set to `1` to print API request/response details |
50
54
  | `RENPHO_OUTPUT_DIR` | No | Output directory (default: `renpho_data`) |
55
+ | `RENPHO_FRIEND_ID` | No | Read this friend's daily data instead of your own (see [Reading through a friend account](#reading-through-a-friend-account)) |
51
56
 
52
57
  ## Library Usage
53
58
 
@@ -57,11 +62,15 @@ from renpho import RenphoClient
57
62
  client = RenphoClient("user@example.com", "password")
58
63
  client.login()
59
64
 
60
- # 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).
61
67
  measurements = client.get_all_measurements()
62
68
 
63
69
  for m in measurements:
64
70
  print(m["weight"], m.get("bodyfat"), m.get("muscle"))
71
+
72
+ import renpho
73
+ print(renpho.__version__)
65
74
  ```
66
75
 
67
76
  ### Step-by-step control
@@ -76,11 +85,13 @@ client.login()
76
85
  device_info = client.get_device_info()
77
86
  scales = device_info["scale"]
78
87
 
79
- # 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.
80
90
  # Use get_body_composition_measurements() for scales with impedance sensors
81
- # (body fat, muscle, etc.) — the server-side count is unreliable for these.
82
- # Fall back to get_measurements() for weight-only scales.
83
- 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"]))
84
95
  measurements = client.get_body_composition_measurements(
85
96
  table_name=table["tableName"],
86
97
  user_id=client.user_id,
@@ -89,7 +100,6 @@ if not measurements:
89
100
  measurements = client.get_measurements(
90
101
  table_name=table["tableName"],
91
102
  user_id=client.user_id,
92
- total_count=table["count"],
93
103
  )
94
104
 
95
105
  # Export
@@ -97,6 +107,79 @@ save_json(measurements, "my_data.json")
97
107
  save_csv(measurements, "my_data.csv")
98
108
  ```
99
109
 
110
+ ### Family members (sub-users)
111
+
112
+ Profiles added under your account in the app (e.g. family members sharing a
113
+ scale) can be listed with `get_family_members()`. The logged-in user is not part
114
+ of that list; their own profile is in `client.user_info`.
115
+
116
+ ```python
117
+ names = {str(client.user_id): client.user_info["accountName"]}
118
+ for member in client.get_family_members():
119
+ names[str(member["id"])] = member["accountName"]
120
+
121
+ # {'5981614576857776000': 'Alice', '5991064042346217344': 'Bob'}
122
+ ```
123
+
124
+ Each entry is a full profile dict. Its `id` matches the `userIds` listed per
125
+ scale in `get_device_info()` and the `bUserId` field on measurement records.
126
+ Compare IDs as strings, since they arrive as both `int` and `str`.
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
+
140
+ ### Reading through a friend account
141
+
142
+ Renpho allows one active session per account, so logging in with your main
143
+ account signs the phone app out. To sync without that, read your data through
144
+ Renpho's friends feature from a second account:
145
+
146
+ 1. Create a second Renpho account with an email and password. An account
147
+ created with "Sign in with Google" or Apple has no password and can't log in
148
+ through the API.
149
+ 2. In the Renpho app, add the second account as a friend of your main account
150
+ and accept the request.
151
+ 3. Log in as the second account and read your main account's data:
152
+
153
+ ```python
154
+ client = RenphoClient("second@example.com", "password")
155
+ friend = client.get_friends()[0] # {"userId", "accountName", ...}
156
+
157
+ days = client.get_friend_measurements(friend["userId"])
158
+ # [{"day": "2026-11-02", "timeStamp": ..., "weight": 79.5, "bodyfat": 20.1, ...}, ...]
159
+ ```
160
+
161
+ With the CLI, set `RENPHO_FRIEND_ID` to the friend's `userId`. It writes
162
+ `friend_daily.json` and `friend_daily.csv` instead of the usual files.
163
+
164
+ `get_friend_trend(friend_id, param)` returns the daily points for a single
165
+ parameter, and `get_friend_summary()` and `get_friend_measure_days()` return
166
+ the server's raw responses.
167
+
168
+ Limits of the friend endpoints:
169
+
170
+ - One value per day (the last weigh-in that day).
171
+ - Body composition values only on days the scale measured them.
172
+ - One call covers a limited window. For older data, move `end_time` (unix
173
+ seconds) back.
174
+ - No segmental or girth data.
175
+ - Days are grouped by a whole-hour UTC offset, by default this machine's
176
+ (`time_zone=` to override).
177
+
178
+ This approach was worked out in
179
+ [#14](https://github.com/danvaneijck/renpho-api/issues/14), with a reference
180
+ implementation at
181
+ [DawidKrynski/renpho-friends](https://github.com/DawidKrynski/renpho-friends).
182
+
100
183
  ### Multiple Renpho accounts on one email
101
184
 
102
185
  Some users end up with **two Renpho accounts under the same email** — for
@@ -116,6 +199,14 @@ measurements = client.get_all_measurements(
116
199
  The library locates that user's rows, fetches them, and dedupes by
117
200
  `(table, id)` so you get a single combined timeline.
118
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
+
119
210
  **How the lookup works.** Measurements are sharded across 24 tables,
120
211
  `measurements_info_0` through `measurements_info_23`, and a user's rows live in
121
212
  `measurements_info_<user_id % 24>`. `device/count` only names the table for the
@@ -178,8 +269,8 @@ Requests time out after 10 s to connect and 30 s to read by default. Pass
178
269
  password, so they cannot log in through the API.
179
270
  - **The phone app logs you out after a sync.** Renpho allows one active
180
271
  session per account, so every `login()` ends the app's session. If you run
181
- scheduled syncs, run them less often or use a separate account
182
- (see [#14](https://github.com/danvaneijck/renpho-api/issues/14)).
272
+ scheduled syncs, read your data from a second account instead (see
273
+ [Reading through a friend account](#reading-through-a-friend-account)).
183
274
 
184
275
  ## Smart Tape Measure (body girth)
185
276
 
@@ -335,7 +426,9 @@ renpho-api/
335
426
  │ ├── constants.py # API endpoints, device types, metrics, girth sites
336
427
  │ ├── crypto.py # AES encryption/decryption
337
428
  │ ├── export.py # JSON/CSV export helpers
338
- │ └── girth.py # Smart Tape Measure (body girth) helpers
339
- ├── tests/ # Unit tests
340
- └── .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
341
434
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "renpho-api"
7
- version = "0.2.1"
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",
@@ -23,6 +23,7 @@ def main(argv: list[str] | None = None) -> None:
23
23
  password = os.getenv("RENPHO_PASSWORD", "")
24
24
  debug = os.getenv("RENPHO_DEBUG", "").lower() in ("1", "true", "yes")
25
25
  output_dir = Path(os.getenv("RENPHO_OUTPUT_DIR", "renpho_data"))
26
+ friend_id = os.getenv("RENPHO_FRIEND_ID", "").strip()
26
27
 
27
28
  if not email or not password:
28
29
  print("Missing credentials!\n")
@@ -39,6 +40,10 @@ def main(argv: list[str] | None = None) -> None:
39
40
  client.login()
40
41
  print(f"Logged in! User ID: {client.user_id}")
41
42
 
43
+ if friend_id:
44
+ _fetch_friend(client, friend_id, output_dir)
45
+ return
46
+
42
47
  # Step 2: Device info
43
48
  print("Getting device info...")
44
49
  device_info = client.get_device_info()
@@ -55,38 +60,50 @@ def main(argv: list[str] | None = None) -> None:
55
60
  print(f" Device info keys: {list(device_info.keys())}")
56
61
  sys.exit(1)
57
62
 
63
+ # Names are cosmetic — a failed family lookup must not abort the run.
64
+ try:
65
+ family = client.get_family_members()
66
+ except (RenphoAPIError, requests.RequestException) as e:
67
+ print(f" Family member lookup failed: {e}")
68
+ family = []
69
+ if family:
70
+ save_json(family, output_dir / "family_members.json")
71
+ user_names = {
72
+ str(m["id"]): m["accountName"]
73
+ for m in family
74
+ if m.get("id") is not None and m.get("accountName")
75
+ }
76
+ if client.user_info and client.user_info.get("accountName"):
77
+ user_names[str(client.user_id)] = client.user_info["accountName"]
78
+
58
79
  print(f"\nFound {len(scales)} scale table(s):")
59
80
  for i, scale in enumerate(scales):
60
81
  table = scale.get("tableName", "unknown")
61
82
  count = scale.get("count", 0)
62
- uids = scale.get("userIds", [])
63
- print(f" [{i}] table={table}, records={count}, users={uids}")
64
-
65
- # Step 3: Fetch measurements
66
- all_measurements: list[dict] = []
67
- for scale in scales:
68
- table_name = scale.get("tableName")
69
- count = scale.get("count", 0)
70
- user_ids = scale.get("userIds", [])
71
-
72
- if not table_name or count == 0:
73
- continue
74
-
75
- uid = client.user_id
76
- if user_ids and uid not in user_ids:
77
- uid = user_ids[0]
78
-
79
- print(f"Fetching measurements (table: {table_name}, total: {count})...")
80
- measurements = client.get_measurements(table_name, uid, count)
81
- all_measurements.extend(measurements)
82
-
83
- if all_measurements:
84
- # Sort newest first
85
- all_measurements.sort(
86
- key=lambda m: m.get("timeStamp", 0) or 0,
87
- reverse=True,
83
+ users = ", ".join(
84
+ f"{user_names[str(u)]} ({u})" if str(u) in user_names else str(u)
85
+ for u in scale.get("userIds", [])
88
86
  )
87
+ print(f" [{i}] table={table}, records={count}, users=[{users}]")
88
+
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)
101
+ for m in all_measurements:
102
+ name = user_names.get(str(m.get("bUserId", client.user_id)))
103
+ if name:
104
+ m["userName"] = name
89
105
 
106
+ if all_measurements:
90
107
  print(f"\nTotal: {len(all_measurements)} measurement(s)")
91
108
 
92
109
  # Display most recent 5
@@ -134,3 +151,31 @@ def main(argv: list[str] | None = None) -> None:
134
151
  save_json(client.user_info, output_dir / "user_profile.json")
135
152
 
136
153
  print(f"\nDone! Data saved to '{output_dir}/' folder.")
154
+
155
+
156
+ def _fetch_friend(client: RenphoClient, friend_id: str, output_dir: Path) -> None:
157
+ """Friend mode: read another account's daily data via the friends feature."""
158
+ print(f"Fetching daily data for friend {friend_id}...")
159
+ records = client.get_friend_measurements(friend_id)
160
+ if not records:
161
+ print(" No data returned. Check that RENPHO_FRIEND_ID is a userId from")
162
+ print(" the friends list and that the friend request was accepted.")
163
+ friends = client.get_friends()
164
+ if friends:
165
+ print(" Friends of this account:")
166
+ for f in friends:
167
+ print(f" {f.get('userId')} {f.get('accountName', '')}")
168
+ return
169
+
170
+ print(f"Total: {len(records)} day(s), newest {records[0]['day']}")
171
+ for r in records[:5]:
172
+ print(f"\n{'=' * 55}")
173
+ print(f" Day {r['day']}")
174
+ print(f"{'=' * 55}")
175
+ print(format_measurement(r))
176
+ if len(records) > 5:
177
+ print(f"\n ... and {len(records) - 5} more")
178
+
179
+ save_json(records, output_dir / "friend_daily.json")
180
+ save_csv(records, output_dir / "friend_daily.csv")
181
+ print(f"\nDone! Data saved to '{output_dir}/' folder.")