Hydro-Quebec-API-Wrapper 3.1.0__py3-none-any.whl → 3.1.2__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.
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/METADATA +3 -2
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/RECORD +11 -12
- hydroqc/error.py +6 -0
- hydroqc/hydro_api/client.py +98 -69
- hydroqc/hydro_api/consts.py +3 -0
- hydroqc/types/outage.py +6 -5
- hydroqc/webuser.py +5 -9
- hydroqc/hydro_api/auth.py +0 -106
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/LICENSE +0 -0
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/WHEEL +0 -0
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/entry_points.txt +0 -0
- {Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/top_level.txt +0 -0
{Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: Hydro-Quebec-API-Wrapper
|
|
3
|
-
Version: 3.1.
|
|
3
|
+
Version: 3.1.2
|
|
4
4
|
Summary: A wrapper library to access hydro quebec API and more
|
|
5
5
|
Home-page: https://hydroqc.ca
|
|
6
6
|
Author-email: Hydroqc Team <info@hydroqc.ca>
|
|
@@ -15,10 +15,11 @@ Classifier: Operating System :: OS Independent
|
|
|
15
15
|
Requires-Python: >=3.10.0
|
|
16
16
|
Description-Content-Type: text/markdown
|
|
17
17
|
License-File: LICENSE
|
|
18
|
-
Requires-Dist: aiohttp (==3.
|
|
18
|
+
Requires-Dist: aiohttp (==3.9.1)
|
|
19
19
|
Requires-Dist: python-dateutil (==2.8.2)
|
|
20
20
|
Requires-Dist: pytz (==2023.3.post1)
|
|
21
21
|
Requires-Dist: aiocache (==0.12.2)
|
|
22
|
+
Requires-Dist: pkce (==1.0.3)
|
|
22
23
|
|
|
23
24
|
# HydroQC - Hydro Quebec API wrapper
|
|
24
25
|
|
{Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/RECORD
RENAMED
|
@@ -3,12 +3,12 @@ hydroqc/account.py,sha256=G8Cag4BMzz9sHYcr7wDxWssLT3C3bR3CdcOdyeL9D1E,3363
|
|
|
3
3
|
hydroqc/consts.py,sha256=LumqKzF9zpCwvrkadlBSdf0prILske68qe9QKGIJ9N8,208
|
|
4
4
|
hydroqc/customer.py,sha256=JOBHH7p_yh7cvKyDt2Ux_M0PDO9LoZK5B-pJhP5V11Y,6165
|
|
5
5
|
hydroqc/diagnostic.py,sha256=Pv51UC2061M5zyYqhwF3CV9-WXlnRATX7i9V7VAfngo,15516
|
|
6
|
-
hydroqc/error.py,sha256=
|
|
6
|
+
hydroqc/error.py,sha256=2HzWBak_RpuhfIrLhnfgNuY3FhUwwNyo1BLUDH6U0CI,598
|
|
7
7
|
hydroqc/logger.py,sha256=YwakuPt6ZGQUwjtowrvnsDd3yk-HLCWtyZvtDx2Np84,1255
|
|
8
8
|
hydroqc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
9
|
hydroqc/timerange.py,sha256=agf6cu826R0O1p_vsJ15hfvQzWRLSshGdN-2dQ3lixM,1136
|
|
10
10
|
hydroqc/utils.py,sha256=sxA5qkOA-Ui5jgEYItFQIeQdBsS_5z8J3xn8YxKZMow,232
|
|
11
|
-
hydroqc/webuser.py,sha256=
|
|
11
|
+
hydroqc/webuser.py,sha256=9Kgx-BR6G4tfAsHIaRX6G5jaqTPn94vOiXXN5uWu0w0,4410
|
|
12
12
|
hydroqc/contract/__init__.py,sha256=yZCzEvJhGmX3we4StrOhQ51KeR40DLct5ytKJo1y1Qc,547
|
|
13
13
|
hydroqc/contract/common.py,sha256=4j8wRwoZV-EeYBRhzk4IXhV1scVHrjIMsjfrbeZLxl8,15445
|
|
14
14
|
hydroqc/contract/contract_d.py,sha256=5s185i1hdxlXlFUTUR0r9DjQhqCGJRra9kErTYOqj48,798
|
|
@@ -20,10 +20,9 @@ hydroqc/contract/contract_m_gdp.py,sha256=J9ca-kpKJ9EH61mqahyfkT8Rt3B9aCXSDz-DZ9
|
|
|
20
20
|
hydroqc/contract/contract_residential.py,sha256=mWOM-wOtrfqLQgSHT3u9b1BD13YQNwfD3ueeYKHMm94,1348
|
|
21
21
|
hydroqc/contract/outage.py,sha256=qex9rnAyNpadRleOweAiNdQNGSfzJi6Jq9N77YTAnKQ,3978
|
|
22
22
|
hydroqc/hydro_api/__init__.py,sha256=bIIjTkhQcXG7kn4cQr_Q6tFSKGjAx-AXLjMMlRCjclY,32
|
|
23
|
-
hydroqc/hydro_api/auth.py,sha256=8VcWRskx17_KizoGMbDYBNABT5Hj4Jkym6bBvaTzRd4,3287
|
|
24
23
|
hydroqc/hydro_api/cache.py,sha256=2z_sdL3lesvIboyPM3bglFmxb6nXHgqOrXhGBwVJgSg,911
|
|
25
|
-
hydroqc/hydro_api/client.py,sha256=
|
|
26
|
-
hydroqc/hydro_api/consts.py,sha256=
|
|
24
|
+
hydroqc/hydro_api/client.py,sha256=UdihQmkASxBr3hq5CB82-I8tlRUMAQlP7ZmThdc766Y,33955
|
|
25
|
+
hydroqc/hydro_api/consts.py,sha256=M7HM34Sy2oc2xR3XEYNhN4wSe0W3Nki-4YUGHHdO1JY,4432
|
|
27
26
|
hydroqc/peak/__init__.py,sha256=ye2KbWXhJEHZnBDaFylWioy3W-mzJw_lDplsJNAapNs,19
|
|
28
27
|
hydroqc/peak/cpc/__init__.py,sha256=sez6LQOUqDu6YVIpJexq9wYv3wef3I4TeCxwHhO9bBU,18
|
|
29
28
|
hydroqc/peak/cpc/consts.py,sha256=HDCJCmgTQQABCog5vlANzkZlYxZdbAeEuTuy1FOQ8Kk,543
|
|
@@ -41,10 +40,10 @@ hydroqc/types/contract.py,sha256=xkqV0ode_KZN_f1UJ3qbTsicvI8IAd_GbqGgkbdKv5s,165
|
|
|
41
40
|
hydroqc/types/cpc.py,sha256=H7LAfSv10TxyB8cFK3vDeyOT-3zNrhc5rvMvZi4pOxA,2115
|
|
42
41
|
hydroqc/types/dpc.py,sha256=MXsiXxBpfchSlphTsz0VHSMi4uuDERAqC0jSh163nnc,1327
|
|
43
42
|
hydroqc/types/dt.py,sha256=DGARR_Cu9E7OIUMc7UxO9Pv3cdDEybg1dOqsaSBFLEE,328
|
|
44
|
-
hydroqc/types/outage.py,sha256=
|
|
45
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
46
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
47
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
48
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
49
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
50
|
-
Hydro_Quebec_API_Wrapper-3.1.
|
|
43
|
+
hydroqc/types/outage.py,sha256=89yBf6tc3X1f8jXVyqdgP4v2dQP0eIze61ocA-lI5qg,3931
|
|
44
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
|
|
45
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/METADATA,sha256=albr7ELd37SE0oxoPnKEnwroBryp3t-hBlMgaRrK7Eo,7940
|
|
46
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
|
|
47
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/entry_points.txt,sha256=G2YKkCH9rFt2dXbFyHINBp4bmqY2HTEIaf7F1CwbC_k,57
|
|
48
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/top_level.txt,sha256=YAcYLnu5YYkbxt1psUoBfo_opl-lAZKq0A7B3IN_P6M,8
|
|
49
|
+
Hydro_Quebec_API_Wrapper-3.1.2.dist-info/RECORD,,
|
hydroqc/error.py
CHANGED
|
@@ -8,6 +8,12 @@ class HydroQcError(Exception):
|
|
|
8
8
|
class HydroQcHTTPError(HydroQcError):
|
|
9
9
|
"""HTTP HydroQc Error."""
|
|
10
10
|
|
|
11
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
12
|
+
"""Initialize."""
|
|
13
|
+
self.message = message
|
|
14
|
+
self.status_code = status_code
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
|
|
11
17
|
|
|
12
18
|
class HydroQcAnnualError(HydroQcError):
|
|
13
19
|
"""Annual HydroQc Error."""
|
hydroqc/hydro_api/client.py
CHANGED
|
@@ -7,7 +7,6 @@ import os
|
|
|
7
7
|
import platform
|
|
8
8
|
import re
|
|
9
9
|
import ssl
|
|
10
|
-
import time
|
|
11
10
|
import uuid
|
|
12
11
|
from collections.abc import Iterator
|
|
13
12
|
from datetime import date, datetime, timedelta
|
|
@@ -15,12 +14,12 @@ from importlib.metadata import PackageNotFoundError, version
|
|
|
15
14
|
from io import StringIO
|
|
16
15
|
from json import dumps as json_dumps
|
|
17
16
|
from typing import Any
|
|
17
|
+
from pkce import generate_pkce_pair
|
|
18
18
|
|
|
19
19
|
import aiohttp
|
|
20
20
|
import yarl
|
|
21
21
|
|
|
22
22
|
from hydroqc.error import HydroQcError, HydroQcHTTPError
|
|
23
|
-
from hydroqc.hydro_api.auth import generate_pkce_pair
|
|
24
23
|
from hydroqc.hydro_api.cache import CCached
|
|
25
24
|
from hydroqc.hydro_api.consts import (
|
|
26
25
|
ANNUAL_DATA_URL,
|
|
@@ -30,6 +29,7 @@ from hydroqc.hydro_api.consts import (
|
|
|
30
29
|
AZB2C_CLIENT_ID_WEB,
|
|
31
30
|
AZB2C_POLICY,
|
|
32
31
|
AZB2C_SCOPE_WEB,
|
|
32
|
+
AZB2C_TIMEOUT_SKEW_SECS,
|
|
33
33
|
CONSO_CSV_URL,
|
|
34
34
|
CONSO_OVERVIEW_CSV_URL,
|
|
35
35
|
CONTRACT_LIST_URL,
|
|
@@ -41,7 +41,6 @@ from hydroqc.hydro_api.consts import (
|
|
|
41
41
|
GET_CPC_API_URL,
|
|
42
42
|
HOURLY_CONSUMPTION_API_URL,
|
|
43
43
|
IS_HYDRO_PORTAL_UP_URL,
|
|
44
|
-
LOGIN_URL_6,
|
|
45
44
|
MONTHLY_DATA_URL,
|
|
46
45
|
OUTAGES,
|
|
47
46
|
PERIOD_DATA_URL,
|
|
@@ -76,12 +75,6 @@ from hydroqc.utils import EST_TIMEZONE
|
|
|
76
75
|
class HydroClient:
|
|
77
76
|
"""HydroQc HTTP Client."""
|
|
78
77
|
|
|
79
|
-
_id_token: str
|
|
80
|
-
access_token: str
|
|
81
|
-
_selected_customer: str
|
|
82
|
-
_selected_contract: str
|
|
83
|
-
cookies: dict[str, Any]
|
|
84
|
-
|
|
85
78
|
def __init__(
|
|
86
79
|
self,
|
|
87
80
|
username: str,
|
|
@@ -97,7 +90,19 @@ class HydroClient:
|
|
|
97
90
|
self.password: str = password
|
|
98
91
|
self._timeout: int = timeout
|
|
99
92
|
self._session: aiohttp.ClientSession | None = session
|
|
93
|
+
self._cookie_jar: aiohttp.CookieJar = aiohttp.CookieJar()
|
|
100
94
|
self._verify_ssl: bool = verify_ssl
|
|
95
|
+
|
|
96
|
+
# OAuth handling variables
|
|
97
|
+
self._id_token: str = ""
|
|
98
|
+
self.access_token: str = ""
|
|
99
|
+
self.access_token_expiry: datetime = datetime.now()
|
|
100
|
+
self.refresh_token: str = ""
|
|
101
|
+
self.refresh_token_expiry: datetime = datetime.now()
|
|
102
|
+
self.web_session_expiry: datetime = datetime.now()
|
|
103
|
+
|
|
104
|
+
self._selected_customer: str
|
|
105
|
+
self._selected_contract: str
|
|
101
106
|
self._diag_folder: str | None = diag_folder
|
|
102
107
|
self._diag_id: int = 0
|
|
103
108
|
self.guid: str = str(uuid.uuid1())
|
|
@@ -109,7 +114,11 @@ class HydroClient:
|
|
|
109
114
|
"""Reset collected data and temporary variable."""
|
|
110
115
|
self._id_token = ""
|
|
111
116
|
self.access_token = ""
|
|
112
|
-
self.
|
|
117
|
+
self.access_token_expiry = datetime.now()
|
|
118
|
+
self.refresh_token = ""
|
|
119
|
+
self.refresh_token_expiry = datetime.now()
|
|
120
|
+
self.web_session_expiry = datetime.now()
|
|
121
|
+
self._cookie_jar = aiohttp.CookieJar()
|
|
113
122
|
self._selected_customer = ""
|
|
114
123
|
self._selected_contract = ""
|
|
115
124
|
|
|
@@ -136,12 +145,10 @@ class HydroClient:
|
|
|
136
145
|
data: str | dict[str, Any] | None = None,
|
|
137
146
|
headers: dict[str, str] | None = None,
|
|
138
147
|
verify_ssl: bool | None = None,
|
|
139
|
-
cookies: dict[str, Any] | None = None,
|
|
140
148
|
status: int | None = 200,
|
|
141
149
|
url_encoded: bool = False,
|
|
142
150
|
) -> aiohttp.ClientResponse:
|
|
143
|
-
"""
|
|
144
|
-
site = url.split("/")[2]
|
|
151
|
+
"""Make an HTTP request."""
|
|
145
152
|
if params is None:
|
|
146
153
|
params = {}
|
|
147
154
|
if data is None:
|
|
@@ -151,10 +158,6 @@ class HydroClient:
|
|
|
151
158
|
headers["User-Agent"] = self.user_agent
|
|
152
159
|
if verify_ssl is None:
|
|
153
160
|
verify_ssl = self._verify_ssl
|
|
154
|
-
if cookies is None:
|
|
155
|
-
if site not in self.cookies:
|
|
156
|
-
self.cookies[site] = {}
|
|
157
|
-
cookies = self.cookies[site]
|
|
158
161
|
|
|
159
162
|
ssl_context: ssl.SSLContext | None = None
|
|
160
163
|
if verify_ssl:
|
|
@@ -182,6 +185,7 @@ class HydroClient:
|
|
|
182
185
|
)
|
|
183
186
|
|
|
184
187
|
self._logger.debug("HTTP query %s to %s", url, method)
|
|
188
|
+
|
|
185
189
|
url_url = yarl.URL(url, encoded=url_encoded)
|
|
186
190
|
raw_res: aiohttp.ClientResponse = await getattr(self._session, method)(
|
|
187
191
|
url_url,
|
|
@@ -189,9 +193,9 @@ class HydroClient:
|
|
|
189
193
|
data=data,
|
|
190
194
|
allow_redirects=False,
|
|
191
195
|
ssl=ssl_context,
|
|
192
|
-
cookies=cookies,
|
|
193
196
|
headers=headers,
|
|
194
197
|
)
|
|
198
|
+
|
|
195
199
|
# Result Diagnostic
|
|
196
200
|
if self._diag_folder is not None:
|
|
197
201
|
cleaned_url = url.replace("/", "_").replace(":", "").split("#", 1)[0]
|
|
@@ -215,9 +219,9 @@ class HydroClient:
|
|
|
215
219
|
self._logger.exception("Exception in http_request")
|
|
216
220
|
data = await raw_res.text()
|
|
217
221
|
self._logger.debug(data)
|
|
218
|
-
raise HydroQcHTTPError(
|
|
219
|
-
|
|
220
|
-
|
|
222
|
+
raise HydroQcHTTPError(
|
|
223
|
+
f"Error Fetching {url} - {raw_res.status}", raw_res.status
|
|
224
|
+
)
|
|
221
225
|
|
|
222
226
|
return raw_res
|
|
223
227
|
|
|
@@ -237,31 +241,21 @@ class HydroClient:
|
|
|
237
241
|
token_data: IDTokenTyping = self._load_json(base64.b64decode(raw_token_data))
|
|
238
242
|
return token_data
|
|
239
243
|
|
|
240
|
-
@property
|
|
241
|
-
def session_expired(self) -> bool:
|
|
242
|
-
"""Get Oauth session expired or not.
|
|
243
|
-
|
|
244
|
-
returns True if the session has expired.
|
|
245
|
-
"""
|
|
246
|
-
if self._id_token in {"", None}:
|
|
247
|
-
return True
|
|
248
|
-
token_data = self.get_token_data()
|
|
249
|
-
return bool(time.time() > token_data["exp"])
|
|
250
|
-
|
|
251
244
|
def _get_httpsession(self) -> None:
|
|
252
245
|
"""Set http session."""
|
|
253
246
|
if self._session is None:
|
|
247
|
+
self._logger.debug("Creating new http session")
|
|
254
248
|
self._session = aiohttp.ClientSession(
|
|
255
|
-
requote_redirect_url=False,
|
|
249
|
+
requote_redirect_url=False, cookie_jar=self._cookie_jar
|
|
256
250
|
)
|
|
257
251
|
|
|
258
|
-
def _get_customer_http_headers(
|
|
259
|
-
self, applicant_id: str, customer_id: str
|
|
252
|
+
async def _get_customer_http_headers(
|
|
253
|
+
self, applicant_id: str, customer_id: str, force_refresh: bool = False
|
|
260
254
|
) -> dict[str, str]:
|
|
261
255
|
"""Prepare http headers for customer url queries."""
|
|
262
256
|
headers = {
|
|
263
257
|
"Content-Type": "application/json",
|
|
264
|
-
"Authorization": "Bearer " + self.
|
|
258
|
+
"Authorization": "Bearer " + await self._get_access_token(force_refresh),
|
|
265
259
|
"NO_PARTENAIRE_DEMANDEUR": applicant_id,
|
|
266
260
|
"NO_PARTENAIRE_TITULAIRE": customer_id,
|
|
267
261
|
"DATE_DERNIERE_VISITE": datetime.now().strftime(
|
|
@@ -274,7 +268,9 @@ class HydroClient:
|
|
|
274
268
|
async def close_session(self) -> None:
|
|
275
269
|
"""Close current session."""
|
|
276
270
|
if self._session is not None:
|
|
271
|
+
self._logger.debug("Closing http session")
|
|
277
272
|
await self._session.close()
|
|
273
|
+
self._session = None
|
|
278
274
|
|
|
279
275
|
async def check_portal_status(self) -> bool:
|
|
280
276
|
"""Check if Hydro Quebec portal is UP."""
|
|
@@ -293,7 +289,7 @@ class HydroClient:
|
|
|
293
289
|
async def login(self) -> bool:
|
|
294
290
|
"""Log in HydroQuebec website.
|
|
295
291
|
|
|
296
|
-
Hydroquebec is using
|
|
292
|
+
Hydroquebec is using B2C solution for authentication.
|
|
297
293
|
"""
|
|
298
294
|
self._logger.info("Login using %s", self.username)
|
|
299
295
|
|
|
@@ -450,19 +446,22 @@ class HydroClient:
|
|
|
450
446
|
|
|
451
447
|
self._id_token = res_json["id_token"]
|
|
452
448
|
self.access_token = res_json["access_token"]
|
|
449
|
+
self.access_token_expiry = datetime.now() + timedelta(
|
|
450
|
+
seconds=int(res_json["expires_in"]) - AZB2C_TIMEOUT_SKEW_SECS
|
|
451
|
+
)
|
|
453
452
|
self.refresh_token = res_json["refresh_token"]
|
|
453
|
+
self.refresh_token_expiry = datetime.now() + timedelta(
|
|
454
|
+
seconds=int(res_json["refresh_token_expires_in"]) - AZB2C_TIMEOUT_SKEW_SECS
|
|
455
|
+
)
|
|
454
456
|
|
|
455
|
-
headers = {
|
|
456
|
-
"Content-Type": "application/json",
|
|
457
|
-
"Authorization": "Bearer " + self.access_token,
|
|
458
|
-
}
|
|
459
|
-
await self.http_request(LOGIN_URL_6, "get", headers=headers)
|
|
460
457
|
self._logger.info("Login completed using %s", self.username)
|
|
461
458
|
|
|
462
459
|
return True
|
|
463
460
|
|
|
464
461
|
async def _refresh_token(self) -> bool:
|
|
465
462
|
"""Refresh current session."""
|
|
463
|
+
self._logger.debug("Refreshing access token")
|
|
464
|
+
|
|
466
465
|
url = TOKEN_URL
|
|
467
466
|
headers = {
|
|
468
467
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
@@ -477,15 +476,32 @@ class HydroClient:
|
|
|
477
476
|
|
|
478
477
|
res = await self.http_request(url, "post", headers=headers, data=data)
|
|
479
478
|
res_json = await res.json()
|
|
479
|
+
|
|
480
480
|
self._id_token = res_json["id_token"]
|
|
481
481
|
self.access_token = res_json["access_token"]
|
|
482
|
+
self.access_token_expiry = datetime.now() + timedelta(
|
|
483
|
+
seconds=int(res_json["expires_in"]) - AZB2C_TIMEOUT_SKEW_SECS
|
|
484
|
+
)
|
|
482
485
|
self.refresh_token = res_json["refresh_token"]
|
|
486
|
+
self.refresh_token_expiry = datetime.now() + timedelta(
|
|
487
|
+
seconds=int(res_json["refresh_token_expires_in"]) - AZB2C_TIMEOUT_SKEW_SECS
|
|
488
|
+
)
|
|
489
|
+
|
|
483
490
|
return True
|
|
484
491
|
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
492
|
+
def is_session_expired(self) -> bool:
|
|
493
|
+
"""Check if the session is expired."""
|
|
494
|
+
return self.refresh_token_expiry < datetime.now()
|
|
495
|
+
|
|
496
|
+
async def _get_access_token(self, force_refresh: bool = True) -> str:
|
|
497
|
+
"""Get an access token."""
|
|
498
|
+
if self.is_session_expired():
|
|
499
|
+
await self.close_session()
|
|
500
|
+
await self.login()
|
|
501
|
+
elif force_refresh or self.access_token_expiry < datetime.now():
|
|
502
|
+
await self._refresh_token()
|
|
503
|
+
|
|
504
|
+
return self.access_token
|
|
489
505
|
|
|
490
506
|
@property
|
|
491
507
|
def selected_customer(self) -> str:
|
|
@@ -497,32 +513,45 @@ class HydroClient:
|
|
|
497
513
|
"""Return the current selected contract."""
|
|
498
514
|
return self._selected_contract
|
|
499
515
|
|
|
516
|
+
async def _create_web_session(
|
|
517
|
+
self, applicant_id: str, customer_id: str, contract_id: str
|
|
518
|
+
) -> None:
|
|
519
|
+
"""Create a web session from a OAuth access_token."""
|
|
520
|
+
self._logger.debug("Creating new web session %s", contract_id)
|
|
521
|
+
|
|
522
|
+
# Clearing all cookies. New SESSION must be created.
|
|
523
|
+
self._cookie_jar.clear()
|
|
524
|
+
|
|
525
|
+
# Forcing a refresh of the access token.
|
|
526
|
+
# The new session that is created with SESSION_URL (/portal resources)
|
|
527
|
+
# seemed to break (calls returning HTTP 400) in alignment with
|
|
528
|
+
# the access_token expiry. With a new access_token, we can assume the web
|
|
529
|
+
# session invalid at the same time as the access token that was used to create it.
|
|
530
|
+
headers = await self._get_customer_http_headers(
|
|
531
|
+
applicant_id, customer_id, force_refresh=True
|
|
532
|
+
)
|
|
533
|
+
|
|
534
|
+
params = {"mode": "web"}
|
|
535
|
+
await self.http_request(SESSION_URL, "get", params=params, headers=headers)
|
|
536
|
+
self.web_session_expiry = self.access_token_expiry
|
|
537
|
+
|
|
500
538
|
async def _select_contract(
|
|
501
|
-
self, applicant_id: str, customer_id: str, contract_id: str
|
|
539
|
+
self, applicant_id: str, customer_id: str, contract_id: str
|
|
502
540
|
) -> None:
|
|
503
|
-
"""
|
|
541
|
+
"""Create a web session from a OAuth access_token and select a customer on the Home page.
|
|
504
542
|
|
|
505
543
|
Equivalent to click on the customer box on the Home page.
|
|
506
544
|
"""
|
|
507
|
-
|
|
508
|
-
|
|
545
|
+
if self.web_session_expiry > datetime.now():
|
|
546
|
+
self._logger.debug("Not refreshing web session")
|
|
509
547
|
return
|
|
510
548
|
|
|
511
|
-
self.
|
|
512
|
-
if force and "cl-ec-spring.hydroquebec.com" in self.cookies:
|
|
513
|
-
del self.cookies["cl-ec-spring.hydroquebec.com"]
|
|
549
|
+
await self._create_web_session(applicant_id, customer_id, contract_id)
|
|
514
550
|
|
|
515
|
-
|
|
516
|
-
# await self.http_request(INFOBASE_URL, "get", headers=headers)
|
|
517
|
-
|
|
518
|
-
params = {"mode": "web"}
|
|
519
|
-
await self.http_request(SESSION_URL, "get", params=params, headers=headers)
|
|
551
|
+
self._logger.info("Selecting contract %s", contract_id)
|
|
520
552
|
|
|
521
|
-
# load overview page
|
|
522
|
-
# await self.http_request(CONTRACT_URL_3, "get", headers=headers)
|
|
523
|
-
# load consumption profile page
|
|
524
553
|
params = {"noContrat": contract_id}
|
|
525
|
-
await self.http_request(PORTRAIT_URL, "get", params=params
|
|
554
|
+
await self.http_request(PORTRAIT_URL, "get", params=params)
|
|
526
555
|
|
|
527
556
|
self._selected_contract = contract_id
|
|
528
557
|
self._selected_customer = customer_id
|
|
@@ -538,7 +567,7 @@ class HydroClient:
|
|
|
538
567
|
self._logger.info("Fetching webuser info")
|
|
539
568
|
headers = {
|
|
540
569
|
"Content-Type": "application/json",
|
|
541
|
-
"Authorization": "Bearer " + self.
|
|
570
|
+
"Authorization": "Bearer " + await self._get_access_token(),
|
|
542
571
|
}
|
|
543
572
|
res = await self.http_request(RELATION_URL, "get", headers=headers)
|
|
544
573
|
# TODO http errors
|
|
@@ -551,7 +580,7 @@ class HydroClient:
|
|
|
551
580
|
) -> InfoAccountTyping:
|
|
552
581
|
"""Fetch customer data."""
|
|
553
582
|
self._logger.info("Fetching customer info: c-%s", customer_id)
|
|
554
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
583
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
555
584
|
params = {"withCredentials": "true"}
|
|
556
585
|
api_call_response = await self.http_request(
|
|
557
586
|
CUSTOMER_INFO_URL,
|
|
@@ -568,7 +597,7 @@ class HydroClient:
|
|
|
568
597
|
) -> list[PeriodDataTyping]:
|
|
569
598
|
"""Fetch all periods info."""
|
|
570
599
|
await self._select_contract(applicant_id, customer_id, contract_id)
|
|
571
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
600
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
572
601
|
res = await self.http_request(PERIOD_DATA_URL, "get", headers=headers)
|
|
573
602
|
data = json.loads(await res.text())
|
|
574
603
|
|
|
@@ -599,7 +628,7 @@ class HydroClient:
|
|
|
599
628
|
self, applicant_id: str, customer_id: str
|
|
600
629
|
) -> AccountContractSummaryTyping:
|
|
601
630
|
"""Get all account_contract linked to a customer."""
|
|
602
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
631
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
603
632
|
res = await self.http_request(CONTRACT_SUMMARY_URL, "get", headers=headers)
|
|
604
633
|
data: AccountContractSummaryTyping = await res.json()
|
|
605
634
|
return data
|
|
@@ -615,7 +644,7 @@ class HydroClient:
|
|
|
615
644
|
customer_id,
|
|
616
645
|
contract_id,
|
|
617
646
|
)
|
|
618
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
647
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
619
648
|
post_data = {
|
|
620
649
|
"listeServices": ["PC"],
|
|
621
650
|
"comptesContrats": [
|
|
@@ -645,7 +674,7 @@ class HydroClient:
|
|
|
645
674
|
:return: raw JSON from hydro QC API
|
|
646
675
|
"""
|
|
647
676
|
self._logger.info("Fetching cpc: c-%s c-%s", customer_id, contract_id)
|
|
648
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
677
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
649
678
|
params = {"noContrat": contract_id}
|
|
650
679
|
api_call_response = await self.http_request(
|
|
651
680
|
GET_CPC_API_URL,
|
|
@@ -822,7 +851,7 @@ class HydroClient:
|
|
|
822
851
|
|
|
823
852
|
"""
|
|
824
853
|
await self._select_contract(applicant_id, customer_id, contract_id)
|
|
825
|
-
headers = self._get_customer_http_headers(applicant_id, customer_id)
|
|
854
|
+
headers = await self._get_customer_http_headers(applicant_id, customer_id)
|
|
826
855
|
params = {"noContrat": contract_id}
|
|
827
856
|
api_call_response = await self.http_request(
|
|
828
857
|
FLEXD_PEAK_URL, "get", params=params, headers=headers
|
hydroqc/hydro_api/consts.py
CHANGED
|
@@ -26,6 +26,9 @@ AZB2C_SCOPE_WEB = (
|
|
|
26
26
|
)
|
|
27
27
|
AZB2C_CODE_CHALLENGE_METHOD = "S256"
|
|
28
28
|
|
|
29
|
+
# Time to remove from the token expiration time to avoid calls to fail
|
|
30
|
+
AZB2C_TIMEOUT_SKEW_SECS = 60
|
|
31
|
+
|
|
29
32
|
# Outages
|
|
30
33
|
OUTAGES = f"{HOST_OUTAGES}/pan/web/api/v1/lieux-conso/etats/"
|
|
31
34
|
# OAUTH PATHS
|
hydroqc/types/outage.py
CHANGED
|
@@ -89,19 +89,20 @@ class OutageCode(Enum):
|
|
|
89
89
|
# Unkonwn (not official HQ code)
|
|
90
90
|
inconnu = "_"
|
|
91
91
|
travaux_assignes = "A"
|
|
92
|
-
|
|
92
|
+
travaux_en_cours = "L"
|
|
93
93
|
equipe_en_route = "R"
|
|
94
|
-
|
|
94
|
+
en_analyse = "N"
|
|
95
95
|
|
|
96
96
|
|
|
97
97
|
class OutageStatus(Enum):
|
|
98
98
|
"""Outage Status enum."""
|
|
99
99
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
100
|
+
planifie_confirme = "P"
|
|
101
|
+
courante_confirme = "C"
|
|
102
|
+
planifie_reporte = "R"
|
|
103
103
|
termine = "T"
|
|
104
104
|
non_confirme = "N"
|
|
105
|
+
annule = "A"
|
|
105
106
|
|
|
106
107
|
|
|
107
108
|
class OutageIdTyping(TypedDict, total=True):
|
hydroqc/webuser.py
CHANGED
|
@@ -45,6 +45,11 @@ class WebUser:
|
|
|
45
45
|
"""Login to Hydroquebec website."""
|
|
46
46
|
return await self._hydro_client.login()
|
|
47
47
|
|
|
48
|
+
@property
|
|
49
|
+
def session_expired(self) -> bool:
|
|
50
|
+
"""Check if the session is expired."""
|
|
51
|
+
return self._hydro_client.is_session_expired()
|
|
52
|
+
|
|
48
53
|
async def get_info(self) -> None:
|
|
49
54
|
"""Fetch data about this webuser.
|
|
50
55
|
|
|
@@ -96,15 +101,6 @@ class WebUser:
|
|
|
96
101
|
data = self._hydro_client.get_token_data()
|
|
97
102
|
return data["family_name"]
|
|
98
103
|
|
|
99
|
-
@property
|
|
100
|
-
def session_expired(self) -> bool:
|
|
101
|
-
"""Is the current session expired or not."""
|
|
102
|
-
return self._hydro_client.session_expired
|
|
103
|
-
|
|
104
|
-
async def refresh_session(self) -> None:
|
|
105
|
-
"""Refresh the current session."""
|
|
106
|
-
await self._hydro_client.refresh_session()
|
|
107
|
-
|
|
108
104
|
def get_customer(self, customer_id: str) -> Customer:
|
|
109
105
|
"""Find customer by id."""
|
|
110
106
|
if not (
|
hydroqc/hydro_api/auth.py
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
"""Generate PKCE-compliant code verifier and code challenge."""
|
|
2
|
-
|
|
3
|
-
# Implement an HTTP call with the following details and capture the session cookie.
|
|
4
|
-
#
|
|
5
|
-
# GET https://connexion.solutions.hydroquebec.com/32bf9b91-0a36-4385-b231-d9a8fa3b05ab/
|
|
6
|
-
# b2c_1a_prd_signup_signin/oauth2/v2.0/authorize
|
|
7
|
-
#
|
|
8
|
-
# with the following query parameters
|
|
9
|
-
# redirect_uri: msauth.com.hydroquebec.infos-pannes://auth
|
|
10
|
-
# client_id: 09b0ae72-6db8-4ecc-a1be-041b67afc1cd
|
|
11
|
-
# response_type: code
|
|
12
|
-
# state: %7B%22redirectUrl%22:%22CONSO%22%7D
|
|
13
|
-
# scope: openid offline_access https://connexionhq.onmicrosoft.com/
|
|
14
|
-
# hq-clientele-mobile/Espace.Client
|
|
15
|
-
# prompt: login
|
|
16
|
-
# ui_locales: fr
|
|
17
|
-
# code_challenge: VQhipatCIaStOosra0_550ztGC76U1ezBURCV9uKK1M
|
|
18
|
-
# code_challenge_method: S256
|
|
19
|
-
#
|
|
20
|
-
# and the following request http headers
|
|
21
|
-
# accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
|
|
22
|
-
|
|
23
|
-
import base64
|
|
24
|
-
import hashlib
|
|
25
|
-
import secrets
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def generate_code_verifier(length: int = 128) -> str:
|
|
29
|
-
"""Return a random PKCE-compliant code verifier.
|
|
30
|
-
|
|
31
|
-
Parameters
|
|
32
|
-
----------
|
|
33
|
-
length : int
|
|
34
|
-
Code verifier length. Must verify `43 <= length <= 128`.
|
|
35
|
-
|
|
36
|
-
Returns
|
|
37
|
-
-------
|
|
38
|
-
code_verifier : str
|
|
39
|
-
Code verifier.
|
|
40
|
-
|
|
41
|
-
Raises
|
|
42
|
-
------
|
|
43
|
-
ValueError
|
|
44
|
-
When `43 <= length <= 128` is not verified.
|
|
45
|
-
"""
|
|
46
|
-
if not 43 <= length <= 128:
|
|
47
|
-
msg = "Parameter `length` must verify `43 <= length <= 128`."
|
|
48
|
-
raise ValueError(msg)
|
|
49
|
-
code_verifier = secrets.token_urlsafe(96)[:length]
|
|
50
|
-
return code_verifier
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
def generate_pkce_pair(code_verifier_length: int = 128) -> tuple[str, str]:
|
|
54
|
-
"""Return random PKCE-compliant code verifier and code challenge.
|
|
55
|
-
|
|
56
|
-
Parameters
|
|
57
|
-
----------
|
|
58
|
-
code_verifier_length : int
|
|
59
|
-
Code verifier length. Must verify
|
|
60
|
-
`43 <= code_verifier_length <= 128`.
|
|
61
|
-
|
|
62
|
-
Returns
|
|
63
|
-
-------
|
|
64
|
-
code_verifier : str
|
|
65
|
-
code_challenge : str
|
|
66
|
-
|
|
67
|
-
Raises
|
|
68
|
-
------
|
|
69
|
-
ValueError
|
|
70
|
-
When `43 <= code_verifier_length <= 128` is not verified.
|
|
71
|
-
"""
|
|
72
|
-
if not 43 <= code_verifier_length <= 128:
|
|
73
|
-
msg = "Parameter `code_verifier_length` must verify "
|
|
74
|
-
msg += "`43 <= code_verifier_length <= 128`."
|
|
75
|
-
raise ValueError(msg)
|
|
76
|
-
code_verifier = generate_code_verifier(code_verifier_length)
|
|
77
|
-
code_challenge = get_code_challenge(code_verifier)
|
|
78
|
-
return code_verifier, code_challenge
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def get_code_challenge(code_verifier: str) -> str:
|
|
82
|
-
"""Return the PKCE-compliant code challenge for a given verifier.
|
|
83
|
-
|
|
84
|
-
Parameters
|
|
85
|
-
----------
|
|
86
|
-
code_verifier : str
|
|
87
|
-
Code verifier. Must verify `43 <= len(code_verifier) <= 128`.
|
|
88
|
-
|
|
89
|
-
Returns
|
|
90
|
-
-------
|
|
91
|
-
code_challenge : str
|
|
92
|
-
Code challenge that corresponds to the input code verifier.
|
|
93
|
-
|
|
94
|
-
Raises
|
|
95
|
-
------
|
|
96
|
-
ValueError
|
|
97
|
-
When `43 <= len(code_verifier) <= 128` is not verified.
|
|
98
|
-
"""
|
|
99
|
-
if not 43 <= len(code_verifier) <= 128:
|
|
100
|
-
msg = "Parameter `code_verifier` must verify "
|
|
101
|
-
msg += "`43 <= len(code_verifier) <= 128`."
|
|
102
|
-
raise ValueError(msg)
|
|
103
|
-
hashed = hashlib.sha256(code_verifier.encode("ascii")).digest()
|
|
104
|
-
encoded = base64.urlsafe_b64encode(hashed)
|
|
105
|
-
code_challenge = encoded.decode("ascii")[:-1]
|
|
106
|
-
return code_challenge
|
{Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/LICENSE
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{Hydro_Quebec_API_Wrapper-3.1.0.dist-info → Hydro_Quebec_API_Wrapper-3.1.2.dist-info}/top_level.txt
RENAMED
|
File without changes
|