async-bakalari-api 0.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.
- __init__.py +0 -0
- async_bakalari_api-0.2.dist-info/LICENSE.md +202 -0
- async_bakalari_api-0.2.dist-info/METADATA +275 -0
- async_bakalari_api-0.2.dist-info/RECORD +17 -0
- async_bakalari_api-0.2.dist-info/WHEEL +5 -0
- async_bakalari_api-0.2.dist-info/entry_points.txt +2 -0
- async_bakalari_api-0.2.dist-info/top_level.txt +2 -0
- bakalari_api/__init__.py +8 -0
- bakalari_api/__main__.py +5 -0
- bakalari_api/bakalari.py +379 -0
- bakalari_api/bakalari_demo.py +53 -0
- bakalari_api/const.py +70 -0
- bakalari_api/datastructure.py +175 -0
- bakalari_api/exceptions.py +64 -0
- bakalari_api/first_login.py +13 -0
- bakalari_api/komens.py +155 -0
- bakalari_api/logger_api.py +61 -0
bakalari_api/bakalari.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Async Bakalari v3 API connector."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Self
|
|
8
|
+
from urllib import parse
|
|
9
|
+
|
|
10
|
+
import aiohttp
|
|
11
|
+
from aiohttp import hdrs
|
|
12
|
+
import aiohttp.web_response
|
|
13
|
+
import orjson
|
|
14
|
+
|
|
15
|
+
from .const import REQUEST_TIMEOUT, EndPoint, Errors
|
|
16
|
+
from .datastructure import Credentials, Schools
|
|
17
|
+
from .exceptions import Ex
|
|
18
|
+
from .logger_api import api_logger
|
|
19
|
+
|
|
20
|
+
log = api_logger("Bakalari API", loglevel=logging.ERROR).get()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Bakalari:
|
|
24
|
+
"""Root class of Bakalari."""
|
|
25
|
+
|
|
26
|
+
session: aiohttp.ClientSession | None = None
|
|
27
|
+
response: None
|
|
28
|
+
response_json: None
|
|
29
|
+
|
|
30
|
+
_close_session = False
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
server: str | None = None,
|
|
35
|
+
auto_cache_credentials: bool = False,
|
|
36
|
+
cache_filename: str | None = None,
|
|
37
|
+
):
|
|
38
|
+
"""Root class of Bakalari.
|
|
39
|
+
|
|
40
|
+
Holds credentials, sends requests and perform first login.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
server (str): Url of endpoint server.
|
|
44
|
+
auto_cache_credentials (bool, optional): If you want to cache credentials locally to file. Defaults to False.
|
|
45
|
+
cache_filename (str, optional): Cache file name, if `auto_cache_credentials`. Defaults to None.
|
|
46
|
+
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
self.server = server
|
|
50
|
+
self.credentials = Credentials
|
|
51
|
+
self.new_token = False
|
|
52
|
+
self.auto_cache_credentials = auto_cache_credentials
|
|
53
|
+
self.cache_filename = cache_filename
|
|
54
|
+
|
|
55
|
+
if self.auto_cache_credentials and not self.cache_filename:
|
|
56
|
+
raise Ex.CacheError("Auto-cache is enabled, but no filename is provided!")
|
|
57
|
+
|
|
58
|
+
async def send_auth_request(self, request_endpoint: EndPoint, **kwargs):
|
|
59
|
+
"""Send authorized request with access token or refresh token."""
|
|
60
|
+
|
|
61
|
+
request = self.get_request_url(request_endpoint)
|
|
62
|
+
method = hdrs.METH_POST if "post" in request_endpoint.method else hdrs.METH_GET
|
|
63
|
+
|
|
64
|
+
access_token_invalid = False
|
|
65
|
+
result = None
|
|
66
|
+
|
|
67
|
+
if not self.credentials.access_token and not self.credentials.refresh_token:
|
|
68
|
+
raise Ex.TokenMissing("Access token or Refresh token is missing!")
|
|
69
|
+
|
|
70
|
+
while True:
|
|
71
|
+
if self.credentials.access_token and not access_token_invalid:
|
|
72
|
+
log.debug("Trying access token ...")
|
|
73
|
+
try:
|
|
74
|
+
headers_access_token = {
|
|
75
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
76
|
+
"Authorization": f"Bearer {self.credentials.access_token}",
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
result = await self._send_request(
|
|
80
|
+
request, method=method, headers=headers_access_token
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
except Ex.AccessTokenExpired:
|
|
84
|
+
access_token_invalid = True
|
|
85
|
+
continue
|
|
86
|
+
except Ex.InvalidToken:
|
|
87
|
+
access_token_invalid = True
|
|
88
|
+
continue
|
|
89
|
+
except Exception as ex:
|
|
90
|
+
raise ex from ex
|
|
91
|
+
else:
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
if access_token_invalid and self.refresh_access_token:
|
|
95
|
+
log.debug("Trying refresh token ...")
|
|
96
|
+
try:
|
|
97
|
+
await self.refresh_access_token()
|
|
98
|
+
except Ex.RefreshTokenExpired as ex:
|
|
99
|
+
log.error("Refresh token expired! Login with username/password")
|
|
100
|
+
raise ex from ex
|
|
101
|
+
except Exception as ex:
|
|
102
|
+
raise ex from ex
|
|
103
|
+
access_token_invalid = False
|
|
104
|
+
|
|
105
|
+
async def send_unauth_request(
|
|
106
|
+
self, request: EndPoint, headers: dict[str, str] | None = None, **kwargs
|
|
107
|
+
) -> str | None:
|
|
108
|
+
"""Send unauthorized request to endpoint.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
request (EndPoint): endpoint
|
|
112
|
+
headers (str): headers for request
|
|
113
|
+
**kwargs (dict): kwargs
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
str: JSON response or None
|
|
117
|
+
|
|
118
|
+
"""
|
|
119
|
+
method = hdrs.METH_GET if "get" in request.method else hdrs.METH_POST
|
|
120
|
+
|
|
121
|
+
_request_url = self.get_request_url(request)
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
_request = await self._send_request(
|
|
125
|
+
_request_url, method=method, headers=headers, **kwargs
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
except Exception as err:
|
|
129
|
+
log.error(f"Sending unauthorized request failed. Error: {err} ")
|
|
130
|
+
raise err from err
|
|
131
|
+
|
|
132
|
+
return _request
|
|
133
|
+
|
|
134
|
+
async def _send_request(
|
|
135
|
+
self,
|
|
136
|
+
url: str,
|
|
137
|
+
method: hdrs.METH_POST | hdrs.METH_GET,
|
|
138
|
+
headers: dict[str, str],
|
|
139
|
+
**kwargs,
|
|
140
|
+
) -> str:
|
|
141
|
+
"""Send request to server.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
url (str): requested endpoint
|
|
145
|
+
method (hdrs.METH_POST | hdrs.METH_GET): which method to use
|
|
146
|
+
headers (str): request headers
|
|
147
|
+
**kwargs: kwargs
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
Ex.TimeoutException: _description_
|
|
151
|
+
Ex.BadRequestException: _description_
|
|
152
|
+
Ex.TokensExpired: _description_
|
|
153
|
+
Ex.AccessTokenExpired: _description_
|
|
154
|
+
Ex.InvalidHTTPMethod: _description_
|
|
155
|
+
Ex.InvalidLogin: _description_
|
|
156
|
+
Ex.RefreshTokenExpired: _description_
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
str: response in json format
|
|
160
|
+
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
if not self.session or self.session.closed:
|
|
164
|
+
self.session = aiohttp.ClientSession()
|
|
165
|
+
|
|
166
|
+
log.debug("Requesting URL %s, kwargs: %s", url, kwargs)
|
|
167
|
+
try:
|
|
168
|
+
async with asyncio.timeout(REQUEST_TIMEOUT):
|
|
169
|
+
async with self.session:
|
|
170
|
+
if method == hdrs.METH_GET:
|
|
171
|
+
response = await self.session.get(
|
|
172
|
+
url, ssl=True, headers=headers, **kwargs
|
|
173
|
+
)
|
|
174
|
+
else:
|
|
175
|
+
response = await self.session.post(
|
|
176
|
+
url, ssl=True, headers=headers, **kwargs
|
|
177
|
+
)
|
|
178
|
+
response_json = await response.json()
|
|
179
|
+
log.debug(f"Response: {response}")
|
|
180
|
+
|
|
181
|
+
except TimeoutError as err:
|
|
182
|
+
raise Ex.TimeoutException(
|
|
183
|
+
f"Timeout occurred while connecting to server {url}"
|
|
184
|
+
) from err
|
|
185
|
+
except aiohttp.ClientConnectionError as err:
|
|
186
|
+
raise Ex.BadRequestException(f"Connection error: {url}") from err
|
|
187
|
+
|
|
188
|
+
match response.status:
|
|
189
|
+
case 401:
|
|
190
|
+
if Errors.ACCESS_TOKEN_EXPIRED in response.headers.get(
|
|
191
|
+
"WWW-Authenticate"
|
|
192
|
+
):
|
|
193
|
+
raise Ex.AccessTokenExpired("Access token expired.")
|
|
194
|
+
if Errors.REFRESH_TOKEN_EXPIRED in response.headers.get(
|
|
195
|
+
"WWW-Authenticate"
|
|
196
|
+
):
|
|
197
|
+
raise Ex.RefreshTokenExpired("Refresh token expired.")
|
|
198
|
+
|
|
199
|
+
if Errors.INVALID_TOKEN in response.headers.get("WWW-Authenticate"):
|
|
200
|
+
raise Ex.InvalidToken("Invalid token provided.")
|
|
201
|
+
|
|
202
|
+
raise Ex.BadRequestException(f"{url} with message: {response_json}")
|
|
203
|
+
case 400:
|
|
204
|
+
match response_json.get("error_uri"):
|
|
205
|
+
case x if Errors.INVALID_METHOD in x:
|
|
206
|
+
raise Ex.InvalidHTTPMethod(
|
|
207
|
+
f"Invalid HTTP method. Method '{method}' is not supported for '{url}'"
|
|
208
|
+
)
|
|
209
|
+
case x if Errors.INVALID_LOGIN in x:
|
|
210
|
+
raise Ex.InvalidLogin("Invalid login!")
|
|
211
|
+
case x if Errors.REFRESH_TOKEN_REDEEMD in x:
|
|
212
|
+
raise Ex.RefreshTokenRedeemd("Refresh token already redeemd!")
|
|
213
|
+
case x if Errors.INVALID_REFRESH_TOKEN in x:
|
|
214
|
+
raise Ex.InvalidRefreshToken("Invalid refresh token!")
|
|
215
|
+
case _:
|
|
216
|
+
raise Ex.BadRequestException(
|
|
217
|
+
f"{url} with message: {response_json}"
|
|
218
|
+
)
|
|
219
|
+
case 200:
|
|
220
|
+
return response_json
|
|
221
|
+
case _:
|
|
222
|
+
raise Ex.BadRequestException(f"{url} with message: {response_json}")
|
|
223
|
+
|
|
224
|
+
async def async_schools_list(self) -> Schools:
|
|
225
|
+
"""Return list of schools with their API points."""
|
|
226
|
+
|
|
227
|
+
_schools_list = Schools()
|
|
228
|
+
headers = {"Accept": "application/json"}
|
|
229
|
+
|
|
230
|
+
log.debug("Gathering list of towns ...")
|
|
231
|
+
try:
|
|
232
|
+
towns_json = await self.send_unauth_request(EndPoint.SCHOOL_LIST, headers)
|
|
233
|
+
except Exception as exc:
|
|
234
|
+
log.error(f"Error while gathering schools endpoints. {exc}")
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
schools: list = []
|
|
238
|
+
|
|
239
|
+
for town in towns_json:
|
|
240
|
+
town_name = str(town["name"])
|
|
241
|
+
if town_name == "":
|
|
242
|
+
continue
|
|
243
|
+
if "." in town_name:
|
|
244
|
+
town_name = town_name[: town_name.find(".")]
|
|
245
|
+
|
|
246
|
+
log.debug("Gathering schools for town: %s", town_name)
|
|
247
|
+
|
|
248
|
+
endpoint = f"{EndPoint.SCHOOL_LIST.endpoint}/{parse.quote(town_name)}"
|
|
249
|
+
|
|
250
|
+
response_town = await self._send_request(endpoint, hdrs.METH_GET, headers)
|
|
251
|
+
|
|
252
|
+
schools: dict = response_town
|
|
253
|
+
for _schools in schools.get("schools"):
|
|
254
|
+
_schools_list.append_school(
|
|
255
|
+
name=_schools.get("name"),
|
|
256
|
+
api_point=_schools.get("schoolUrl"),
|
|
257
|
+
town=town_name,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
return _schools_list
|
|
261
|
+
|
|
262
|
+
async def first_login(self, username: str, password: str) -> Credentials:
|
|
263
|
+
"""First login.
|
|
264
|
+
|
|
265
|
+
Create access and refresh tokens.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
login_url = f"client_id=ANDR&grant_type=password&username={username}&password={password}"
|
|
269
|
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
log.debug("Trying to login with username and password ...")
|
|
273
|
+
_credentials = await self.send_unauth_request(
|
|
274
|
+
EndPoint.LOGIN, data=login_url, headers=headers
|
|
275
|
+
)
|
|
276
|
+
except Ex.InvalidLogin as ex:
|
|
277
|
+
log.error("Invalid username / password provided.")
|
|
278
|
+
raise ex from ex
|
|
279
|
+
_credentials.update({"username": username})
|
|
280
|
+
self.credentials = Credentials.create(_credentials)
|
|
281
|
+
|
|
282
|
+
if self.auto_cache_credentials:
|
|
283
|
+
self.save_credentials()
|
|
284
|
+
return self.credentials
|
|
285
|
+
|
|
286
|
+
async def refresh_access_token(self):
|
|
287
|
+
"""Refresh access token using refresh token.
|
|
288
|
+
|
|
289
|
+
returns new Credentials if success, else RefreshTokenExpired exception
|
|
290
|
+
"""
|
|
291
|
+
login_body = f"client_id=ANDR&grant_type=refresh_token&refresh_token={self.credentials.refresh_token}"
|
|
292
|
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
log.debug("Trying refresh token ... ")
|
|
296
|
+
_credentials = await self.send_unauth_request(
|
|
297
|
+
EndPoint.LOGIN, headers=headers, data=login_body
|
|
298
|
+
)
|
|
299
|
+
except Ex.RefreshTokenExpired as ex:
|
|
300
|
+
raise ex from ex
|
|
301
|
+
|
|
302
|
+
self.credentials = Credentials.create(_credentials)
|
|
303
|
+
|
|
304
|
+
if self.auto_cache_credentials:
|
|
305
|
+
self.save_credentials()
|
|
306
|
+
|
|
307
|
+
return self.credentials
|
|
308
|
+
|
|
309
|
+
def get_request_url(self, request_endpoint: EndPoint) -> str | Ex.BadEndpointUrl:
|
|
310
|
+
"""Get requested url from endpoint.
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
request_endpoint (EndPoint): EndPoint
|
|
314
|
+
|
|
315
|
+
Raises:
|
|
316
|
+
Ex.BadEndpointUrl: if no server is specified
|
|
317
|
+
|
|
318
|
+
Returns:
|
|
319
|
+
str: full url of endpoint
|
|
320
|
+
|
|
321
|
+
"""
|
|
322
|
+
request = (
|
|
323
|
+
request_endpoint.endpoint
|
|
324
|
+
if request_endpoint.endpoint.lower().startswith(("http", "https"))
|
|
325
|
+
else f"{self.server}{request_endpoint.endpoint}"
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
if not request.lower().startswith(("http", "https")):
|
|
329
|
+
raise Ex.BadEndpointUrl(f"Bad endpoint url ({request})")
|
|
330
|
+
|
|
331
|
+
return request
|
|
332
|
+
|
|
333
|
+
def save_credentials(self, filename: str | None = None) -> bool:
|
|
334
|
+
"""Save credentials to file in JSON format.
|
|
335
|
+
|
|
336
|
+
If auto_save_credentials are enabled, parameters could be ommited.
|
|
337
|
+
"""
|
|
338
|
+
|
|
339
|
+
if not filename and self.auto_cache_credentials:
|
|
340
|
+
filename = self.cache_filename
|
|
341
|
+
try:
|
|
342
|
+
with open(filename, "wb") as file:
|
|
343
|
+
file.write(orjson.dumps(self.credentials, option=orjson.OPT_INDENT_2))
|
|
344
|
+
file.close()
|
|
345
|
+
except OSError:
|
|
346
|
+
return False
|
|
347
|
+
|
|
348
|
+
return True
|
|
349
|
+
|
|
350
|
+
def load_credentials(self, filename: str) -> Credentials | bool:
|
|
351
|
+
"""Load credentials from file."""
|
|
352
|
+
|
|
353
|
+
try:
|
|
354
|
+
with open(filename, "rb") as file:
|
|
355
|
+
data = orjson.loads(file.read())
|
|
356
|
+
file.close()
|
|
357
|
+
except OSError:
|
|
358
|
+
return False
|
|
359
|
+
|
|
360
|
+
self.credentials = Credentials.create_from_json(data)
|
|
361
|
+
return self.credentials
|
|
362
|
+
|
|
363
|
+
async def __aenter__(self) -> Self:
|
|
364
|
+
"""Async enter.
|
|
365
|
+
|
|
366
|
+
Returns:
|
|
367
|
+
Bakalari object.
|
|
368
|
+
|
|
369
|
+
"""
|
|
370
|
+
return self # pragma: no cover
|
|
371
|
+
|
|
372
|
+
async def __aexit__(self, *_exc_info: object) -> None:
|
|
373
|
+
"""Async exit.
|
|
374
|
+
|
|
375
|
+
Args:
|
|
376
|
+
_exc_info: Exec type.
|
|
377
|
+
|
|
378
|
+
"""
|
|
379
|
+
return # pragma: no cover
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Main module."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
import orjson
|
|
6
|
+
|
|
7
|
+
from .bakalari import Bakalari, Schools
|
|
8
|
+
from .komens import Komens, Messages, MessageContainer
|
|
9
|
+
from .first_login import first_login
|
|
10
|
+
|
|
11
|
+
import datetime
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def w(data):
|
|
15
|
+
with open(".data", "+wb") as fi:
|
|
16
|
+
fi.write(orjson.dumps(data, option=orjson.OPT_INDENT_2))
|
|
17
|
+
fi.close()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def runme():
|
|
21
|
+
|
|
22
|
+
# await first_login()
|
|
23
|
+
|
|
24
|
+
schools: Schools = await Schools().load_from_file("schools_data.json")
|
|
25
|
+
server = schools.get_url("Kadaňská")
|
|
26
|
+
|
|
27
|
+
bakalari = Bakalari(
|
|
28
|
+
server=server, auto_cache_credentials=True, cache_filename="new_data.json"
|
|
29
|
+
)
|
|
30
|
+
bakalari.load_credentials("new_data.json")
|
|
31
|
+
k = Komens(bakalari=bakalari)
|
|
32
|
+
|
|
33
|
+
await k.get_messages()
|
|
34
|
+
print(k.messages.count_messages())
|
|
35
|
+
|
|
36
|
+
print(datetime.date.today() + datetime.timedelta(days=-8))
|
|
37
|
+
|
|
38
|
+
messages = k.messages.get_messages_by_date(
|
|
39
|
+
datetime.date.today() + datetime.timedelta(days=-30),
|
|
40
|
+
to_date=datetime.date.today(),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
print(await k.count_unread_messages())
|
|
45
|
+
|
|
46
|
+
for msg in messages:
|
|
47
|
+
print(msg.text)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main() -> None:
|
|
51
|
+
|
|
52
|
+
loop = asyncio.get_event_loop()
|
|
53
|
+
loop.run_until_complete(runme())
|
bakalari_api/const.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Constants."""
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from typing import Any, Final
|
|
5
|
+
|
|
6
|
+
from .logger_api import api_logger
|
|
7
|
+
from strenum import StrEnum
|
|
8
|
+
|
|
9
|
+
log = api_logger("Bakalari API").get()
|
|
10
|
+
|
|
11
|
+
REQUEST_TIMEOUT: int = 10
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Errors(StrEnum):
|
|
15
|
+
"""Returned errors."""
|
|
16
|
+
|
|
17
|
+
INVALID_METHOD: str = "ID2084"
|
|
18
|
+
INVALID_LOGIN: str = "ID2024"
|
|
19
|
+
MISSING_LOGIN: str = "ID2059"
|
|
20
|
+
ACCESS_TOKEN_EXPIRED: str = "ID2019"
|
|
21
|
+
INVALID_TOKEN: str = "ID2004"
|
|
22
|
+
REFRESH_TOKEN_EXPIRED: str = "ID2012"
|
|
23
|
+
INVALID_REFRESH_TOKEN: str = "ID2003"
|
|
24
|
+
REFRESH_TOKEN_REDEEMD: str = "ID2012"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class EndPoint(Enum):
|
|
28
|
+
"""List of endpoints."""
|
|
29
|
+
|
|
30
|
+
VERSION: Final = {"endpoint": "/api", "method": "get"}
|
|
31
|
+
LOGIN: Final = {"endpoint": "/api/login", "method": "post"}
|
|
32
|
+
SCHOOL_LIST: Final = {
|
|
33
|
+
"endpoint": "https://sluzby.bakalari.cz/api/v1/municipality",
|
|
34
|
+
"method": "get",
|
|
35
|
+
}
|
|
36
|
+
KOMENS_UNREAD: Final = {
|
|
37
|
+
"endpoint": "/api/3/komens/messages/received",
|
|
38
|
+
"method": "post",
|
|
39
|
+
}
|
|
40
|
+
KOMENS_UNREAD_COUNT: Final = {
|
|
41
|
+
"endpoint": "/api/3/komens/messages/received/unread",
|
|
42
|
+
"method": "get",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
def get(self, key: str) -> Any:
|
|
46
|
+
"""Get key value."""
|
|
47
|
+
if not (ret := self.value.get(key)):
|
|
48
|
+
log.error(f"Requested key ({key}) is not valid. Check for spelling.")
|
|
49
|
+
return False
|
|
50
|
+
return ret
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def endpoint(self) -> str:
|
|
54
|
+
"""Endpoint property."""
|
|
55
|
+
|
|
56
|
+
return self.get("endpoint")
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def method(self) -> str:
|
|
60
|
+
"""Method property."""
|
|
61
|
+
return self.get("method")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Token(StrEnum):
|
|
65
|
+
"""Token."""
|
|
66
|
+
|
|
67
|
+
USER_ID: str = "bak:UserId"
|
|
68
|
+
ACCESS_TOKEN: str = "access_token"
|
|
69
|
+
REFRESH_TOKEN: str = "refresh_token"
|
|
70
|
+
USERNAME: str = "username"
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Datastructure."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import orjson
|
|
9
|
+
|
|
10
|
+
from .const import Token
|
|
11
|
+
from .logger_api import api_logger
|
|
12
|
+
|
|
13
|
+
log = api_logger("Bakalari API").get()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Credentials:
|
|
18
|
+
"""Credentials holder."""
|
|
19
|
+
|
|
20
|
+
username: str = None
|
|
21
|
+
access_token: str = None
|
|
22
|
+
refresh_token: str = None
|
|
23
|
+
user_id: str = None
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def create(cls, data: dict[str, Any]) -> Credentials:
|
|
27
|
+
"""Create class object form data."""
|
|
28
|
+
|
|
29
|
+
return cls(
|
|
30
|
+
user_id=data[Token.USER_ID],
|
|
31
|
+
access_token=data[Token.ACCESS_TOKEN],
|
|
32
|
+
refresh_token=data[Token.REFRESH_TOKEN],
|
|
33
|
+
username=data[Token.USERNAME],
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def create_from_json(cls, data: dict[str, Any]) -> Credentials:
|
|
38
|
+
"""Return class object from JSON dictionary."""
|
|
39
|
+
return Credentials.create(
|
|
40
|
+
{
|
|
41
|
+
Token.USER_ID: data["user_id"],
|
|
42
|
+
Token.ACCESS_TOKEN: data["access_token"],
|
|
43
|
+
Token.REFRESH_TOKEN: data["refresh_token"],
|
|
44
|
+
Token.USERNAME: data["username"],
|
|
45
|
+
}
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class School:
|
|
51
|
+
"""Data structure for one school item."""
|
|
52
|
+
|
|
53
|
+
name: str = None
|
|
54
|
+
api_point: str = None
|
|
55
|
+
town: str = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Schools:
|
|
59
|
+
"""List of schools with their url for Bakalari API."""
|
|
60
|
+
|
|
61
|
+
def __init__(self) -> None:
|
|
62
|
+
"""List of schools with their url for Bakalari API."""
|
|
63
|
+
|
|
64
|
+
self.school_list: list[School] = []
|
|
65
|
+
|
|
66
|
+
def append_school(
|
|
67
|
+
self,
|
|
68
|
+
name: str,
|
|
69
|
+
api_point: str,
|
|
70
|
+
town: str,
|
|
71
|
+
) -> bool:
|
|
72
|
+
"""Append new school to the school_list list."""
|
|
73
|
+
|
|
74
|
+
if name == "" or None:
|
|
75
|
+
log.error(
|
|
76
|
+
f"School's name should not be none or empty! (name={name}, api_point={api_point}, town={town})"
|
|
77
|
+
)
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
if api_point == "" or None:
|
|
81
|
+
log.error(
|
|
82
|
+
f"School's API point should not be none or empty! (name={name}, api_point={api_point}, town={town})"
|
|
83
|
+
)
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
if town == "" or None:
|
|
87
|
+
log.error(
|
|
88
|
+
f"School's town should not be none or empty! (name={name}, api_point={api_point}, town={town})"
|
|
89
|
+
)
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
new_school = School(name=name, api_point=api_point, town=town)
|
|
93
|
+
self.school_list.append(new_school)
|
|
94
|
+
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
def get_url(self, name: str | None = None, idx: int | None = None) -> str | False:
|
|
98
|
+
"""Return url for school from name or index in dictionary.
|
|
99
|
+
|
|
100
|
+
Only one must be specified - name or index, otherwise returns False
|
|
101
|
+
If name or index is not found in dictionary returns False.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
if (name is not None) and (idx is not None):
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
if name is not None:
|
|
108
|
+
for item in self.school_list:
|
|
109
|
+
if name in item.name:
|
|
110
|
+
return item.api_point
|
|
111
|
+
|
|
112
|
+
if idx is not None:
|
|
113
|
+
try:
|
|
114
|
+
return self.school_list[idx].api_point
|
|
115
|
+
except IndexError:
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
return False
|
|
119
|
+
|
|
120
|
+
def get_schools_by_town(self, town: str | None = None) -> list[School]:
|
|
121
|
+
"""Get list of schools in town."""
|
|
122
|
+
_schools = []
|
|
123
|
+
for item in self.school_list:
|
|
124
|
+
_schools.append(item) if item.town in town else None
|
|
125
|
+
return _schools
|
|
126
|
+
|
|
127
|
+
def get_school_name_by_api_point(self, api_point: str) -> str | bool:
|
|
128
|
+
"""Get school name by its api point."""
|
|
129
|
+
|
|
130
|
+
for item in self.school_list:
|
|
131
|
+
if api_point == item.api_point:
|
|
132
|
+
return item.name
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
def save_to_file(self, filename: str) -> bool:
|
|
136
|
+
"""Save loaded school list to file in JSON format."""
|
|
137
|
+
|
|
138
|
+
schools = []
|
|
139
|
+
|
|
140
|
+
for item in self.school_list:
|
|
141
|
+
new_data = {
|
|
142
|
+
"name": item.name,
|
|
143
|
+
"api_point": item.api_point,
|
|
144
|
+
"town": item.town,
|
|
145
|
+
}
|
|
146
|
+
schools.append(new_data)
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
with open(filename, "wb") as file:
|
|
150
|
+
file.write(orjson.dumps(schools, option=orjson.OPT_INDENT_2))
|
|
151
|
+
file.close()
|
|
152
|
+
except OSError:
|
|
153
|
+
return False
|
|
154
|
+
|
|
155
|
+
return True
|
|
156
|
+
|
|
157
|
+
async def load_from_file(self, filename: str) -> Schools:
|
|
158
|
+
"""Load schools list from a file."""
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
with open(filename, mode="+rb") as file:
|
|
162
|
+
data = orjson.loads(file.read())
|
|
163
|
+
file.close()
|
|
164
|
+
except OSError:
|
|
165
|
+
return False
|
|
166
|
+
except orjson.JSONDecodeError:
|
|
167
|
+
log.error(f"Unable to decode JSON file. File {filename} is corrupted.")
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
for item in data:
|
|
171
|
+
self.append_school(
|
|
172
|
+
item.get("name"), item.get("api_point"), item.get("town")
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
return self
|