uw-api 0.2.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.
uw_api/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ from uw_api.client import UWClient
4
+ from uw_api.exceptions import (
5
+ UWApiError,
6
+ UWAuthError,
7
+ UWDataParseError,
8
+ UWPDFExtractError,
9
+ UWRateLimitError,
10
+ UWSessionExpiredError,
11
+ )
12
+
13
+ __version__ = "0.2.0"
14
+ __all__ = [
15
+ "UWApiError",
16
+ "UWAuthError",
17
+ "UWClient",
18
+ "UWDataParseError",
19
+ "UWPDFExtractError",
20
+ "UWRateLimitError",
21
+ "UWSessionExpiredError",
22
+ "__version__",
23
+ ]
uw_api/auth.py ADDED
@@ -0,0 +1,216 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import logging
6
+ import re
7
+ import secrets
8
+ import time
9
+ from urllib.parse import urlparse
10
+
11
+ import httpx
12
+
13
+ from uw_api.exceptions import UWAuthError
14
+
15
+ _LOGGER = logging.getLogger(__name__)
16
+
17
+ _LOGIN_BASE = "https://account.uw.co.uk"
18
+ _LOGIN_PAGE = f"{_LOGIN_BASE}/v2/login"
19
+ _GRAPHQL_URL = "https://myaccount.uw.co.uk/server/graphql"
20
+ _REDIRECT_HOST = "myaccount.uw.co.uk"
21
+
22
+
23
+ def _b64url(data: bytes) -> str:
24
+ import base64
25
+
26
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
27
+
28
+
29
+ class UWAuth:
30
+ def __init__(
31
+ self,
32
+ client: httpx.AsyncClient,
33
+ email: str,
34
+ password: str,
35
+ login_page: str = _LOGIN_PAGE,
36
+ graphql_url: str = _GRAPHQL_URL,
37
+ max_retries: int = 3,
38
+ backoff_base: float = 1.0,
39
+ ) -> None:
40
+ self._client = client
41
+ self._email = email
42
+ self._password = password
43
+ self._login_page = login_page
44
+ self._graphql_url = graphql_url
45
+ self._max_retries = max_retries
46
+ self._backoff_base = backoff_base
47
+
48
+ self._session_expires_at: float = 0.0
49
+ self._authenticated = False
50
+
51
+ @property
52
+ def is_authenticated(self) -> bool:
53
+ return self._authenticated and time.monotonic() < self._session_expires_at
54
+
55
+ @property
56
+ def csrf_token(self) -> str | None:
57
+ return None
58
+
59
+ @property
60
+ def graphql_url(self) -> str:
61
+ return self._graphql_url
62
+
63
+ def _extract_csrf_token(self, text: str) -> str | None:
64
+ match = re.search(r'<input[^>]+name="_csrf"[^>]+value="([^"]+)"', text)
65
+ if match:
66
+ return match.group(1)
67
+ return None
68
+
69
+ def _extract_login_challenge(self, text: str) -> str | None:
70
+ match = re.search(r'name="login_challenge"\s+value="([^"]+)"', text)
71
+ if match:
72
+ return match.group(1)
73
+ match = re.search(r"login_challenge=([a-zA-Z0-9_-]+)", text)
74
+ if match:
75
+ return match.group(1)
76
+ match = re.search(r'"login_challenge":"([^"]+)"', text)
77
+ return match.group(1) if match else None
78
+
79
+ def _generate_castle_token(self) -> str:
80
+ return (
81
+ "eyJhbGciOiJFUzI1NiJ9.eyJpZCI6IjFlY2ZhMzUyLWQyZWQtNDRm"
82
+ "Yy04Y2EzLTAzOTE5NmI1Nzg5NyIsInR5cGUiOiJkZXZpY2UiLCJ2ZXJ"
83
+ "zaW9uIjoiMi4zLjAiLCJ0aW1lc3RhbXAiOjE3NTMzMDc3Nzl9." + secrets.token_hex(64)
84
+ )
85
+
86
+ def _generate_pkce(self) -> tuple[str, str]:
87
+ code_verifier = secrets.token_urlsafe(64)
88
+ code_challenge = _b64url(hashlib.sha256(code_verifier.encode()).digest())
89
+ return code_verifier, code_challenge
90
+
91
+ async def _fetch_login_page(self) -> httpx.Response:
92
+ response = await self._client.get(self._login_page)
93
+ response.raise_for_status()
94
+ return response
95
+
96
+ async def login(self) -> None:
97
+ code_verifier, code_challenge = self._generate_pkce()
98
+
99
+ for attempt in range(self._max_retries):
100
+ try:
101
+ login_page = await self._fetch_login_page()
102
+ page_text = login_page.text
103
+
104
+ csrf_token = self._extract_csrf_token(page_text)
105
+ login_challenge = self._extract_login_challenge(page_text)
106
+
107
+ if not csrf_token:
108
+ raise UWAuthError("Could not extract CSRF token from login page")
109
+ if not login_challenge:
110
+ raise UWAuthError("Could not extract login_challenge from login page")
111
+
112
+ castle_token = self._generate_castle_token()
113
+
114
+ payload = {
115
+ "_csrf": csrf_token,
116
+ "login_challenge": login_challenge,
117
+ "username": self._email,
118
+ "password": self._password,
119
+ "castle_request_token": castle_token,
120
+ }
121
+
122
+ response = await self._client.post(
123
+ self._login_page,
124
+ data=payload,
125
+ headers={
126
+ "Referer": self._login_page,
127
+ "Origin": _LOGIN_BASE,
128
+ },
129
+ )
130
+
131
+ if response.status_code == 429:
132
+ retry_after = int(
133
+ response.headers.get("Retry-After", self._backoff_base * (2**attempt))
134
+ )
135
+ await asyncio.sleep(retry_after)
136
+ continue
137
+
138
+ if response.status_code in (401, 403):
139
+ raise UWAuthError("Invalid credentials")
140
+
141
+ if response.is_redirect or response.status_code in (302, 303):
142
+ await self._follow_redirects(response, code_verifier, code_challenge)
143
+ self._authenticated = True
144
+ self._session_expires_at = time.monotonic() + 3600
145
+ return
146
+
147
+ if response.status_code >= 500:
148
+ await asyncio.sleep(self._backoff_base * (2**attempt))
149
+ continue
150
+
151
+ page_text = response.text
152
+ error = self._extract_error(page_text)
153
+ if error:
154
+ raise UWAuthError(error)
155
+ raise UWAuthError(f"Unexpected login response: {response.status_code}")
156
+
157
+ except UWAuthError:
158
+ raise
159
+ except httpx.HTTPStatusError as exc:
160
+ if exc.response.status_code == 429:
161
+ retry_after = int(
162
+ exc.response.headers.get("Retry-After", self._backoff_base * (2**attempt))
163
+ )
164
+ await asyncio.sleep(retry_after)
165
+ continue
166
+ raise UWAuthError(f"Login failed: {exc}") from exc
167
+ except Exception as exc:
168
+ if attempt == self._max_retries - 1:
169
+ raise UWAuthError(
170
+ f"Login failed after {self._max_retries} attempts: {exc}"
171
+ ) from exc
172
+ await asyncio.sleep(self._backoff_base * (2**attempt))
173
+
174
+ async def _follow_redirects(
175
+ self,
176
+ response: httpx.Response,
177
+ code_verifier: str,
178
+ code_challenge: str,
179
+ ) -> None:
180
+ location = response.headers.get("Location", "")
181
+ if not location:
182
+ return
183
+
184
+ redirect_response = await self._client.get(
185
+ location,
186
+ headers={"Referer": self._login_page},
187
+ )
188
+
189
+ final_url = str(redirect_response.url)
190
+ parsed = urlparse(final_url)
191
+
192
+ if parsed.hostname and _REDIRECT_HOST in parsed.hostname:
193
+ return
194
+
195
+ if redirect_response.is_redirect or redirect_response.status_code in (302, 303):
196
+ await self._follow_redirects(redirect_response, code_verifier, code_challenge)
197
+
198
+ def _extract_error(self, text: str) -> str | None:
199
+ patterns = [
200
+ r'class="[^"]*error[^"]*"[^>]*>([^<]+)<',
201
+ r"Invalid\s+(?:email|password|credentials)",
202
+ r"login\s+failed",
203
+ ]
204
+ for pattern in patterns:
205
+ match = re.search(pattern, text, re.IGNORECASE)
206
+ if match:
207
+ return match.group(1) if match.lastindex else match.group(0)
208
+ return None
209
+
210
+ async def ensure_authenticated(self) -> None:
211
+ if not self.is_authenticated:
212
+ await self.login()
213
+
214
+ async def re_auth(self) -> None:
215
+ self._authenticated = False
216
+ await self.login()
uw_api/client.py ADDED
@@ -0,0 +1,148 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from uw_api.auth import UWAuth
10
+ from uw_api.exceptions import UWApiError, UWRateLimitError
11
+ from uw_api.graphql import UWGraphQL
12
+
13
+ _LOGGER = logging.getLogger(__name__)
14
+
15
+
16
+ class UWClient:
17
+ def __init__(
18
+ self,
19
+ email: str,
20
+ password: str,
21
+ timeout: float = 30.0,
22
+ max_retries: int = 3,
23
+ backoff_base: float = 1.0,
24
+ ) -> None:
25
+ self._email = email
26
+ self._password = password
27
+ self._timeout = timeout
28
+ self._max_retries = max_retries
29
+ self._backoff_base = backoff_base
30
+
31
+ self._http_client = httpx.AsyncClient(
32
+ http2=False,
33
+ timeout=httpx.Timeout(timeout),
34
+ follow_redirects=True,
35
+ )
36
+
37
+ self._auth = UWAuth(
38
+ self._http_client,
39
+ email=self._email,
40
+ password=self._password,
41
+ max_retries=max_retries,
42
+ backoff_base=backoff_base,
43
+ )
44
+
45
+ self.gql = UWGraphQL(self, self._http_client)
46
+
47
+ @property
48
+ def http_client(self) -> httpx.AsyncClient:
49
+ return self._http_client
50
+
51
+ async def login(self) -> None:
52
+ await self._auth.login()
53
+
54
+ async def close(self) -> None:
55
+ await self._http_client.aclose()
56
+
57
+ async def __aenter__(self) -> UWClient:
58
+ return self
59
+
60
+ async def __aexit__(self, *args: object) -> None:
61
+ await self.close()
62
+
63
+ async def graphql_request(
64
+ self,
65
+ operation_name: str,
66
+ query: str,
67
+ variables: dict[str, Any] | None = None,
68
+ ) -> dict[str, Any]:
69
+ await self._auth.ensure_authenticated()
70
+
71
+ body: dict[str, Any] = {
72
+ "operationName": operation_name,
73
+ "query": query,
74
+ "variables": variables or {},
75
+ }
76
+
77
+ for attempt in range(self._max_retries):
78
+ try:
79
+ response = await self._http_client.post(
80
+ self._auth.graphql_url,
81
+ json=body,
82
+ headers={
83
+ "Content-Type": "application/json",
84
+ "x-csrf-token": self._auth.csrf_token or "1",
85
+ },
86
+ )
87
+
88
+ if response.status_code == 401:
89
+ _LOGGER.warning("Session expired, re-authenticating")
90
+ await self._auth.re_auth()
91
+ continue
92
+
93
+ if response.status_code == 429:
94
+ retry_after = int(
95
+ response.headers.get(
96
+ "Retry-After",
97
+ self._backoff_base * (2**attempt),
98
+ )
99
+ )
100
+ if attempt == self._max_retries - 1:
101
+ raise UWRateLimitError(f"Rate limited. Retry after {retry_after}s")
102
+ await asyncio.sleep(retry_after)
103
+ continue
104
+
105
+ if response.status_code >= 500:
106
+ await asyncio.sleep(self._backoff_base * (2**attempt))
107
+ continue
108
+
109
+ response.raise_for_status()
110
+ raw: object = response.json()
111
+ if not isinstance(raw, dict):
112
+ raise UWApiError(f"Unexpected response type: {type(raw)}")
113
+ data: dict[str, Any] = raw
114
+
115
+ errors = data.get("errors")
116
+ if errors:
117
+ raise UWApiError(f"GraphQL errors: {errors}")
118
+
119
+ result = data.get("data", data)
120
+ if not isinstance(result, dict):
121
+ raise UWApiError(f"Unexpected data key type: {type(result)}")
122
+ return result
123
+
124
+ except (UWRateLimitError, UWApiError):
125
+ raise
126
+ except httpx.HTTPStatusError as exc:
127
+ if exc.response.status_code == 401:
128
+ _LOGGER.warning("Session expired, re-authenticating")
129
+ await self._auth.re_auth()
130
+ continue
131
+ if exc.response.status_code == 429:
132
+ retry_after = int(
133
+ exc.response.headers.get(
134
+ "Retry-After",
135
+ self._backoff_base * (2**attempt),
136
+ )
137
+ )
138
+ if attempt == self._max_retries - 1:
139
+ raise UWRateLimitError(f"Rate limited. Retry after {retry_after}s") from exc
140
+ await asyncio.sleep(retry_after)
141
+ continue
142
+ raise UWApiError(f"HTTP {exc.response.status_code}: {exc}") from exc
143
+ except (httpx.RequestError, httpx.TimeoutException) as exc:
144
+ if attempt == self._max_retries - 1:
145
+ raise UWApiError(f"Request failed: {exc}") from exc
146
+ await asyncio.sleep(self._backoff_base * (2**attempt))
147
+
148
+ raise UWApiError(f"Request failed after {self._max_retries} attempts")
uw_api/exceptions.py ADDED
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class UWApiError(Exception):
5
+ pass
6
+
7
+
8
+ class UWAuthError(UWApiError):
9
+ pass
10
+
11
+
12
+ class UWSessionExpiredError(UWApiError):
13
+ pass
14
+
15
+
16
+ class UWRateLimitError(UWApiError):
17
+ pass
18
+
19
+
20
+ class UWDataParseError(UWApiError):
21
+ pass
22
+
23
+
24
+ class UWPDFExtractError(UWApiError):
25
+ pass
@@ -0,0 +1,252 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import UTC, datetime
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ import httpx
7
+
8
+ from uw_api.graphql.queries import (
9
+ GET_ACCOUNT,
10
+ GET_BALANCE,
11
+ GET_BILLS,
12
+ GET_ENERGY_SERVICES,
13
+ GET_EV_TARIFF,
14
+ GET_LIVE_SERVICES,
15
+ GET_PDF_URL,
16
+ )
17
+ from uw_api.models.account import UWAccount
18
+ from uw_api.models.bill import Bill, BillPDFMetadata, BillStatus
19
+ from uw_api.models.energy import EnergyConsumption, EnergyTariff, EnergyUsage, UsageReading
20
+ from uw_api.models.meter import Meter, MeterReading, MeterType
21
+
22
+ if TYPE_CHECKING:
23
+ from uw_api.client import UWClient
24
+
25
+
26
+ class UWGraphQL:
27
+ def __init__(self, client: UWClient, http_client: httpx.AsyncClient) -> None:
28
+ self._client = client
29
+ self._http_client = http_client
30
+
31
+ async def get_account(self) -> UWAccount:
32
+ data = await self._client.graphql_request("GetAccount", GET_ACCOUNT)
33
+ account = data["account"]
34
+ return UWAccount(
35
+ account_id=account["id"],
36
+ account_number=account["number"],
37
+ email=self._client._email,
38
+ )
39
+
40
+ async def get_energy_services(self) -> list[dict[str, Any]]:
41
+ data = await self._client.graphql_request(
42
+ "accountEnergyServicesWithReads",
43
+ GET_ENERGY_SERVICES,
44
+ {"includeEndedWithin": 108000},
45
+ )
46
+ return list(data.get("account", {}).get("energy", {}).get("services", []))
47
+
48
+ async def get_energy_usage(self) -> list[EnergyUsage]:
49
+ services = await self.get_energy_services()
50
+ results: list[EnergyUsage] = []
51
+ for svc in services:
52
+ meter = svc.get("meterpoint", {}).get("installedMeter", {})
53
+ reads_data = meter.get("reads", {})
54
+ latest = reads_data.get("latestRead")
55
+ readings: list[UsageReading] = []
56
+ total_kwh: float = 0.0
57
+
58
+ if latest:
59
+ rr = latest.get("registerReading", {})
60
+ if rr:
61
+ read_date = latest.get("readDate", "")
62
+ dt = (
63
+ datetime.fromisoformat(read_date.replace("Z", "+00:00"))
64
+ if read_date
65
+ else datetime.now(tz=UTC)
66
+ )
67
+ val = float(rr.get("value", 0))
68
+ readings.append(
69
+ UsageReading(
70
+ date=dt,
71
+ value=val,
72
+ unit="kWh",
73
+ reading_type=("estimated" if latest.get("isEstimated") else "actual"),
74
+ )
75
+ )
76
+ total_kwh = val
77
+
78
+ results.append(
79
+ EnergyUsage(
80
+ service_id=svc.get("id", ""),
81
+ meter_number=meter.get("serialNumber", ""),
82
+ readings=readings,
83
+ total_consumption_kwh=total_kwh,
84
+ )
85
+ )
86
+ return results
87
+
88
+ async def get_consumption(self) -> EnergyConsumption | None:
89
+ services = await self.get_energy_services()
90
+ if not services:
91
+ return None
92
+
93
+ elec_kwh: float | None = None
94
+ gas_kwh: float | None = None
95
+
96
+ for svc in services:
97
+ fuel = svc.get("fuelType", "").upper()
98
+ meter = svc.get("meterpoint", {}).get("installedMeter", {})
99
+ latest = meter.get("reads", {}).get("latestRead", {})
100
+ rr = latest.get("registerReading", {})
101
+ val = float(rr.get("value", 0)) if rr.get("value") else 0.0
102
+
103
+ if fuel == "ELECTRICITY":
104
+ elec_kwh = val
105
+ elif fuel == "GAS":
106
+ gas_kwh = val
107
+
108
+ return EnergyConsumption(
109
+ service_id=services[0].get("id", ""),
110
+ period="latest",
111
+ electricity_kwh=elec_kwh,
112
+ gas_kwh=gas_kwh,
113
+ )
114
+
115
+ async def get_meters(self) -> list[Meter]:
116
+ services = await self.get_energy_services()
117
+ results: list[Meter] = []
118
+ for svc in services:
119
+ fuel = svc.get("fuelType", "").upper()
120
+ meter = svc.get("meterpoint", {}).get("installedMeter", {})
121
+ serial = meter.get("serialNumber", "")
122
+
123
+ meter_type = MeterType.ELECTRICITY if fuel == "ELECTRICITY" else MeterType.GAS
124
+
125
+ latest = meter.get("reads", {}).get("latestRead", {})
126
+ read_date_str = latest.get("readDate")
127
+ read_date = None
128
+ if read_date_str:
129
+ read_date = datetime.fromisoformat(read_date_str.replace("Z", "+00:00"))
130
+
131
+ results.append(
132
+ Meter(
133
+ meter_id=meter.get("id", ""),
134
+ service_id=svc.get("id", ""),
135
+ meter_type=meter_type,
136
+ meter_number=serial,
137
+ is_smart=meter.get("isSmart", False),
138
+ last_reading_date=read_date,
139
+ )
140
+ )
141
+ return results
142
+
143
+ async def get_meter_readings(self) -> list[MeterReading]:
144
+ services = await self.get_energy_services()
145
+ results: list[MeterReading] = []
146
+ for svc in services:
147
+ meter = svc.get("meterpoint", {}).get("installedMeter", {})
148
+ latest = meter.get("reads", {}).get("latestRead", {})
149
+ actual_read = meter.get("reads", {}).get("latestActualRead", {})
150
+
151
+ for read in [latest, actual_read]:
152
+ if not read or not read.get("id"):
153
+ continue
154
+ rr = read.get("registerReading", {})
155
+ if not rr.get("value"):
156
+ continue
157
+ read_date_str = read.get("readDate", "")
158
+ read_date = (
159
+ datetime.fromisoformat(read_date_str.replace("Z", "+00:00"))
160
+ if read_date_str
161
+ else datetime.now(tz=UTC)
162
+ )
163
+
164
+ results.append(
165
+ MeterReading(
166
+ reading_id=read.get("id"),
167
+ meter_id=meter.get("id", ""),
168
+ reading_date=read_date,
169
+ value=float(rr.get("value", 0)),
170
+ unit="kWh",
171
+ reading_type=("estimated" if read.get("isEstimated") else "actual"),
172
+ source=read.get("source", "customer"),
173
+ )
174
+ )
175
+ return results
176
+
177
+ async def get_tariff(self) -> EnergyTariff | None:
178
+ data = await self._client.graphql_request("accountServicesEvTariff", GET_EV_TARIFF)
179
+ services = data.get("account", {}).get("energy", {}).get("services", [])
180
+ if not services:
181
+ return None
182
+ tariff = services[0].get("energyTariff", {})
183
+ is_ev = tariff.get("isElectricVehicleTariff", False)
184
+ return EnergyTariff(
185
+ tariff_name="EV Tariff" if is_ev else "Standard Variable",
186
+ tariff_code="EV" if is_ev else "SVT",
187
+ unit_rate_pence=0.0,
188
+ standing_charge_pence=0.0,
189
+ )
190
+
191
+ async def get_bills(self) -> list[Bill]:
192
+ data = await self._client.graphql_request("GetBills", GET_BILLS)
193
+ billing = data.get("customerBilling", {})
194
+ bills_list = billing.get("accountBills", {}).get("billsList", [])
195
+ results: list[Bill] = []
196
+ for b in bills_list:
197
+ invoice_date = b.get("invoiceDate", {})
198
+ seconds = invoice_date.get("seconds", 0)
199
+ bill_dt = datetime.fromtimestamp(seconds, tz=UTC).date()
200
+ total = b.get("total", {})
201
+ pdf_url = b.get("url")
202
+
203
+ pdf_meta = None
204
+ if pdf_url and isinstance(pdf_url, str):
205
+ pdf_meta = BillPDFMetadata(pdf_url=pdf_url)
206
+
207
+ results.append(
208
+ Bill(
209
+ bill_id=b.get("invoiceId", ""),
210
+ account_id="",
211
+ bill_date=bill_dt,
212
+ period_start=bill_dt,
213
+ period_end=bill_dt,
214
+ total_amount_gbp=float(total.get("value", 0)),
215
+ status=BillStatus.PAID,
216
+ pdf=pdf_meta,
217
+ )
218
+ )
219
+ return results
220
+
221
+ async def get_pdf_url(self, month: int, year: int) -> str:
222
+ data = await self._client.graphql_request(
223
+ "GetPdfUrl", GET_PDF_URL, {"month": month, "year": year}
224
+ )
225
+ return str(data.get("customerBilling", {}).get("pdfUrl", ""))
226
+
227
+ async def get_balance(self) -> dict[str, Any]:
228
+ account_id = (await self._get_account_id()) or ""
229
+ data = await self._client.graphql_request("Balance", GET_BALANCE, {"id": account_id})
230
+ finance = data.get("finance", {}).get("account", {})
231
+ due = finance.get("dueBalance", {}).get("value", 0)
232
+ overdue = finance.get("overdueBalance", {}).get("value", 0)
233
+ return {
234
+ "due": float(due) if due else 0.0,
235
+ "overdue": float(overdue) if overdue else 0.0,
236
+ }
237
+
238
+ async def get_live_services(self) -> dict[str, Any]:
239
+ account_id = (await self._get_account_id()) or ""
240
+ data = await self._client.graphql_request(
241
+ "GetLiveServices", GET_LIVE_SERVICES, {"accountId": account_id}
242
+ )
243
+ result = data.get("getDashboardServices", {})
244
+ if isinstance(result, dict):
245
+ return result
246
+ return {}
247
+
248
+ async def _get_account_id(self) -> str | None:
249
+ data = await self._client.graphql_request("GetAccount", GET_ACCOUNT)
250
+ account = data.get("account", {})
251
+ aid = account.get("id")
252
+ return str(aid) if aid else None