equilab 0.1.1__py3-none-any.whl

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.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: equilab
3
+ Version: 0.1.1
4
+ Summary: Async, read-only Python client for the unofficial Equilab cloud API
5
+ Project-URL: Homepage, https://github.com/Danw33/py-equilab
6
+ Project-URL: Repository, https://github.com/Danw33/py-equilab
7
+ Project-URL: Issues, https://github.com/Danw33/py-equilab/issues
8
+ Project-URL: Changelog, https://github.com/Danw33/py-equilab/blob/main/CHANGELOG.md
9
+ Author-email: Daniel Wilson <hello@danw.io>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: asyncio,equestrian,equilab,home-assistant
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Home Automation
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.11
27
+ Requires-Dist: aiohttp<4,>=3.11.0
28
+ Provides-Extra: test
29
+ Requires-Dist: mypy==2.3.1; extra == 'test'
30
+ Requires-Dist: pytest-asyncio==1.4.0; extra == 'test'
31
+ Requires-Dist: pytest-cov==7.1.0; extra == 'test'
32
+ Requires-Dist: pytest==9.1.1; extra == 'test'
33
+ Requires-Dist: ruff==0.16.7; extra == 'test'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # py-equilab: Equilab API Client Python Library
37
+
38
+ An **unofficial**, asynchronous, read-only Python client for the Equilab cloud API.
39
+
40
+ This library provides authentication, token renewal, bounded concurrent reads,
41
+ rate-limit observations, Firestore decoding, and typed domain models for Equilab
42
+ accounts, horses, training sessions, riders, and stables/groups. It does not modify
43
+ cloud data, bypass subscription entitlements, or download route recordings.
44
+
45
+ > [!IMPORTANT]
46
+ > This independent project is unofficial and is not affiliated with, endorsed by,
47
+ > or supported by Equilab or Equestrian Insights. The upstream API is undocumented
48
+ > and may change without notice. Use only with an account and data you are authorised
49
+ > to access.
50
+
51
+ ## Installation
52
+
53
+ ```sh
54
+ python -m pip install equilab
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ```python
60
+ import aiohttp
61
+
62
+ from pyequilab import EquilabClient
63
+
64
+
65
+ async def get_account(email: str, password: str) -> dict:
66
+ async with aiohttp.ClientSession() as session:
67
+ client = EquilabClient(session)
68
+ await client.async_login(email, password)
69
+ return await client.async_get_user()
70
+ ```
71
+
72
+ Long-running applications should persist `client.refresh_token` securely. Pass an
73
+ `on_token` callback to receive rotated refresh tokens. Callers own the supplied
74
+ `aiohttp.ClientSession`; the library never closes it.
75
+
76
+ ## Supported operations
77
+
78
+ - Sign in and renew authentication tokens.
79
+ - Read the authenticated user profile.
80
+ - Read referenced horses, training sessions, and stables/groups.
81
+ - Read the latest notification without marking it as read.
82
+ - Normalise the subset of domain data used by downstream applications.
83
+
84
+ All public network operations are asynchronous. Exceptions contain safe generic
85
+ messages and never include response bodies, credentials, identifiers, or request URLs.
86
+
87
+ ## Development
88
+
89
+ ```sh
90
+ python -m pip install -e '.[test]'
91
+ pytest --cov=pyequilab --cov-branch --cov-report=term-missing
92
+ ruff check .
93
+ ruff format --check .
94
+ mypy
95
+ ```
96
+
97
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the release process.
98
+
99
+ ## Licence
100
+
101
+ Copyright © 2026 Daniel Wilson ([@Danw33](https://github.com/Danw33))
102
+
103
+ Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
104
+
105
+ Equilab and Equestrian Insights AB are trademarks of their respective owners.
@@ -0,0 +1,9 @@
1
+ pyequilab/__init__.py,sha256=ZKAfYXMr_YLVgIXsDdG9YbHtEjLQ4A-VSGuguiA23R4,655
2
+ pyequilab/api.py,sha256=uSzrFhr1f6C0wwXtoOqP6n5eTiUsqeDm7FToN7CnqbU,11873
3
+ pyequilab/models.py,sha256=sH_3vv2BqbNCjplvY51sTAw476DuPu2SGKHdLzVm_8c,10828
4
+ pyequilab/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
+ equilab-0.1.1.dist-info/METADATA,sha256=NPhDJBYKdLnBy2kvaVveoFvaYTHGYbkD7XqMxhEPlLw,3765
6
+ equilab-0.1.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ equilab-0.1.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
8
+ equilab-0.1.1.dist-info/licenses/NOTICE,sha256=1yLltYao5FomTx6YhYkoIK4vDqiQVJjTLpd3fM13LU4,333
9
+ equilab-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ py-equilab
2
+ Copyright © 2026 Daniel Wilson (https://github.com/Danw33)
3
+
4
+ Licensed under the Apache License, Version 2.0.
5
+
6
+ Equilab and related names and marks are the property of their respective
7
+ owners. This independent project is unofficial and is not affiliated with,
8
+ endorsed by, or supported by Equilab or Equestrian Insights AB.
pyequilab/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """Async, read-only client for the unofficial Equilab cloud API."""
2
+
3
+ from .api import (
4
+ AccessError,
5
+ AuthError,
6
+ EquilabClient,
7
+ EquilabError,
8
+ MissingError,
9
+ RateLimitError,
10
+ active_ids,
11
+ )
12
+ from .models import (
13
+ GAITS,
14
+ Horse,
15
+ Profile,
16
+ Training,
17
+ horse_from_data,
18
+ number,
19
+ rider_from_data,
20
+ stable_from_data,
21
+ )
22
+
23
+ __all__ = [
24
+ "GAITS",
25
+ "AccessError",
26
+ "AuthError",
27
+ "EquilabClient",
28
+ "EquilabError",
29
+ "Horse",
30
+ "MissingError",
31
+ "Profile",
32
+ "RateLimitError",
33
+ "Training",
34
+ "active_ids",
35
+ "horse_from_data",
36
+ "number",
37
+ "rider_from_data",
38
+ "stable_from_data",
39
+ ]
pyequilab/api.py ADDED
@@ -0,0 +1,296 @@
1
+ """Small, read-only Firebase client; independent of Home Assistant.
2
+
3
+ No admin credentials, entitlement changes, storage downloads or cloud writes.
4
+ The sole POST operations authenticate and refresh authentication.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import math
11
+ import time
12
+ from collections.abc import Callable
13
+ from datetime import datetime
14
+ from typing import Any, TypedDict
15
+ from urllib.parse import quote
16
+
17
+ import aiohttp
18
+
19
+ PROJECT = "project-847196107745527358"
20
+ API_KEY = "AIzaSyCRPTesSPploBVb2SMXbloWDyEkmHB1Wx8"
21
+ AUTH_URL = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={API_KEY}"
22
+ TOKEN_URL = f"https://securetoken.googleapis.com/v1/token?key={API_KEY}"
23
+ ROOT = f"https://firestore.googleapis.com/v1/projects/{PROJECT}/databases/(default)/documents"
24
+
25
+
26
+ class EquilabError(Exception):
27
+ """Safe public exception; never includes response bodies or URLs."""
28
+
29
+
30
+ class AuthError(EquilabError):
31
+ """Authentication expired or rejected."""
32
+
33
+
34
+ class AccessError(EquilabError):
35
+ """Document access denied."""
36
+
37
+
38
+ class MissingError(EquilabError):
39
+ """Document no longer exists."""
40
+
41
+
42
+ class RateLimitError(EquilabError):
43
+ """Upstream quota exceeded."""
44
+
45
+
46
+ class RateLimitObservations(TypedDict):
47
+ """Non-sensitive rate-limit metadata observed from the service."""
48
+
49
+ http_429_count: int
50
+ headers: dict[str, str]
51
+
52
+
53
+ def decode(value: dict[str, Any]) -> Any:
54
+ """Decode Firestore values, retaining timezone-aware timestamps."""
55
+ if "nullValue" in value:
56
+ return None
57
+ for key, converter in (
58
+ ("stringValue", str),
59
+ ("booleanValue", bool),
60
+ ("integerValue", int),
61
+ ("doubleValue", float),
62
+ ):
63
+ if key in value:
64
+ return converter(value[key])
65
+ if "timestampValue" in value:
66
+ return datetime.fromisoformat(value["timestampValue"].replace("Z", "+00:00"))
67
+ if "mapValue" in value:
68
+ return {k: decode(v) for k, v in value["mapValue"].get("fields", {}).items()}
69
+ if "arrayValue" in value:
70
+ return [decode(v) for v in value["arrayValue"].get("values", [])]
71
+ # Unsupported types are intentionally not surfaced or dereferenced.
72
+ return None
73
+
74
+
75
+ def active_ids(value: Any) -> set[str]:
76
+ """Only explicitly active boolean index entries confer discovery."""
77
+ if not isinstance(value, dict):
78
+ return set()
79
+ return {k for k, v in value.items() if isinstance(k, str) and v is True}
80
+
81
+
82
+ class EquilabClient:
83
+ """Use a caller-owned session, with serialized refresh and bounded reads."""
84
+
85
+ def __init__(
86
+ self,
87
+ session: aiohttp.ClientSession,
88
+ *,
89
+ uid: str = "",
90
+ refresh_token: str = "",
91
+ on_token: Callable[[str], None] | None = None,
92
+ ):
93
+ self.session = session
94
+ self.uid = uid
95
+ self.refresh_token = refresh_token
96
+ self.on_token = on_token
97
+ self._id_token = ""
98
+ self._expires = 0.0
99
+ self._refresh_lock = asyncio.Lock()
100
+ self._read_limit = asyncio.Semaphore(4)
101
+ self.rate_limit_observations: RateLimitObservations = {
102
+ "http_429_count": 0,
103
+ "headers": {},
104
+ }
105
+
106
+ async def _request(
107
+ self, method: str, url: str, *, auth: bool = False, **kwargs: Any
108
+ ) -> dict[str, Any]:
109
+ try:
110
+ async with self.session.request(
111
+ method,
112
+ url,
113
+ timeout=aiohttp.ClientTimeout(total=30),
114
+ allow_redirects=False,
115
+ **kwargs,
116
+ ) as response:
117
+ observed = {
118
+ k.lower(): str(v)[:200]
119
+ for k, v in response.headers.items()
120
+ if k.lower()
121
+ in {
122
+ "retry-after",
123
+ "ratelimit-limit",
124
+ "ratelimit-remaining",
125
+ "ratelimit-reset",
126
+ "ratelimit",
127
+ "ratelimit-policy",
128
+ "x-ratelimit-limit",
129
+ "x-ratelimit-remaining",
130
+ "x-ratelimit-reset",
131
+ }
132
+ }
133
+ self.rate_limit_observations["headers"].update(observed)
134
+ if response.status == 429:
135
+ self.rate_limit_observations["http_429_count"] += 1
136
+ raise RateLimitError("Cloud rate limit; try again later")
137
+ if response.status == 401:
138
+ raise AuthError("Authentication rejected")
139
+ if response.status == 403:
140
+ raise AccessError("Cloud access denied")
141
+ if response.status == 404:
142
+ raise MissingError("Document not found")
143
+ if response.status >= 500:
144
+ raise EquilabError("Cloud service unavailable")
145
+ if response.status == 400 and auth:
146
+ body = await response.json()
147
+ code = body.get("error", {}).get("message", "").split(" : ")[0]
148
+ if code in {
149
+ "INVALID_LOGIN_CREDENTIALS",
150
+ "INVALID_PASSWORD",
151
+ "EMAIL_NOT_FOUND",
152
+ "USER_DISABLED",
153
+ "USER_NOT_FOUND",
154
+ "INVALID_REFRESH_TOKEN",
155
+ "TOKEN_EXPIRED",
156
+ "INVALID_EMAIL",
157
+ }:
158
+ raise AuthError("Authentication rejected")
159
+ if code == "TOO_MANY_ATTEMPTS_TRY_LATER":
160
+ raise RateLimitError("Too many authentication attempts")
161
+ raise EquilabError("Authentication service rejected request")
162
+ if response.status != 200:
163
+ raise EquilabError("Unexpected cloud response")
164
+ body = await response.json()
165
+ if not isinstance(body, dict):
166
+ raise EquilabError("Invalid cloud response")
167
+ return body
168
+ except (aiohttp.ClientError, TimeoutError, ValueError, TypeError, AttributeError):
169
+ raise EquilabError("Could not communicate with Equilab") from None
170
+
171
+ def _tokens(self, body: dict[str, Any], *, refresh: bool) -> None:
172
+ uid_value = body.get("user_id" if refresh else "localId")
173
+ token_value = body.get("id_token" if refresh else "idToken")
174
+ renewal_value = body.get("refresh_token" if refresh else "refreshToken")
175
+ try:
176
+ expiry = float(body.get("expires_in" if refresh else "expiresIn", 3600))
177
+ except (TypeError, ValueError):
178
+ raise EquilabError("Invalid authentication response") from None
179
+ if not (
180
+ isinstance(uid_value, str)
181
+ and uid_value
182
+ and isinstance(token_value, str)
183
+ and token_value
184
+ and isinstance(renewal_value, str)
185
+ and renewal_value
186
+ ):
187
+ raise EquilabError("Incomplete authentication response")
188
+ if not math.isfinite(expiry) or expiry <= 0:
189
+ raise EquilabError("Invalid token lifetime")
190
+ if self.uid and self.uid != uid_value:
191
+ raise AuthError("Account identity changed")
192
+ self.uid, self._id_token = uid_value, token_value
193
+ self._expires = time.monotonic() + max(0, expiry - 60)
194
+ changed = self.refresh_token != renewal_value
195
+ self.refresh_token = renewal_value
196
+ if changed and self.on_token:
197
+ self.on_token(renewal_value)
198
+
199
+ async def async_login(self, email: str, password: str) -> None:
200
+ body = await self._request(
201
+ "POST",
202
+ AUTH_URL,
203
+ auth=True,
204
+ json={
205
+ "email": email.strip(),
206
+ "password": password,
207
+ "returnSecureToken": True,
208
+ },
209
+ )
210
+ self._tokens(body, refresh=False)
211
+
212
+ async def _async_ensure_token(self, rejected: str | None = None) -> None:
213
+ async with self._refresh_lock:
214
+ if self._id_token and time.monotonic() < self._expires:
215
+ if rejected is None or rejected != self._id_token:
216
+ return
217
+ if not self.refresh_token:
218
+ raise AuthError("Sign in required")
219
+ body = await self._request(
220
+ "POST",
221
+ TOKEN_URL,
222
+ auth=True,
223
+ data={
224
+ "grant_type": "refresh_token",
225
+ "refresh_token": self.refresh_token,
226
+ },
227
+ )
228
+ self._tokens(body, refresh=True)
229
+
230
+ async def _async_document(self, collection: str, identifier: str) -> dict[str, Any]:
231
+ """Read one referenced document; refresh once on a rejected ID token."""
232
+ if not isinstance(identifier, str) or not identifier:
233
+ raise EquilabError("Invalid document identifier")
234
+ async with self._read_limit:
235
+ await self._async_ensure_token()
236
+ url = f"{ROOT}/{quote(collection, safe='')}/{quote(identifier, safe='')}"
237
+ for attempt in range(2):
238
+ token = self._id_token
239
+ try:
240
+ body = await self._request(
241
+ "GET",
242
+ url,
243
+ headers={
244
+ "Authorization": f"Bearer {token}",
245
+ },
246
+ )
247
+ return {k: decode(v) for k, v in body.get("fields", {}).items()}
248
+ except AuthError:
249
+ if attempt:
250
+ raise
251
+ await self._async_ensure_token(rejected=token)
252
+ except (ValueError, TypeError, AttributeError, OverflowError):
253
+ raise EquilabError("Invalid document data") from None
254
+ raise AuthError("Sign in required")
255
+
256
+ async def async_get_user(self, identifier: str | None = None) -> dict[str, Any]:
257
+ """Return a decoded user document."""
258
+ return await self._async_document("users", identifier or self.uid)
259
+
260
+ async def async_get_horse(self, identifier: str) -> dict[str, Any]:
261
+ """Return a decoded horse document."""
262
+ return await self._async_document("horses", identifier)
263
+
264
+ async def async_get_training(self, identifier: str) -> dict[str, Any]:
265
+ """Return a decoded training document."""
266
+ return await self._async_document("trainings", identifier)
267
+
268
+ async def async_get_stable(self, identifier: str) -> dict[str, Any]:
269
+ """Return a decoded stable or group document."""
270
+ return await self._async_document("stables", identifier)
271
+
272
+ async def async_get_latest_notification(self) -> list[dict[str, Any]]:
273
+ """Read only the most recent inbox item; never acknowledge it."""
274
+ async with self._read_limit:
275
+ await self._async_ensure_token()
276
+ url = f"{ROOT}/users/{quote(self.uid, safe='')}/notifications"
277
+ for attempt in range(2):
278
+ token = self._id_token
279
+ try:
280
+ body = await self._request(
281
+ "GET",
282
+ url,
283
+ params={"pageSize": "1", "orderBy": "date desc"},
284
+ headers={"Authorization": f"Bearer {token}"},
285
+ )
286
+ return [
287
+ {k: decode(v) for k, v in item.get("fields", {}).items()}
288
+ for item in body.get("documents", [])
289
+ ]
290
+ except AuthError:
291
+ if attempt:
292
+ raise
293
+ await self._async_ensure_token(rejected=token)
294
+ except (ValueError, TypeError, AttributeError, OverflowError):
295
+ raise EquilabError("Invalid notification data") from None
296
+ raise AuthError("Sign in required")
pyequilab/models.py ADDED
@@ -0,0 +1,303 @@
1
+ """Normalized, deliberately minimal models; no raw profiles or notes retained."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field
7
+ from datetime import date, datetime, timedelta
8
+ from typing import Any, cast
9
+
10
+ from .api import active_ids
11
+
12
+ TYPE_NAMES: dict[str, str] = {
13
+ "-KgsjZPxgZP7Nsj_cXvV": "Show jumping",
14
+ "-KgsjZPxgZP7Nsj_cXvW": "Dressage",
15
+ "-KgsjZPyo4n1dAYIvVQe": "Flatwork",
16
+ "-KgsjZPyo4n1dAYIvVQf": "Hacking",
17
+ "-KgsjZPyo4n1dAYIvVQg": "Trotting training",
18
+ "-KgsjZPyo4n1dAYIvVQh": "Gallop training",
19
+ "-KgsjZPyo4n1dAYIvVQi": "Cardio",
20
+ "-KgsjZPzi754NLdGfZ4p": "Lungeing",
21
+ "-KgsjZPzi754NLdGfZ4q": "Long reining",
22
+ "-KgsjZPzi754NLdGfZ4r": "Walk training",
23
+ "-KgsjZPzi754NLdGfZ4s": "Competition",
24
+ "-KgsjZPzi754NLdGfZ4t": "Poles",
25
+ "-KgsjZPzi754NLdGfZ4u": "Eventing",
26
+ "-KgsjZPzi754NLdGfZ4v": "Strength",
27
+ "-KgsjZPzi754NLdGfZ4y": "Driving",
28
+ "-KgsjZPzi754NLdGfZ4x": "Suppleness",
29
+ "-KgsjZPzi754NLdGfZ4a": "Western riding",
30
+ "-KgsjZPzi754NLdGfZ4c": "Groundwork",
31
+ "-KgsjZPzi754NLdGfZ4i": "Cross country",
32
+ "-KgsjZPzi754NLdGfZ4z": "Endurance riding",
33
+ "-KgsjZPzi754NLdGfZ4l": "Hunting",
34
+ "-KgsjZPzi754NLdGfZ4m": "Reining",
35
+ "-KgsjZPzi754NLdGfZ4n": "Barrel racing",
36
+ "-KgsjZPzi754NLdGfZ4b": "Western pleasure",
37
+ "-KgsjZPzi754NLdGfZ4d": "Working equitation",
38
+ "-KgsjZPzi754NLdGfZ4e": "Polocrosse",
39
+ "-KgsjZPzi754NLdGfZ4g": "Polo",
40
+ "-KgsjZPzi754NLdGfZ5a": "Vaulting",
41
+ "-KgsjZPzi754NLdGfZ5b": "Cutting",
42
+ "-KgsjZPzi754NLdGfZ5c": "Mounted games",
43
+ "-KgsjZPzi754NLdGfZ5d": "Hunter jumping",
44
+ "-KgsjZPzi754NLdGfZ5e": "Harness racing",
45
+ "-KgsjZPzi754NLdGfZ5f": "Combined driving",
46
+ "-KgsjZPzi754NLdGfZ5g": "Icelandic horse riding",
47
+ "-KgsjZPzi754NLdGfZ4f": "Other",
48
+ }
49
+ GAITS: tuple[str, ...] = ("stand", "walk", "trot", "canter", "tolt", "unknown")
50
+
51
+
52
+ def number(value: Any) -> float | None:
53
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
54
+ return None
55
+ return float(value) if math.isfinite(value) and value >= 0 else None
56
+
57
+
58
+ def text(value: Any) -> str | None:
59
+ return value if isinstance(value, str) and value else None
60
+
61
+
62
+ def best_records(data: dict[str, Any]) -> dict[str, float | None]:
63
+ """Equilab's reported personal bests, not estimates from accessible history."""
64
+ records = data.get("records")
65
+ if not isinstance(records, list):
66
+ return {}
67
+ result: dict[str, float | None] = {}
68
+ for kind in ("distance", "duration", "speed"):
69
+ values = [
70
+ number(r.get("value")) for r in records if isinstance(r, dict) and r.get("type") == kind
71
+ ]
72
+ result["record_" + kind] = max((v for v in values if v is not None), default=None)
73
+ return result
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Training:
78
+ id: str
79
+ start: datetime | None
80
+ kind: str | None
81
+ duration: float | None
82
+ distance: float | None
83
+ energy: float | None
84
+ gaits: dict[str, float | None] = field(default_factory=dict)
85
+ stats: dict[str, float | None] = field(default_factory=dict)
86
+ rider_id: str | None = None
87
+ horse_id: str | None = None
88
+ rider_energy: float | None = None
89
+
90
+ @classmethod
91
+ def parse(cls, identifier: str, data: dict[str, Any]) -> Training:
92
+ start = data.get("date")
93
+ if not isinstance(start, datetime) or start.tzinfo is None:
94
+ start = None
95
+ total = data.get("total")
96
+ total = total if isinstance(total, dict) else {}
97
+ kinds = sorted({TYPE_NAMES.get(k, "Other") for k in active_ids(data.get("trainingTypes"))})
98
+ gaits: dict[str, float | None] = {}
99
+ stats: dict[str, float | None] = {}
100
+ for gait in GAITS:
101
+ values = data.get(gait)
102
+ gaits[gait] = number(values.get("time")) if isinstance(values, dict) else None
103
+ for gait in (*GAITS, "total"):
104
+ values = data.get(gait)
105
+ if not isinstance(values, dict):
106
+ continue
107
+ for source, target, multiplier in (
108
+ ("pace", "speed", 1),
109
+ ("topSpeed", "top_speed", 1),
110
+ ("beat", "tempo", 60),
111
+ ("counter", "strides", 1),
112
+ ("stride", "stride_length", 1),
113
+ ("distance", "distance", 1),
114
+ ("leftTurnsDuration", "left_rein", 1),
115
+ ("rightTurnsDuration", "right_rein", 1),
116
+ ):
117
+ value = number(values.get(source))
118
+ stats[f"{gait}_{target}"] = value * multiplier if value is not None else None
119
+ weather = data.get("weather")
120
+ if isinstance(weather, dict):
121
+ for key in ("temperature", "apparentTemperature", "windSpeed", "humidity", "pressure"):
122
+ value = weather.get(key)
123
+ if (
124
+ isinstance(value, (int, float))
125
+ and not isinstance(value, bool)
126
+ and math.isfinite(value)
127
+ ):
128
+ if key == "humidity":
129
+ value = value * 100 if 0 <= value <= 1 else None
130
+ stats[f"weather_{key}"] = value
131
+ transitions = data.get("transitionData")
132
+ if isinstance(transitions, dict):
133
+ counts = [
134
+ number(v)
135
+ for row in transitions.values()
136
+ if isinstance(row, dict)
137
+ for v in row.values()
138
+ ]
139
+ stats["transitions"] = (
140
+ sum(cast(float, value) for value in counts)
141
+ if all(value is not None for value in counts)
142
+ else None
143
+ )
144
+ return cls(
145
+ identifier,
146
+ start,
147
+ ", ".join(kinds) or None,
148
+ number(total.get("time")),
149
+ number(total.get("distance")),
150
+ number(data.get("horseEnergyMj")),
151
+ gaits,
152
+ stats,
153
+ text(data.get("user")),
154
+ text(data.get("horse")),
155
+ number(data.get("riderEnergy")),
156
+ )
157
+
158
+ @property
159
+ def end(self) -> datetime | None:
160
+ if self.start is None or self.duration is None:
161
+ return None
162
+ try:
163
+ return self.start + timedelta(seconds=max(1, self.duration))
164
+ except OverflowError:
165
+ return None
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class Horse:
170
+ id: str
171
+ name: str
172
+ breed: str | None
173
+ birthday: str | None
174
+ category: str | None
175
+ level: str | None
176
+ owned: bool
177
+ trainings: tuple[Training, ...]
178
+ skipped: int = 0
179
+ profile: dict[str, Any] = field(default_factory=dict)
180
+
181
+ @property
182
+ def latest(self) -> Training | None:
183
+ candidates = [training for training in self.trainings if training.start is not None]
184
+ return max(candidates, key=lambda training: cast(datetime, training.start), default=None)
185
+
186
+ def aggregate(self, period: str, metric: str, now: datetime) -> float | int | None:
187
+ """Calendar periods in HA's timezone; missing data never becomes zero."""
188
+ start = now.replace(hour=0, minute=0, second=0, microsecond=0)
189
+ start = (
190
+ start - timedelta(days=start.weekday()) if period == "week" else start.replace(day=1)
191
+ )
192
+ if self.skipped or any(t.start is None for t in self.trainings):
193
+ return None
194
+ items = [
195
+ training
196
+ for training in self.trainings
197
+ if training.start is not None and start <= training.start <= now
198
+ ]
199
+ if metric == "count":
200
+ return len(items)
201
+ values = [getattr(t, metric) for t in items]
202
+ return sum(values) if all(v is not None for v in values) else None
203
+
204
+
205
+ def horse_from_data(
206
+ identifier: str,
207
+ data: dict[str, Any],
208
+ owned: bool,
209
+ trainings: tuple[Training, ...],
210
+ skipped: int,
211
+ ) -> Horse:
212
+ birth = data.get("birthDate")
213
+ birthday = birth.date().isoformat() if isinstance(birth, datetime) else None
214
+ if isinstance(birth, str):
215
+ try:
216
+ birthday = date.fromisoformat(birth[:10]).isoformat()
217
+ except ValueError:
218
+ pass
219
+ return Horse(
220
+ identifier,
221
+ text(data.get("name")) or "Horse",
222
+ text(data.get("horseBreed")),
223
+ birthday,
224
+ text(data.get("category")),
225
+ text(data.get("level")),
226
+ owned,
227
+ trainings,
228
+ skipped,
229
+ {
230
+ **best_records(data),
231
+ "owner_id": text(data.get("ownerId")),
232
+ "stable_id": text(data.get("stableId")),
233
+ "weight": number(data.get("weight")),
234
+ "tack_weight": number(data.get("toolWeight")),
235
+ "records_count": len(data["records"])
236
+ if isinstance(data.get("records"), list)
237
+ else None,
238
+ },
239
+ )
240
+
241
+
242
+ @dataclass(frozen=True)
243
+ class Profile:
244
+ id: str
245
+ name: str
246
+ model: str
247
+ values: dict[str, Any]
248
+ trainings: tuple[Training, ...] = ()
249
+ skipped: int = 0
250
+
251
+ latest = Horse.latest
252
+ aggregate = Horse.aggregate
253
+
254
+
255
+ def rider_from_data(
256
+ identifier: str,
257
+ data: dict[str, Any],
258
+ trainings: tuple[Training, ...],
259
+ skipped: int,
260
+ notifications: list[dict[str, Any]],
261
+ ) -> Profile:
262
+ values: dict[str, Any] = {
263
+ key: text(data.get(key)) for key in ("firstName", "lastName", "city", "discipline")
264
+ }
265
+ values.update(best_records(data))
266
+ for key in (
267
+ "totalTrainingCount",
268
+ "totalTrainingDistance",
269
+ "totalTrainingTime",
270
+ "unseenNotificationCount",
271
+ ):
272
+ values[key] = number(data.get(key))
273
+ for key in ("achievements", "records"):
274
+ values[key + "Count"] = len(data[key]) if isinstance(data.get(key), (dict, list)) else None
275
+ latest = max(
276
+ (n for n in notifications if isinstance(n.get("date"), datetime) and n["date"].tzinfo),
277
+ key=lambda n: n["date"],
278
+ default={},
279
+ )
280
+ values["lastNotification"] = latest.get("date")
281
+ values["lastNotificationType"] = text(latest.get("type"))
282
+ name = " ".join(filter(None, (values["firstName"], values["lastName"]))) or "Rider"
283
+ return Profile(identifier, name, "Rider", values, tuple(trainings), skipped)
284
+
285
+
286
+ def stable_from_data(identifier: str, data: dict[str, Any]) -> Profile:
287
+ values: dict[str, Any] = {key: text(data.get(key)) for key in ("type", "privacy", "ownerId")}
288
+ values["horseCount"] = (
289
+ len(active_ids(data["horses"])) if isinstance(data.get("horses"), dict) else None
290
+ )
291
+ for key, maximum in (("lat", 90), ("lon", 180)):
292
+ value = data.get(key)
293
+ values[key] = (
294
+ value
295
+ if isinstance(value, (int, float))
296
+ and not isinstance(value, bool)
297
+ and math.isfinite(value)
298
+ and abs(value) <= maximum
299
+ else None
300
+ )
301
+ return Profile(
302
+ identifier, text(data.get("name")) or "Stable or group", "Stable / Group", values
303
+ )
pyequilab/py.typed ADDED
@@ -0,0 +1 @@
1
+