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.
@@ -0,0 +1,64 @@
1
+ """Exceptions."""
2
+
3
+ from .logger_api import api_logger
4
+
5
+ logger = api_logger("Bakalari API").get()
6
+
7
+
8
+ class APIException(Exception):
9
+ """General API exception."""
10
+
11
+ def __init__(self, message, *args, **kwargs):
12
+ """General API Exception."""
13
+
14
+ super().__init__(message)
15
+ logger.error("(%s): %s", self.__class__.__name__, self)
16
+
17
+
18
+ class Ex(APIException):
19
+ """Root exception class."""
20
+
21
+ class InvalidCredentials(APIException):
22
+ """Invalid credentials."""
23
+
24
+ class InvalidResponse(APIException):
25
+ """Invalid response from server."""
26
+
27
+ class TimeoutException(APIException):
28
+ """Server timeout."""
29
+
30
+ class BadRequestException(APIException):
31
+ """Bad request."""
32
+
33
+ class InvalidHTTPMethod(APIException):
34
+ """Invalid HTTP method."""
35
+
36
+ class InvalidLogin(APIException):
37
+ """Invalid login (username/password)."""
38
+
39
+ class AccessTokenExpired(APIException):
40
+ """Access token expired. Refresh with refresh token."""
41
+
42
+ class RefreshTokenExpired(APIException):
43
+ """Refresh token expired. You have to login with username and password."""
44
+
45
+ class RefreshTokenRedeemd(APIException):
46
+ """Refresh token already redeemd. Use access token."""
47
+
48
+ class InvalidRefreshToken(APIException):
49
+ """Refresh token is invalid."""
50
+
51
+ class TokensExpired(APIException):
52
+ """Access token and refresh token expired."""
53
+
54
+ class BadEndpointUrl(APIException):
55
+ """Bad endpoint url."""
56
+
57
+ class TokenMissing(APIException):
58
+ """Either Access token or Refresh token is missing."""
59
+
60
+ class InvalidToken(APIException):
61
+ """Specified token is invalid."""
62
+
63
+ class CacheError(APIException):
64
+ """Auto-cache is enabled, but no filename is provided."""
@@ -0,0 +1,13 @@
1
+ """First login - for demo only."""
2
+
3
+ from .bakalari import Bakalari, Schools
4
+
5
+ async def first_login():
6
+ schools: Schools = Schools().load_from_file("schools_data.json")
7
+
8
+ bakalari = Bakalari(
9
+ schools.get_url("Your school"),
10
+ auto_cache_credentials=True,
11
+ cache_filename="new_data.json",
12
+ )
13
+ await bakalari.first_login("username", "password")
bakalari_api/komens.py ADDED
@@ -0,0 +1,155 @@
1
+ """Module for working with Komens."""
2
+
3
+ from datetime import datetime as dt
4
+ from typing import Any
5
+
6
+ import dateutil
7
+ import orjson
8
+
9
+ from .bakalari import Bakalari
10
+ from .const import EndPoint
11
+ from .logger_api import api_logger
12
+
13
+ log = api_logger("Bakalari API").get()
14
+
15
+
16
+ class MessageContainer:
17
+ """Messages registry."""
18
+
19
+ mid: int
20
+ title: str
21
+ text: str
22
+ sent: dt.date
23
+ sender: dict[str, str]
24
+ attachments: dict[str, str]
25
+
26
+ def __init__(
27
+ self,
28
+ *,
29
+ mid: int,
30
+ title: str,
31
+ text: str,
32
+ sent: dt,
33
+ sender: dict[str, str],
34
+ attachments: dict[str, str] | None = None,
35
+ ):
36
+ """Initialize MessagesContainer."""
37
+
38
+ _setter = object.__setattr__
39
+ _setter(self, "mid", mid)
40
+ _setter(self, "title", title)
41
+ _setter(self, "text", text)
42
+ _setter(self, "sent", sent)
43
+ _setter(self, "sender", sender)
44
+ _setter(self, "attachments", attachments)
45
+
46
+ def __repr__(self) -> str:
47
+ """Representation of MessageContainer."""
48
+ return (
49
+ f"<MessageContainer message_id={self.mid} "
50
+ f"title={self.title} sender={self.sender}>"
51
+ )
52
+
53
+ def __setattr__(self, key: str, value: Any) -> None:
54
+ """Set an attribute."""
55
+ super().__setattr__(key, value)
56
+
57
+ def as_json(self) -> orjson.Fragment:
58
+ """Return JSON fragment of message."""
59
+ json_repr = {
60
+ "mid": self.mid,
61
+ "title": self.title,
62
+ "text": self.text,
63
+ "sent": self.sent,
64
+ "sender": self.sender,
65
+ "attachments": self.attachments,
66
+ }
67
+ return orjson.Fragment(json_repr)
68
+
69
+ def __str__(self) -> str:
70
+ """Return string representation of data."""
71
+ return f"""Message id: {self.mid}
72
+ title: {self.title}
73
+ text: {self.text},
74
+ sent: {self.sent.date()},
75
+ sender: {self.sender},
76
+ attachments: {self.attachments}"""
77
+
78
+
79
+ class Messages(list[MessageContainer]):
80
+ """Messages class holds all messages."""
81
+
82
+ def __init__(self) -> None:
83
+ """Messages class holds all messages."""
84
+ super().__init__()
85
+
86
+ def add_message(self, data: MessageContainer):
87
+ """Add new message to list."""
88
+ self.append([data])
89
+
90
+ def get_message_by_id(self, id: int) -> MessageContainer:
91
+ """Get message by id."""
92
+ for i in self:
93
+ if i[0].mid == id:
94
+ return i[0]
95
+
96
+ def get_messages_by_date(
97
+ self, date: dt, to_date: dt | None = None
98
+ ) -> list[MessageContainer]:
99
+ """Get messages by date.
100
+
101
+ If `to_date` is set, then returns list of range from `date` to `to_date`
102
+ """
103
+
104
+ messages = []
105
+
106
+ for i in self:
107
+ if to_date:
108
+ if (i[0].sent.date() >= date) and (i[0].sent.date() <= to_date):
109
+ messages.append(i[0])
110
+ elif i[0].sent.date() == date:
111
+ messages.append(i[0])
112
+ return None if len(messages) == 0 else messages
113
+
114
+ def count_messages(self) -> int:
115
+ """Count messages."""
116
+ return len(self)
117
+
118
+
119
+ class Komens:
120
+ """Class for working with Komens messages."""
121
+
122
+ def __init__(self, bakalari: Bakalari):
123
+ """Initialize class Komens."""
124
+ self.bakalari = bakalari
125
+ self.messages = Messages()
126
+
127
+ async def get_messages(self) -> Messages:
128
+ """Get unread messages."""
129
+ messages = await self.bakalari.send_auth_request(
130
+ EndPoint.KOMENS_UNREAD,
131
+ )
132
+
133
+ _messages = Messages()
134
+
135
+ # with open(".data", "rb") as f:
136
+ # messages = orjson.loads(f.read())
137
+ # f.close()
138
+
139
+ for msg in messages["Messages"]:
140
+ log.debug(f"Writing message: {msg}")
141
+ _message = MessageContainer(
142
+ mid=msg["Id"],
143
+ title=msg["Title"],
144
+ text=msg["Text"],
145
+ sent=dateutil.parser.parse(msg["SentDate"]),
146
+ sender=msg["Sender"]["Name"],
147
+ attachments=msg["Attachments"],
148
+ )
149
+ self.messages.add_message(_message)
150
+
151
+ return _messages
152
+
153
+ async def count_unread_messages(self) -> int:
154
+ """Get count of unreaded messages."""
155
+ return await self.bakalari.send_auth_request(EndPoint.KOMENS_UNREAD_COUNT)
@@ -0,0 +1,61 @@
1
+ """Bakalari API logger."""
2
+
3
+ import logging
4
+ import logging.handlers
5
+
6
+
7
+ class CustomFormatter(logging.Formatter):
8
+ """Custom formater for module."""
9
+
10
+ black = "\u001b[30m"
11
+ yellow = "\u001b[33m"
12
+ red = "\u001b[31m"
13
+ bold_red = "\x1b[31;1m"
14
+ reset = "\u001b[0m"
15
+ green = "\u001b[32m"
16
+ grey = "\u001b[30m"
17
+ blue = "\u001b[34m"
18
+ magenta = "\u001b[35m"
19
+ cyan = "\u001b[36m"
20
+ white = "\u001b[37m"
21
+
22
+ format = f"%(asctime)s - %(name)s - %(levelname)s - %(threadName)s:\n {cyan}Message: %(message)s\n{magenta}@(%(filename)s:%(lineno)d)"
23
+ dateformat = "%d/%m/%Y %H:%M:%S"
24
+
25
+ FORMATS = {
26
+ logging.DEBUG: grey + format + reset,
27
+ logging.INFO: green + format + reset,
28
+ logging.WARNING: yellow + format + reset,
29
+ logging.ERROR: bold_red + format + reset,
30
+ logging.CRITICAL: bold_red + format + reset,
31
+ }
32
+
33
+ def format(self, record):
34
+ """Format string."""
35
+
36
+ log_fmt = self.FORMATS.get(record.levelno)
37
+ formatter = logging.Formatter(log_fmt, datefmt=self.dateformat)
38
+ return formatter.format(record)
39
+
40
+
41
+ class api_logger:
42
+ """API logger."""
43
+
44
+ def __init__(self, name, loglevel: logging = logging.ERROR):
45
+ """Create API logger."""
46
+ self.name = name
47
+ self.loglevel = loglevel
48
+
49
+ self.console_formatter = CustomFormatter()
50
+ self.console_logger = logging.StreamHandler()
51
+ self.console_logger.setFormatter(self.console_formatter)
52
+
53
+ self.logger = logging.getLogger(name)
54
+ if self.logger.handlers:
55
+ self.logger.handlers.pop()
56
+ self.logger.addHandler(self.console_logger)
57
+ self.logger.setLevel(self.loglevel)
58
+
59
+ def get(self):
60
+ "Get."
61
+ return self.logger