python-siseli 0.2.6__py3-none-any.whl → 0.3.0__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.
- python_siseli-0.3.0.dist-info/METADATA +134 -0
- python_siseli-0.3.0.dist-info/RECORD +34 -0
- {python_siseli-0.2.6.dist-info → python_siseli-0.3.0.dist-info}/WHEEL +1 -1
- python_siseli-0.3.0.dist-info/licenses/LICENSE +21 -0
- siseli/__init__.py +4 -0
- siseli/_utils.py +28 -2
- siseli/alarms.py +7 -4
- siseli/auth.py +64 -23
- siseli/client.py +166 -31
- siseli/config.py +43 -6
- siseli/config_safety.py +35 -7
- siseli/const.py +6 -2
- siseli/dashboard.py +8 -6
- siseli/device.py +8 -12
- siseli/dictionary.py +5 -2
- siseli/exceptions.py +22 -0
- siseli/history.py +29 -36
- siseli/models/auth.py +2 -2
- siseli/models/dashboard.py +1 -2
- siseli/models/state.py +12 -2
- siseli/models/station.py +4 -3
- siseli/open_auth.py +12 -7
- siseli/overview.py +33 -9
- siseli/py.typed +0 -0
- siseli/state.py +28 -12
- siseli/station.py +19 -7
- python_siseli-0.2.6.dist-info/METADATA +0 -58
- python_siseli-0.2.6.dist-info/RECORD +0 -32
- {python_siseli-0.2.6.dist-info → python_siseli-0.3.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-siseli
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python SDK for Siseli Cloud
|
|
5
|
+
Author: vvkor
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/vvkor/python-siseli
|
|
8
|
+
Project-URL: Issues, https://github.com/vvkor/python-siseli/issues
|
|
9
|
+
Keywords: siseli,solar,inverter,home-assistant
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: httpx>=0.27
|
|
22
|
+
Requires-Dist: cryptography>=42
|
|
23
|
+
Requires-Dist: tzdata; platform_system == "Windows"
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
27
|
+
Requires-Dist: respx>=0.21; extra == "dev"
|
|
28
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
29
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# python-siseli
|
|
33
|
+
|
|
34
|
+
Python SDK for [Siseli Cloud](https://solar.siseli.com).
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install python-siseli
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
from siseli import SiseliClient
|
|
47
|
+
|
|
48
|
+
async def main():
|
|
49
|
+
async with SiseliClient("user@example.com", "secret", timezone="Europe/Warsaw") as client:
|
|
50
|
+
# Discover devices
|
|
51
|
+
devices = await client.get_devices()
|
|
52
|
+
device = devices[0]
|
|
53
|
+
print(f"Device: {device.name} ({device.id})")
|
|
54
|
+
|
|
55
|
+
# Latest telemetry
|
|
56
|
+
state = await client.get_device_state(device.id)
|
|
57
|
+
grid = state.get("gridVoltage")
|
|
58
|
+
if grid:
|
|
59
|
+
print(f"Grid voltage: {grid.value_display} {grid.unit}")
|
|
60
|
+
|
|
61
|
+
# Energy flow diagram
|
|
62
|
+
flow = await client.get_energy_flow(device.id)
|
|
63
|
+
if flow.battery:
|
|
64
|
+
print(f"Battery: {flow.battery.value.value_display} {flow.battery.value.unit}")
|
|
65
|
+
|
|
66
|
+
asyncio.run(main())
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Client options
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
SiseliClient(
|
|
73
|
+
account, password,
|
|
74
|
+
timezone="Europe/Warsaw", # also used for "today"/"this month" in summaries
|
|
75
|
+
timeout=30.0,
|
|
76
|
+
max_retries=2, # transient failures only, never for config writes
|
|
77
|
+
retry_backoff=0.5, # seconds, doubled on each retry
|
|
78
|
+
http_client=None, # reuse your own httpx.AsyncClient (not closed by the SDK)
|
|
79
|
+
open_auth=False, # sign requests with the Siseli Open API headers
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
* An expired token is refreshed transparently; an HTTP 401/403 triggers one
|
|
84
|
+
re-login and retry.
|
|
85
|
+
* Connection errors, timeouts and HTTP 429/502/503/504 are retried with
|
|
86
|
+
exponential backoff.
|
|
87
|
+
* `open_auth=True` adds the `IOT-Open-*` signature headers. The application
|
|
88
|
+
secret used for this is taken from the official web client; it is only
|
|
89
|
+
obfuscated, not confidential, and may be rotated by the vendor. Pass
|
|
90
|
+
`open_auth=(app_id, encrypted_secret)` to override it.
|
|
91
|
+
|
|
92
|
+
## Errors
|
|
93
|
+
|
|
94
|
+
All errors derive from `SiseliError`:
|
|
95
|
+
|
|
96
|
+
| Exception | Meaning | Typical handling (e.g. Home Assistant) |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `AuthenticationError` | Login rejected, or HTTP 401/403 after a re-login | start re-auth flow |
|
|
99
|
+
| `RateLimitError` (a `NetworkError`) | HTTP 429, see `.retry_after` | back off |
|
|
100
|
+
| `NetworkError` | Timeouts, connection errors, other HTTP errors (`.http_status`) | mark unavailable, retry later |
|
|
101
|
+
| `ApiError` | API returned a non-zero `code` | report `.code` / `.message` |
|
|
102
|
+
| `InvalidResponseError` | Body is not JSON or has an unexpected shape | log, retry later |
|
|
103
|
+
|
|
104
|
+
## Writing configuration
|
|
105
|
+
|
|
106
|
+
Use `safe_set_device_config()`; the low-level `set_device_config()` performs no
|
|
107
|
+
validation. Writes are allow-listed, range-checked, serialized per device,
|
|
108
|
+
never retried and verified by reading the value back (the result is
|
|
109
|
+
`UNKNOWN`, not success, when that is inconclusive). Battery-voltage keys need an
|
|
110
|
+
explicit `battery_nominal_voltage`, which is cross-checked against the live
|
|
111
|
+
`batteryVoltage` reading. See [`docs/api.md`](docs/api.md) for details.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from siseli import ConfigAccess
|
|
115
|
+
|
|
116
|
+
result = await client.safe_set_device_config(
|
|
117
|
+
device.id, key="buzzerEnabled", value=False, dry_run=True
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Development
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
pip install -e ".[dev]"
|
|
125
|
+
ruff check siseli tests && mypy siseli && pytest
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Development plan
|
|
129
|
+
|
|
130
|
+
See [`roadmap.md`](roadmap.md) for the full development plan.
|
|
131
|
+
|
|
132
|
+
## API documentation
|
|
133
|
+
|
|
134
|
+
See [`docs/api.md`](docs/api.md).
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
python_siseli-0.3.0.dist-info/licenses/LICENSE,sha256=4D06esKe5FeqAgmsB8P6fx7Tn5qs-0H6EHbsomlpz04,1062
|
|
2
|
+
siseli/__init__.py,sha256=NhbCRKmcUNQEWnpHV5uBpdGNHnvwaEjw13JeYyununY,1694
|
|
3
|
+
siseli/_utils.py,sha256=FjRnheOn_dm4roOvYOEMAcmA9NkOkRwAJuhYggdvvuc,1778
|
|
4
|
+
siseli/alarms.py,sha256=a3rDmonTdwy1henrV6GwjWovb8PTP5lAegCcDWyQnDg,4958
|
|
5
|
+
siseli/auth.py,sha256=4A9KeE_rQcEc5c6Tz8pZsq2K_DdIs3C3z362VbmyaYQ,7975
|
|
6
|
+
siseli/client.py,sha256=cFACRufaGFzqglBAo9M5uUWUT3hkQ26OAxkSIf5T9SQ,22046
|
|
7
|
+
siseli/config.py,sha256=rIvl97tRQTI2h64LGR789vi1-08pRl4G45mMM3xMzgc,9673
|
|
8
|
+
siseli/config_safety.py,sha256=oC8l9g3ggnffePOFWSUXp8YusH6EDimfyVhOxUw-I9A,13958
|
|
9
|
+
siseli/const.py,sha256=57eVMzu9BA_vRuQ835iG_pimxMZKS_bW4KDZKo7dmYQ,660
|
|
10
|
+
siseli/dashboard.py,sha256=UMTzDHcPdw7JU1wQ1WhrIB1zxzIO_0KLzm19k1W20xQ,3430
|
|
11
|
+
siseli/device.py,sha256=iGZARAaJ-ms8SSWnOIF1UrZAtnH7VECK4Qkt-wSaOvg,2724
|
|
12
|
+
siseli/dictionary.py,sha256=gW-6ClHSAXlHm4NvS_-HmPq5815goMXYaTooftuEm60,1258
|
|
13
|
+
siseli/exceptions.py,sha256=2EotluJ_qx_8VU5uXvbdw0MVFf2EJTTUdIky2JKcOUU,2274
|
|
14
|
+
siseli/history.py,sha256=ctE7OtCGS8pARZBybBGN5BcqXlHuOMdJ1hvonXhQfVk,3624
|
|
15
|
+
siseli/open_auth.py,sha256=EhjiAFKKN3gaWeoSiZ3jZ60nUUnIWidfpmDBA8Gr0pQ,5858
|
|
16
|
+
siseli/overview.py,sha256=JPbzkozaBi4pHHCW1H04YoURzI1SO_piZFWotlK9GHY,3958
|
|
17
|
+
siseli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
siseli/state.py,sha256=qiuR9RLVTqc0SX9QRdSIStlANkRU5nrHSqymWY9OwY0,6182
|
|
19
|
+
siseli/station.py,sha256=ONJcJTUxwNnpfd9CWcl_rtSdAcrEuUlrp66jV_713EQ,5829
|
|
20
|
+
siseli/models/__init__.py,sha256=WSIXRM_JRKNhB_hDwxrpeQgdqKUHdbT3KiFvdrLrrzY,1242
|
|
21
|
+
siseli/models/alarm.py,sha256=Id8OyN2HQ-EeU-E9AleUHmhFuOyTH27r1G5pT3g8nzM,887
|
|
22
|
+
siseli/models/auth.py,sha256=6Os8Z5ATn-KINkxR26slHFqG3YjHzW5Zjve4n9pVbug,395
|
|
23
|
+
siseli/models/common.py,sha256=zOEz8W-NGaNW7H-jUYOup7D9-cidWpvpRjeTRTe3WiY,960
|
|
24
|
+
siseli/models/config.py,sha256=VXlzXYij6ZhY0zmdaTjVxiA86H46mczBwcMI9L-xMf0,680
|
|
25
|
+
siseli/models/dashboard.py,sha256=NSB7nGn6uFiVAEsMbJejkL6LYiyOCWHmYwCtiDh8gvQ,1091
|
|
26
|
+
siseli/models/device.py,sha256=u57-csypaF-c5hAimqb8GIMeZqYZMKMhYFBTVuBRSfQ,657
|
|
27
|
+
siseli/models/dictionary.py,sha256=d6KCu77UMlPcIDON8G3sjuytkSfbI5go1y3I_jAGTX8,422
|
|
28
|
+
siseli/models/history.py,sha256=dx26VWLJosucMvwL36vojvAguvkMiv5GEKTllUtZV0Y,791
|
|
29
|
+
siseli/models/state.py,sha256=S4u2-H9_Iyq0Qeg6hpplevMnmNu4Ymb75Q8Z3xNNr10,7244
|
|
30
|
+
siseli/models/station.py,sha256=3mRoshxF1GyCm07eWLrFn5BddZgmEyYzJEULS2voEss,2798
|
|
31
|
+
python_siseli-0.3.0.dist-info/METADATA,sha256=ILy4jvGuGSVI9O7YroHhdN7hWOPM7jcBkvFlcRLglOI,4468
|
|
32
|
+
python_siseli-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
33
|
+
python_siseli-0.3.0.dist-info/top_level.txt,sha256=Dofr9c7hGvRRV6ij6aoPuAZqxEjkgtsBeN4KtFHbGgo,7
|
|
34
|
+
python_siseli-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vvkor
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
siseli/__init__.py
CHANGED
|
@@ -16,7 +16,9 @@ from .config_safety import (
|
|
|
16
16
|
from .exceptions import (
|
|
17
17
|
ApiError,
|
|
18
18
|
AuthenticationError,
|
|
19
|
+
InvalidResponseError,
|
|
19
20
|
NetworkError,
|
|
21
|
+
RateLimitError,
|
|
20
22
|
SiseliError,
|
|
21
23
|
TokenExpiredError,
|
|
22
24
|
)
|
|
@@ -60,6 +62,8 @@ __all__ = [
|
|
|
60
62
|
"TokenExpiredError",
|
|
61
63
|
"ApiError",
|
|
62
64
|
"NetworkError",
|
|
65
|
+
"RateLimitError",
|
|
66
|
+
"InvalidResponseError",
|
|
63
67
|
"Alarm",
|
|
64
68
|
"AlarmReport",
|
|
65
69
|
"AttributeGroup",
|
siseli/_utils.py
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
import re
|
|
6
|
+
from datetime import UTC, datetime
|
|
6
7
|
from typing import Any
|
|
7
8
|
|
|
8
9
|
|
|
@@ -14,7 +15,12 @@ def parse_datetime(value: str | None) -> datetime | None:
|
|
|
14
15
|
text = f"{text}-01-01"
|
|
15
16
|
elif len(text) == 7 and text[4] == "-":
|
|
16
17
|
text = f"{text}-01"
|
|
17
|
-
return datetime.fromisoformat(text)
|
|
18
|
+
return ensure_aware(datetime.fromisoformat(text))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def ensure_aware(value: datetime) -> datetime:
|
|
22
|
+
"""Treat naive timestamps from the API as UTC so they compare safely."""
|
|
23
|
+
return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
|
|
18
24
|
|
|
19
25
|
|
|
20
26
|
def serialize_datetime(value: datetime | str | None) -> str | None:
|
|
@@ -32,3 +38,23 @@ def extract_value(raw: Any) -> Any:
|
|
|
32
38
|
if key in raw:
|
|
33
39
|
return raw[key]
|
|
34
40
|
return raw
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def as_dict(value: Any) -> dict:
|
|
44
|
+
"""Return *value* if it is a dict, else an empty dict (handles JSON null)."""
|
|
45
|
+
return value if isinstance(value, dict) else {}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def as_list(value: Any) -> list:
|
|
49
|
+
"""Return *value* if it is a list, else an empty list (handles JSON null)."""
|
|
50
|
+
return value if isinstance(value, list) else []
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def validate_path_segment(value: str, label: str) -> str:
|
|
57
|
+
"""Reject values that could alter the URL path when interpolated."""
|
|
58
|
+
if not isinstance(value, str) or not _SEGMENT_RE.match(value):
|
|
59
|
+
raise ValueError(f"invalid {label}: {value!r}")
|
|
60
|
+
return value
|
siseli/alarms.py
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from typing import Any
|
|
6
7
|
|
|
7
|
-
from ._utils import parse_datetime, serialize_datetime
|
|
8
|
+
from ._utils import as_dict, as_list, parse_datetime, serialize_datetime
|
|
8
9
|
from .const import DEFAULT_PAGE_SIZE
|
|
9
10
|
from .models.alarm import Alarm, AlarmReport
|
|
10
11
|
from .models.common import PagedResult
|
|
@@ -100,7 +101,8 @@ async def fetch_alarm_list(
|
|
|
100
101
|
"orderByCreatedTimeDesc": order_by_created_time_desc,
|
|
101
102
|
},
|
|
102
103
|
)
|
|
103
|
-
|
|
104
|
+
data = as_dict(data)
|
|
105
|
+
items = [_parse_alarm(item) for item in as_list(data.get("list"))]
|
|
104
106
|
return PagedResult(
|
|
105
107
|
page=data.get("page", page),
|
|
106
108
|
count=data.get("count", count),
|
|
@@ -149,7 +151,8 @@ async def fetch_alarm_reports(
|
|
|
149
151
|
"orderByCreatedAtAsc": order_by_created_at_asc,
|
|
150
152
|
},
|
|
151
153
|
)
|
|
152
|
-
|
|
154
|
+
data = as_dict(data)
|
|
155
|
+
items = [_parse_alarm_report(item) for item in as_list(data.get("list"))]
|
|
153
156
|
return PagedResult(
|
|
154
157
|
page=data.get("page", page),
|
|
155
158
|
count=data.get("count", count),
|
siseli/auth.py
CHANGED
|
@@ -4,11 +4,17 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import hashlib
|
|
6
6
|
import logging
|
|
7
|
-
from datetime import UTC, datetime
|
|
7
|
+
from datetime import UTC, datetime, timedelta
|
|
8
8
|
|
|
9
9
|
import httpx
|
|
10
10
|
|
|
11
|
-
from .
|
|
11
|
+
from ._utils import parse_datetime
|
|
12
|
+
from .exceptions import (
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
InvalidResponseError,
|
|
15
|
+
NetworkError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
)
|
|
12
18
|
from .models.auth import TokenInfo
|
|
13
19
|
|
|
14
20
|
_LOGGER = logging.getLogger(__name__)
|
|
@@ -22,10 +28,15 @@ def _md5(text: str) -> str:
|
|
|
22
28
|
return hashlib.md5(text.encode()).hexdigest() # noqa: S324
|
|
23
29
|
|
|
24
30
|
|
|
25
|
-
def
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
31
|
+
def _mask_account(account: str) -> str:
|
|
32
|
+
"""Obfuscate the account for logs: ``user@example.com`` -> ``u***@example.com``."""
|
|
33
|
+
local, sep, domain = account.partition("@")
|
|
34
|
+
masked = f"{local[:1]}***" if local else "***"
|
|
35
|
+
return f"{masked}{sep}{domain}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Treat tokens as expired slightly early to avoid racing the server clock.
|
|
39
|
+
EXPIRY_MARGIN = timedelta(seconds=30)
|
|
29
40
|
|
|
30
41
|
|
|
31
42
|
def _extract_api_message(response: httpx.Response) -> str | None:
|
|
@@ -44,12 +55,19 @@ def _extract_api_message(response: httpx.Response) -> str | None:
|
|
|
44
55
|
value = body.get(key)
|
|
45
56
|
if value and isinstance(value, str):
|
|
46
57
|
return value[:200]
|
|
47
|
-
except Exception: # noqa: BLE001
|
|
58
|
+
except Exception: # noqa: BLE001, S110
|
|
48
59
|
pass
|
|
49
60
|
text = (response.text or "").strip()
|
|
50
61
|
return text[:200] if text else None
|
|
51
62
|
|
|
52
63
|
|
|
64
|
+
def _retry_after_seconds(response: httpx.Response) -> float | None:
|
|
65
|
+
try:
|
|
66
|
+
return max(0.0, float(response.headers.get("Retry-After", "")))
|
|
67
|
+
except ValueError:
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
53
71
|
class Auth:
|
|
54
72
|
"""Manages credentials and the current access token.
|
|
55
73
|
|
|
@@ -59,6 +77,7 @@ class Auth:
|
|
|
59
77
|
|
|
60
78
|
def __init__(self, account: str, password: str) -> None:
|
|
61
79
|
self._account = account
|
|
80
|
+
self._masked = _mask_account(account)
|
|
62
81
|
# The web client sends the MD5 hash of the plaintext password.
|
|
63
82
|
self._password_hash = _md5(password)
|
|
64
83
|
self._token_info: TokenInfo | None = None
|
|
@@ -71,7 +90,7 @@ class Auth:
|
|
|
71
90
|
on network / timeout errors so callers can distinguish the two cases.
|
|
72
91
|
"""
|
|
73
92
|
endpoint = "/apis/login/account"
|
|
74
|
-
_LOGGER.debug("Siseli auth: POST %s (account=%
|
|
93
|
+
_LOGGER.debug("Siseli auth: POST %s (account=%s)", endpoint, self._masked)
|
|
75
94
|
|
|
76
95
|
try:
|
|
77
96
|
response = await http.post(
|
|
@@ -79,17 +98,17 @@ class Auth:
|
|
|
79
98
|
json={"account": self._account, "password": self._password_hash},
|
|
80
99
|
)
|
|
81
100
|
except httpx.TimeoutException as exc:
|
|
82
|
-
_LOGGER.warning("Siseli auth: request timed out for account=%
|
|
101
|
+
_LOGGER.warning("Siseli auth: request timed out for account=%s", self._masked)
|
|
83
102
|
raise NetworkError(f"Login request timed out: {exc}") from exc
|
|
84
103
|
except httpx.HTTPError as exc:
|
|
85
104
|
_LOGGER.warning(
|
|
86
|
-
"Siseli auth: network error for account=%
|
|
105
|
+
"Siseli auth: network error for account=%s: %s", self._masked, exc
|
|
87
106
|
)
|
|
88
107
|
raise NetworkError(f"Login request failed: {exc}") from exc
|
|
89
108
|
|
|
90
109
|
http_status = response.status_code
|
|
91
110
|
_LOGGER.debug(
|
|
92
|
-
"Siseli auth: response status=%d for account=%
|
|
111
|
+
"Siseli auth: response status=%d for account=%s", http_status, self._masked
|
|
93
112
|
)
|
|
94
113
|
|
|
95
114
|
# For HTTP error responses, extract a safe diagnostic message and raise
|
|
@@ -97,31 +116,43 @@ class Auth:
|
|
|
97
116
|
if not response.is_success:
|
|
98
117
|
api_message = _extract_api_message(response)
|
|
99
118
|
_LOGGER.warning(
|
|
100
|
-
"Siseli auth: failed for account=%
|
|
101
|
-
self.
|
|
119
|
+
"Siseli auth: failed for account=%s — HTTP %d%s",
|
|
120
|
+
self._masked,
|
|
102
121
|
http_status,
|
|
103
122
|
f", api_message={api_message!r}" if api_message else "",
|
|
104
123
|
)
|
|
105
124
|
diag = f"HTTP {http_status}"
|
|
106
125
|
if api_message:
|
|
107
126
|
diag = f"{diag}: {api_message}"
|
|
108
|
-
if http_status
|
|
109
|
-
raise
|
|
127
|
+
if http_status == 429:
|
|
128
|
+
raise RateLimitError(
|
|
129
|
+
f"Login request failed: {diag}",
|
|
130
|
+
retry_after=_retry_after_seconds(response),
|
|
131
|
+
)
|
|
132
|
+
if http_status >= 500 or http_status == 408:
|
|
133
|
+
raise NetworkError(
|
|
134
|
+
f"Login request failed: {diag}", http_status=http_status
|
|
135
|
+
)
|
|
110
136
|
raise AuthenticationError(
|
|
111
137
|
f"Login failed: {diag}",
|
|
112
138
|
http_status=http_status,
|
|
113
139
|
api_message=api_message,
|
|
114
140
|
)
|
|
115
141
|
|
|
116
|
-
|
|
142
|
+
try:
|
|
143
|
+
body = response.json()
|
|
144
|
+
except ValueError as exc:
|
|
145
|
+
raise InvalidResponseError("Login response is not valid JSON") from exc
|
|
146
|
+
if not isinstance(body, dict):
|
|
147
|
+
raise InvalidResponseError("Login response has unexpected shape")
|
|
117
148
|
if body.get("code") != 0:
|
|
118
149
|
api_message = body.get("message") or body.get("error") or body.get("detail")
|
|
119
150
|
if api_message:
|
|
120
151
|
api_message = str(api_message)
|
|
121
152
|
_LOGGER.warning(
|
|
122
|
-
"Siseli auth: API returned non-zero code=%r for account=%
|
|
153
|
+
"Siseli auth: API returned non-zero code=%r for account=%s, message=%r",
|
|
123
154
|
body.get("code"),
|
|
124
|
-
self.
|
|
155
|
+
self._masked,
|
|
125
156
|
api_message,
|
|
126
157
|
)
|
|
127
158
|
raise AuthenticationError(
|
|
@@ -130,17 +161,23 @@ class Auth:
|
|
|
130
161
|
api_message=api_message,
|
|
131
162
|
)
|
|
132
163
|
|
|
133
|
-
data = body
|
|
164
|
+
data = body.get("data")
|
|
165
|
+
if (
|
|
166
|
+
not isinstance(data, dict)
|
|
167
|
+
or not data.get("accessToken")
|
|
168
|
+
or not data.get("refreshToken")
|
|
169
|
+
):
|
|
170
|
+
raise InvalidResponseError("Login response is missing tokens")
|
|
134
171
|
self._token_info = TokenInfo(
|
|
135
172
|
access_token=data["accessToken"],
|
|
136
173
|
refresh_token=data["refreshToken"],
|
|
137
|
-
access_token_expires_at=
|
|
138
|
-
refresh_token_expires_at=
|
|
174
|
+
access_token_expires_at=parse_datetime(data.get("accessTokenWillExpiredAt")),
|
|
175
|
+
refresh_token_expires_at=parse_datetime(data.get("refreshTokenWillExpiredAt")),
|
|
139
176
|
auth_id=data.get("authId", ""),
|
|
140
177
|
account=data.get("account", self._account),
|
|
141
178
|
user_id=data.get("userId", ""),
|
|
142
179
|
)
|
|
143
|
-
_LOGGER.debug("Siseli auth: login successful for account=%
|
|
180
|
+
_LOGGER.debug("Siseli auth: login successful for account=%s", self._masked)
|
|
144
181
|
return self._token_info
|
|
145
182
|
|
|
146
183
|
@property
|
|
@@ -154,6 +191,10 @@ class Auth:
|
|
|
154
191
|
raise AuthenticationError("Not authenticated — call authenticate() first")
|
|
155
192
|
return self._token_info.access_token
|
|
156
193
|
|
|
194
|
+
def invalidate(self) -> None:
|
|
195
|
+
"""Forget the current token so the next call logs in again."""
|
|
196
|
+
self._token_info = None
|
|
197
|
+
|
|
157
198
|
@property
|
|
158
199
|
def token_info(self) -> TokenInfo | None:
|
|
159
200
|
"""Return token metadata, or *None* if not authenticated."""
|
|
@@ -166,4 +207,4 @@ class Auth:
|
|
|
166
207
|
expires_at = self._token_info.access_token_expires_at
|
|
167
208
|
if expires_at is None:
|
|
168
209
|
return True
|
|
169
|
-
return datetime.now(UTC) < expires_at
|
|
210
|
+
return datetime.now(UTC) + EXPIRY_MARGIN < expires_at
|