nit-tools 0.1.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.
nit_tools/client.py ADDED
@@ -0,0 +1,344 @@
1
+ """Small synchronous client based on the observed NIT diary request."""
2
+
3
+ import logging
4
+ import time
5
+ from datetime import date, timedelta
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Callable
8
+
9
+ import requests
10
+
11
+ from .auth import AuthResult, auto_auth
12
+ from .errors import InvalidResponseError, NetworkError, NITError, http_error
13
+ from .models import Attachment, DiaryDay, Lesson, MarkRecord, parse_date
14
+ from .user import UserProfile
15
+
16
+ if TYPE_CHECKING:
17
+ from .my_class import MyClass
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class NITClient:
24
+ def __init__(
25
+ self,
26
+ token: str,
27
+ school_id: str | int,
28
+ user_id: str,
29
+ *,
30
+ locale: str = "uk",
31
+ timeout: float = 30,
32
+ reauthenticate: Callable[[], AuthResult] | None = None,
33
+ headers: dict[str, str] | None = None,
34
+ cookies: list[dict] | None = None,
35
+ class_id: str | None = None,
36
+ ):
37
+ if not token.strip() or not str(school_id).strip() or not user_id.strip():
38
+ raise ValueError("token, school_id and user_id must be non-empty")
39
+ self._token = token
40
+ self.school_id = str(school_id)
41
+ self.user_id = user_id
42
+ self.locale = locale
43
+ self.timeout = timeout
44
+ self._reauthenticate = reauthenticate
45
+ self._headers = dict(headers or {})
46
+ self._cookies = self._cookie_jar(cookies or [])
47
+ self.class_id = class_id
48
+
49
+ @staticmethod
50
+ def _cookie_jar(cookies: list[dict]) -> requests.cookies.RequestsCookieJar:
51
+ """Preserve cookie domains, paths, secure flags and expiration."""
52
+ jar = requests.cookies.RequestsCookieJar()
53
+ for cookie in cookies:
54
+ expires = cookie.get("expires", -1)
55
+ jar.set(
56
+ cookie["name"], cookie["value"], domain=cookie["domain"],
57
+ path=cookie.get("path", "/"), secure=cookie.get("secure", False),
58
+ expires=int(expires) if expires > 0 else None,
59
+ )
60
+ return jar
61
+
62
+ @classmethod
63
+ def from_auth(cls, auth: AuthResult, **kwargs) -> "NITClient":
64
+ """Create a client with the identity and application headers from login."""
65
+ kwargs.setdefault('class_id', auth.class_id)
66
+ return cls(auth.token, auth.school_id, auth.user_id, headers=auth.headers, cookies=auth.cookies, **kwargs)
67
+
68
+ @classmethod
69
+ def connect(
70
+ cls, email: str | None = None, password: str | None = None, *,
71
+ auth_file: str | Path = '.nit-auth.json', headless: bool = True,
72
+ force: bool = False, require_class_id: bool = False,
73
+ credential_provider: Callable[[], tuple[str, str]] | None = None,
74
+ timeout: float = 30, locale: str = 'uk', login_options: dict | None = None,
75
+ ) -> "NITClient":
76
+ """Load a saved session or log in, and refresh it once on HTTP 401.
77
+
78
+ Credentials/provider are retained in memory for future logins, never
79
+ stored in the authentication file. This method does not load .env or
80
+ prompt for input; applications can do so through credential_provider.
81
+ """
82
+ options = dict(login_options or {})
83
+ reserved = {'email', 'password', 'path', 'force', 'headless', 'require_class_id', 'credential_provider'}
84
+ if reserved.intersection(options):
85
+ raise ValueError('Use connect parameters rather than login_options for authentication settings')
86
+
87
+ def authenticate(force_login: bool = False) -> AuthResult:
88
+ return auto_auth(
89
+ email, password, path=auth_file, headless=headless, force=force_login,
90
+ require_class_id=require_class_id, credential_provider=credential_provider,
91
+ **options,
92
+ )
93
+
94
+ auth = authenticate(force)
95
+ return cls.from_auth(auth, reauthenticate=lambda: authenticate(True), timeout=timeout, locale=locale)
96
+
97
+ def download_attachment(
98
+ self, attachment: Attachment, folder: str | Path = 'homework', *, overwrite: bool = False,
99
+ ) -> Path:
100
+ """Stream one signed attachment to disk, without sending the API token."""
101
+ from .downloads import download_attachment
102
+
103
+ agent = requests.structures.CaseInsensitiveDict(self._headers).get('User-Agent')
104
+ return download_attachment(attachment, folder, timeout=self.timeout, user_agent=agent, overwrite=overwrite)
105
+
106
+ def download_homework(
107
+ self, day: date | str, folder: str | Path = 'homework', *,
108
+ subject: str | None = None, overwrite: bool = False, request_delay: float = 0.5,
109
+ ) -> list[Path]:
110
+ """Save homework attachments under folder/date/lesson_subject/filename.
111
+
112
+ Homework text and lesson URLs are not downloaded. Repeated attachment
113
+ IDs are downloaded once per call. Completed files remain if a later
114
+ download fails; the failed file is never committed partially.
115
+ """
116
+ from .downloads import safe_filename
117
+
118
+ if request_delay < 0:
119
+ raise ValueError('request_delay must be non-negative')
120
+ target_day = parse_date(day)
121
+ root = Path(folder).resolve()
122
+ downloaded = []
123
+ seen = set()
124
+ for lesson in self.get_homework(target_day, subject):
125
+ directory = root / target_day.isoformat() / f'{lesson.number:02d}_{safe_filename(lesson.subject)}'
126
+ if not directory.resolve().is_relative_to(root):
127
+ raise ValueError('Homework folder resolves outside the requested destination')
128
+ for attachment in lesson.attachments:
129
+ identity = attachment.id or attachment.url
130
+ if identity in seen:
131
+ continue
132
+ if downloaded:
133
+ time.sleep(request_delay)
134
+ downloaded.append(self.download_attachment(attachment, directory, overwrite=overwrite))
135
+ seen.add(identity)
136
+ return downloaded
137
+
138
+ def get_days(self, day: date | str) -> list[DiaryDay]:
139
+ """Return all days provided by the API for the requested date."""
140
+ return [DiaryDay.from_dict(item) for item in self.get_diary(parse_date(day))["data"]]
141
+
142
+ def get_day(self, day: date | str) -> DiaryDay | None:
143
+ """Return exactly the requested day, or None if the API omits it."""
144
+ target = parse_date(day)
145
+ return next((item for item in self.get_days(target) if item.date == target), None)
146
+
147
+ def get_lessons(self, day: date | str, subject: str | None = None) -> list[Lesson]:
148
+ """Return a day's lessons, optionally filtered by subject."""
149
+ result = self.get_day(day)
150
+ return result.get_lessons(subject) if result else []
151
+
152
+ def get_homework(self, day: date | str, subject: str | None = None) -> list[Lesson]:
153
+ """Return lessons containing homework text or attachments."""
154
+ return [lesson for lesson in self.get_lessons(day, subject) if lesson.has_homework]
155
+
156
+ def get_marks(self, day: date | str, subject: str | None = None) -> list[Lesson]:
157
+ """Return lessons containing grades or attendance records."""
158
+ return [lesson for lesson in self.get_lessons(day, subject) if lesson.marks]
159
+
160
+ def get_days_between(
161
+ self, start: date | str, end: date | str, *, request_delay: float = 0.5,
162
+ ) -> list[DiaryDay]:
163
+ """Fetch an inclusive period, reusing days from multi-day responses.
164
+
165
+ Omitted dates are not synthesized as empty school days. HTTP errors
166
+ propagate so a failed fetch cannot silently produce a partial report.
167
+ """
168
+ start, end = parse_date(start), parse_date(end)
169
+ if start > end:
170
+ raise ValueError("start must be on or before end")
171
+ if request_delay < 0:
172
+ raise ValueError("request_delay must be non-negative")
173
+ days: dict[date, DiaryDay] = {}
174
+ current = start
175
+ requested = False
176
+ while True:
177
+ if current not in days:
178
+ if requested:
179
+ logger.info("Pausing %.2f seconds before the next report request", request_delay)
180
+ time.sleep(request_delay)
181
+ for item in self.get_days(current):
182
+ if start <= item.date <= end:
183
+ days[item.date] = item
184
+ requested = True
185
+ if current == end:
186
+ break
187
+ current += timedelta(days=1)
188
+ return [days[key] for key in sorted(days)]
189
+
190
+ def get_marks_between(
191
+ self, start: date | str, end: date | str, subject: str | None = None,
192
+ *, request_delay: float = 0.5,
193
+ ) -> list[MarkRecord]:
194
+ """Return dated mark/attendance records, deduplicated by API mark ID."""
195
+ start, end = parse_date(start), parse_date(end)
196
+ records = []
197
+ seen = set()
198
+ for day in self.get_days_between(start, end, request_delay=request_delay):
199
+ for lesson in day.get_marks(subject):
200
+ for mark in lesson.marks:
201
+ mark_date = date.fromisoformat(mark.raw['day'].split('T', 1)[0]) if mark.raw.get('day') else day.date
202
+ if not start <= mark_date <= end:
203
+ continue
204
+ mark_id = mark.raw.get('id')
205
+ if mark_id and mark_id in seen:
206
+ continue
207
+ if mark_id:
208
+ seen.add(mark_id)
209
+ records.append(MarkRecord(mark_date, lesson.subject, lesson.number, mark))
210
+ return sorted(records, key=lambda item: (item.date, item.lesson_number, item.subject))
211
+
212
+ def export_marks(
213
+ self, start: date | str, end: date | str, path: str | Path | None = None,
214
+ *, subject: str | None = None, report_type: str = 'summary', request_delay: float = 0.5,
215
+ ) -> Path:
216
+ """Save an Excel grade report and return its path."""
217
+ from .reports import write_marks_report
218
+
219
+ start, end = parse_date(start), parse_date(end)
220
+ if start > end:
221
+ raise ValueError("start must be on or before end")
222
+ if report_type not in {'summary', 'detailed'}:
223
+ raise ValueError("report_type must be summary or detailed")
224
+ target = Path(path) if path is not None else Path('reports') / f'marks_{report_type}_{start}_{end}.xlsx'
225
+ if target.suffix.lower() != '.xlsx':
226
+ raise ValueError("Report path must have an .xlsx extension")
227
+ records = self.get_marks_between(start, end, subject, request_delay=request_delay)
228
+ return write_marks_report(records, start, end, target, report_type=report_type)
229
+
230
+ def get_diary(self, day: date) -> dict:
231
+ """Return the full diary response for a date, including data and total.
232
+
233
+ NIT returned multiple days for the observed request. No assumption is
234
+ made that the response contains only the requested date.
235
+ """
236
+ # Use English names explicitly so the process locale cannot change them.
237
+ weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
238
+ months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
239
+ value = f"{weekdays[day.weekday()]} {months[day.month - 1]} {day.day:02d} {day.year}"
240
+ return self._get("/dashboard/diary", params={"date": value}, alias="user-diary")
241
+
242
+ def my_class(self, class_id: str | None = None) -> "MyClass":
243
+ """Bind the class submodule to this client's authenticated session."""
244
+ from .my_class import MyClass
245
+
246
+ selected = self.class_id if class_id is None else class_id
247
+ if selected is None:
248
+ raise ValueError("Class ID was not detected. Log in again to capture the student profile, or pass class_id explicitly.")
249
+ return MyClass(self, selected)
250
+
251
+ def get_user(self, user_id: str | None = None) -> UserProfile:
252
+ """Fetch one profile; default to the authenticated user."""
253
+ target = self.user_id if user_id is None else user_id
254
+ if not isinstance(target, str) or not target.strip():
255
+ raise ValueError('user_id must be a non-empty string')
256
+ payload = self._get('/users/' + requests.utils.quote(target, safe=''), params={}, alias='users')
257
+ profile = UserProfile.from_dict(payload, self.school_id)
258
+ if profile.id == self.user_id and profile.class_id is not None:
259
+ self.class_id = profile.class_id
260
+ return profile
261
+
262
+ def export_user(
263
+ self, path: str | Path | None = None, *, user_id: str | None = None,
264
+ user: UserProfile | None = None,
265
+ ) -> Path:
266
+ """Export a profile, school memberships and related people to Excel."""
267
+ from .reports import write_user_report
268
+
269
+ if user is not None and user_id is not None and user.id != user_id:
270
+ raise ValueError('user and user_id refer to different profiles')
271
+ target_id = user.id if user is not None else (self.user_id if user_id is None else user_id)
272
+ # Avoid treating a supplied ID as a filesystem path.
273
+ target = Path(path) if path is not None else Path('reports') / f'user_{requests.utils.quote(target_id, safe="")}.xlsx'
274
+ if target.suffix.lower() != '.xlsx':
275
+ raise ValueError('Report path must have an .xlsx extension')
276
+ profile = user if user is not None else self.get_user(user_id)
277
+ return write_user_report(profile, target)
278
+
279
+ def _get(self, path: str, *, params: dict, alias: str) -> dict:
280
+ """Make an authenticated API GET with one shared reauthentication policy."""
281
+ for attempt in range(2):
282
+ logger.info("Requesting %s (attempt %s)", path, attempt + 1)
283
+ try:
284
+ response = requests.get(
285
+ "https://api.nit.school/api/v1" + path,
286
+ params=params,
287
+ headers={
288
+ "X-NIT-CLIENT-VERSION": "v1.11.3.0",
289
+ "Content-Type": "application/json",
290
+ **self._headers,
291
+ "Authorization": f"Bearer {self._token}",
292
+ "X-NIT-REQUESTED-SCHOOL-ID": self.school_id,
293
+ "X-NIT-REQUESTED-USER-ID": self.user_id,
294
+ "X-NIT-LOCALE": self.locale,
295
+ "X-NIT-CLIENT": "web",
296
+ "Alias": alias,
297
+ "Referer": "https://app.nit.school/",
298
+ "Accept": "application/json",
299
+ },
300
+ timeout=self.timeout,
301
+ cookies=self._cookies,
302
+ )
303
+ except requests.RequestException:
304
+ logger.error("API connection failed for %s", path)
305
+ raise NetworkError(message="Could not connect to the NIT API") from None
306
+ with response:
307
+ logger.info("API %s returned HTTP %s", path, response.status_code)
308
+ if response.status_code == 401 and attempt == 0 and self._reauthenticate:
309
+ logger.info("Access token rejected; reauthenticating")
310
+ auth = self._reauthenticate()
311
+ self._token = auth.token
312
+ self.school_id = str(auth.school_id)
313
+ self.user_id = auth.user_id
314
+ self._headers = dict(auth.headers)
315
+ self._cookies = self._cookie_jar(auth.cookies)
316
+ self.class_id = auth.class_id
317
+ logger.info("Credentials updated; retrying API request")
318
+ continue
319
+ if not response.ok:
320
+ logger.error("API %s request failed (HTTP %s)", path, response.status_code)
321
+ if response.status_code == 403:
322
+ logger.error(
323
+ "API access forbidden; verify the selected school/user and access in the web app. "
324
+ "Response Content-Type: %s",
325
+ response.headers.get("Content-Type", "unknown"),
326
+ )
327
+ logger.error(
328
+ "Response diagnostics: server=%s, bytes=%s, redirected=%s, browser metadata=%s",
329
+ response.headers.get("Server", "unknown"),
330
+ len(response.content),
331
+ bool(response.history),
332
+ ", ".join(sorted(self._headers)) or "none",
333
+ )
334
+ logger.error("Request reference (CF-Ray): %s", response.headers.get("CF-Ray", "unavailable"))
335
+ raise http_error(response.status_code, response.headers)
336
+ try:
337
+ data = response.json()
338
+ except ValueError:
339
+ raise InvalidResponseError(message="NIT API did not return valid JSON") from None
340
+ if not isinstance(data, dict):
341
+ raise InvalidResponseError(message="Expected a JSON object from NIT API")
342
+ logger.info("API response decoded successfully")
343
+ return data
344
+ raise RuntimeError("Unreachable retry state")
nit_tools/downloads.py ADDED
@@ -0,0 +1,96 @@
1
+ """Atomic downloads of signed homework attachment URLs."""
2
+
3
+ import logging
4
+ import re
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ import requests
9
+
10
+ from .errors import NetworkError, http_error
11
+ from .models import Attachment
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def safe_filename(value: str) -> str:
17
+ """Keep a single portable name; never trust paths supplied by the API."""
18
+ value = value.replace('\\', '/').rsplit('/', 1)[-1]
19
+ value = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', value).strip(' .')
20
+ if not value:
21
+ value = 'attachment'
22
+ reserved = {'CON', 'PRN', 'AUX', 'NUL'} | {f'{prefix}{i}' for prefix in ('COM', 'LPT') for i in range(1, 10)}
23
+ if value.split('.', 1)[0].upper() in reserved:
24
+ value = '_' + value
25
+ # Leave room for collision suffixes on filesystems with a 255-byte limit.
26
+ if len(value.encode('utf-8')) > 220:
27
+ suffix = Path(value).suffix
28
+ suffix = suffix if len(suffix.encode('utf-8')) <= 30 else ''
29
+ stem = value[:-len(suffix)] if suffix else value
30
+ stem = stem.encode('utf-8')[:220 - len(suffix.encode('utf-8'))].decode('utf-8', errors='ignore')
31
+ value = stem + suffix
32
+ return value
33
+
34
+
35
+ def _commit(temporary: Path, target: Path, overwrite: bool) -> Path:
36
+ """Reserve a new filename exclusively so collisions never overwrite files."""
37
+ if overwrite:
38
+ temporary.replace(target)
39
+ return target
40
+ candidate = target
41
+ counter = 2
42
+ while True:
43
+ try:
44
+ with candidate.open('xb'):
45
+ pass
46
+ except FileExistsError:
47
+ candidate = target.with_name(f'{target.stem} ({counter}){target.suffix}')
48
+ counter += 1
49
+ continue
50
+ try:
51
+ temporary.replace(candidate)
52
+ except OSError:
53
+ candidate.unlink(missing_ok=True)
54
+ raise
55
+ return candidate
56
+
57
+
58
+ def download_attachment(
59
+ attachment: Attachment, folder: str | Path, *, timeout: float = 30,
60
+ user_agent: str | None = None, overwrite: bool = False,
61
+ ) -> Path:
62
+ """Download a signed HTTPS URL without API credentials or cookies.
63
+
64
+ Use freshly fetched attachments: the storage URL may have expired. Logs
65
+ and network exceptions never include the signed URL or its query string.
66
+ """
67
+ parsed = requests.utils.urlparse(attachment.url)
68
+ if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password:
69
+ raise ValueError('Attachment URL must be HTTPS without embedded credentials')
70
+ directory = Path(folder)
71
+ directory.mkdir(parents=True, exist_ok=True)
72
+ target = directory / safe_filename(attachment.name)
73
+ temporary = None
74
+ headers = {'Accept': '*/*'}
75
+ if user_agent:
76
+ headers['User-Agent'] = user_agent
77
+ logger.info('Downloading homework attachment %s', target.name)
78
+ try:
79
+ try:
80
+ # Storage links carry their own signatures; never copy API headers.
81
+ with requests.get(attachment.url, headers=headers, timeout=timeout, stream=True) as response:
82
+ if not response.ok:
83
+ raise http_error(response.status_code, response.headers)
84
+ with tempfile.NamedTemporaryFile(dir=directory, suffix='.part', delete=False) as handle:
85
+ temporary = Path(handle.name)
86
+ for chunk in response.iter_content(chunk_size=64 * 1024):
87
+ if chunk:
88
+ handle.write(chunk)
89
+ saved = _commit(temporary, target, overwrite)
90
+ except requests.RequestException:
91
+ raise NetworkError(message='Attachment download failed; no partial file was saved') from None
92
+ finally:
93
+ if temporary is not None:
94
+ temporary.unlink(missing_ok=True)
95
+ logger.info('Saved homework attachment to %s', saved)
96
+ return saved
nit_tools/errors.py ADDED
@@ -0,0 +1,74 @@
1
+ """Public, credential-safe exceptions for NIT API operations."""
2
+
3
+ from datetime import datetime, timezone
4
+ from email.utils import parsedate_to_datetime
5
+ from typing import Mapping
6
+
7
+
8
+ class NITError(Exception):
9
+ """Base error; existing handlers for NITError remain valid."""
10
+
11
+ def __init__(
12
+ self, status_code: int | None = None, request_id: str | None = None,
13
+ *, message: str | None = None,
14
+ ):
15
+ self.status_code = status_code
16
+ self.request_id = request_id
17
+ super().__init__(message or f"NIT API returned HTTP {status_code}")
18
+
19
+
20
+ class AuthenticationError(NITError):
21
+ """HTTP 401, or a failed browser authentication attempt."""
22
+
23
+
24
+ class AccessDeniedError(NITError):
25
+ """HTTP 403. Reauthentication is not attempted automatically."""
26
+
27
+
28
+ class NotFoundError(NITError):
29
+ """HTTP 404."""
30
+
31
+
32
+ class RateLimitError(NITError):
33
+ """HTTP 429, with the server's optional Retry-After guidance."""
34
+
35
+ def __init__(self, status_code=429, request_id=None, *, retry_after: float | None = None):
36
+ self.retry_after = retry_after
37
+ super().__init__(status_code, request_id)
38
+
39
+
40
+ class ServerError(NITError):
41
+ """An HTTP 5xx server response."""
42
+
43
+
44
+ class NetworkError(NITError):
45
+ """A connection, timeout or streaming error without sensitive request details."""
46
+
47
+
48
+ class InvalidResponseError(NITError):
49
+ """The API response could not be decoded as a JSON object."""
50
+
51
+
52
+ def http_error(status: int, headers: Mapping[str, str] | None = None) -> NITError:
53
+ """Map HTTP status codes without retaining response bodies or signed URLs."""
54
+ headers = {key.lower(): value for key, value in (headers or {}).items()}
55
+ request_id = headers.get('cf-ray')
56
+ if status == 429:
57
+ raw = headers.get('retry-after')
58
+ seconds = None
59
+ if isinstance(raw, str):
60
+ try:
61
+ seconds = max(0, int(raw.strip()))
62
+ except ValueError:
63
+ try:
64
+ deadline = parsedate_to_datetime(raw)
65
+ if deadline.tzinfo is None:
66
+ deadline = deadline.replace(tzinfo=timezone.utc)
67
+ seconds = max(0.0, (deadline - datetime.now(timezone.utc)).total_seconds())
68
+ except (ValueError, TypeError, OverflowError):
69
+ pass
70
+ return RateLimitError(status, request_id, retry_after=seconds)
71
+ error_type = {401: AuthenticationError, 403: AccessDeniedError, 404: NotFoundError}.get(status)
72
+ if error_type is None:
73
+ error_type = ServerError if 500 <= status <= 599 else NITError
74
+ return error_type(status, request_id)
nit_tools/models.py ADDED
@@ -0,0 +1,128 @@
1
+ """Convenient diary objects with access to the original API fields."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import date, datetime
5
+ from typing import Any
6
+
7
+
8
+ def parse_date(value: date | str) -> date:
9
+ """Accept a date or an ISO YYYY-MM-DD string."""
10
+ if isinstance(value, datetime):
11
+ return value.date()
12
+ return date.fromisoformat(value) if isinstance(value, str) else value
13
+
14
+
15
+ @dataclass
16
+ class Attachment:
17
+ id: str
18
+ name: str
19
+ url: str
20
+
21
+ @classmethod
22
+ def from_dict(cls, data: dict) -> "Attachment":
23
+ return cls(data['id'], data['fileName'], data['filePath'])
24
+
25
+
26
+ @dataclass
27
+ class Mark:
28
+ point: str | None
29
+ absence: int | None
30
+ raw: dict[str, Any] = field(repr=False)
31
+
32
+ @classmethod
33
+ def from_dict(cls, data: dict) -> "Mark":
34
+ # Preserve strings and the API's original misspelled "absense" field.
35
+ return cls(data.get('point'), data.get('absense'), data)
36
+
37
+
38
+ @dataclass
39
+ class MarkRecord:
40
+ """A mark with the date and subject needed for a period report."""
41
+
42
+ date: date
43
+ subject: str
44
+ lesson_number: int
45
+ mark: Mark
46
+
47
+ @property
48
+ def point(self) -> str | None:
49
+ return self.mark.point
50
+
51
+ @property
52
+ def absence(self) -> int | None:
53
+ return self.mark.absence
54
+
55
+
56
+ @dataclass
57
+ class Lesson:
58
+ number: int
59
+ subject: str
60
+ homework: str | None
61
+ content: str | None
62
+ marks: list[Mark]
63
+ attachments: list[Attachment]
64
+ is_checked: bool
65
+ is_required_to_submit: bool
66
+ raw: dict[str, Any] = field(repr=False)
67
+
68
+ @property
69
+ def has_homework(self) -> bool:
70
+ """Include attachment-only assignments, but exclude empty text."""
71
+ return bool((self.homework or '').strip() or self.attachments)
72
+
73
+ @classmethod
74
+ def from_dict(cls, data: dict) -> "Lesson":
75
+ return cls(
76
+ number=data['number'], subject=data['subject'],
77
+ homework=data.get('homework'), content=data.get('lessonContent'),
78
+ marks=[Mark.from_dict(item) for item in data.get('marks', [])],
79
+ attachments=[Attachment.from_dict(item) for item in data.get('homeworkAttachments', [])],
80
+ is_checked=data.get('isChecked', False),
81
+ is_required_to_submit=data.get('isRequiredToSubmit', False), raw=data,
82
+ )
83
+
84
+
85
+ @dataclass
86
+ class DiaryDay:
87
+ date: date
88
+ lessons: list[Lesson]
89
+ is_day_off: bool
90
+ raw: dict[str, Any] = field(repr=False)
91
+
92
+ @property
93
+ def homework(self) -> list[Lesson]:
94
+ """Lessons containing homework text or attachments, without another request."""
95
+ return self.get_homework()
96
+
97
+ @property
98
+ def marks(self) -> list[MarkRecord]:
99
+ """Flatten mark records while preserving their subject and date."""
100
+ return [
101
+ MarkRecord(
102
+ date.fromisoformat(mark.raw['day'].split('T', 1)[0]) if mark.raw.get('day') else self.date,
103
+ lesson.subject, lesson.number, mark,
104
+ )
105
+ for lesson in self.lessons for mark in lesson.marks
106
+ ]
107
+
108
+ @classmethod
109
+ def from_dict(cls, data: dict) -> "DiaryDay":
110
+ return cls(
111
+ date=date.fromisoformat(data['date'].split('T', 1)[0]),
112
+ lessons=[Lesson.from_dict(item) for item in data.get('subjects', [])],
113
+ is_day_off=data.get('isDayOff', False), raw=data,
114
+ )
115
+
116
+ def get_lessons(self, subject: str | None = None) -> list[Lesson]:
117
+ """Filter by exact subject name, ignoring case and outer whitespace."""
118
+ if subject is None:
119
+ return list(self.lessons)
120
+ return [lesson for lesson in self.lessons if lesson.subject.strip().casefold() == subject.strip().casefold()]
121
+
122
+ def get_homework(self, subject: str | None = None) -> list[Lesson]:
123
+ """Return lessons with homework, retaining subject and attachment context."""
124
+ return [lesson for lesson in self.get_lessons(subject) if lesson.has_homework]
125
+
126
+ def get_marks(self, subject: str | None = None) -> list[Lesson]:
127
+ """Return lessons with mark records, including attendance-only records."""
128
+ return [lesson for lesson in self.get_lessons(subject) if lesson.marks]