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/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ from .client import NITClient, NITError
2
+ from .auth import AuthResult, LoginError, auto_auth, load_auth, login, save_auth
3
+ from .models import Attachment, DiaryDay, Lesson, Mark, MarkRecord
4
+ from .my_class import ClassReference, MyClass, Student, Teacher
5
+ from .user import UserProfile, UserRelation, UserSchool
6
+ from .errors import (
7
+ AccessDeniedError, AuthenticationError, InvalidResponseError, NetworkError,
8
+ NotFoundError, RateLimitError, ServerError,
9
+ )
10
+
11
+ __all__ = ["NITClient", "NITError", "AuthResult", "LoginError", "login", "auto_auth", "load_auth", "save_auth",
12
+ "Attachment", "DiaryDay", "Lesson", "Mark", "MarkRecord", "ClassReference", "MyClass", "Teacher", "Student",
13
+ "UserProfile", "UserRelation", "UserSchool", "AuthenticationError", "AccessDeniedError",
14
+ "NotFoundError", "RateLimitError", "ServerError", "NetworkError", "InvalidResponseError"]
nit_tools/auth.py ADDED
@@ -0,0 +1,385 @@
1
+ """Browser login and capture of the active NIT diary identity."""
2
+
3
+ from dataclasses import dataclass, field
4
+ import platform
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Callable
10
+ import logging
11
+ import shlex
12
+ import sys
13
+ from time import monotonic
14
+ import requests
15
+
16
+ from playwright.sync_api import sync_playwright, Error as PlaywrightError
17
+ from .errors import AuthenticationError
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class AuthResult:
25
+ token: str = field(repr=False)
26
+ school_id: str
27
+ user_id: str
28
+ headers: dict[str, str] = field(default_factory=dict, repr=False)
29
+ cookies: list[dict] = field(default_factory=list, repr=False)
30
+ local_storage: dict[str, str] = field(default_factory=dict, repr=False)
31
+ class_id: str | None = None
32
+
33
+
34
+ class LoginError(AuthenticationError):
35
+ """Login did not produce an authenticated request with a school identity."""
36
+
37
+ def __init__(self, message: str):
38
+ super().__init__(message=message)
39
+
40
+
41
+ def _storage_contains_token(value: str, token: str) -> bool:
42
+ """Find the confirmed API token in plain or JSON-encoded storage values."""
43
+ if value == token or value == f"Bearer {token}":
44
+ return True
45
+ try:
46
+ data = json.loads(value)
47
+ except (ValueError, TypeError):
48
+ return False
49
+
50
+ def contains(item) -> bool:
51
+ if isinstance(item, str):
52
+ return item == token or item == f"Bearer {token}"
53
+ if isinstance(item, dict):
54
+ return any(contains(child) for child in item.values())
55
+ if isinstance(item, list):
56
+ return any(contains(child) for child in item)
57
+ return False
58
+
59
+ return contains(data)
60
+
61
+
62
+ def _capture_local_storage(context, token: str) -> dict[str, str]:
63
+ """Keep storage entries containing the access token confirmed by the API."""
64
+ state = context.storage_state()
65
+ storage = {}
66
+ for origin in state.get('origins', []):
67
+ if origin.get('origin') != 'https://app.nit.school':
68
+ continue
69
+ for item in origin.get('localStorage', []):
70
+ if _storage_contains_token(item['value'], token):
71
+ storage[item['name']] = item['value']
72
+ return storage
73
+
74
+
75
+ def _profile_classes(payload) -> dict[tuple[str, str], set[str]]:
76
+ """Read class IDs only from user records and their school memberships.
77
+
78
+ teacherClasses is deliberately ignored: it describes other classes and
79
+ cannot establish the student's own class.
80
+ """
81
+ found: dict[tuple[str, str], set[str]] = {}
82
+
83
+ def visit(value):
84
+ if isinstance(value, dict):
85
+ user_id = value.get('id')
86
+ schools = value.get('subjects')
87
+ if isinstance(user_id, str) and isinstance(schools, list):
88
+ for school in schools:
89
+ if not isinstance(school, dict) or school.get('schoolId') is None:
90
+ continue
91
+ student_class = school.get('class')
92
+ class_id = student_class.get('id') if isinstance(student_class, dict) else school.get('studentClassId')
93
+ if isinstance(class_id, str) and class_id.strip():
94
+ found.setdefault((str(school['schoolId']), user_id), set()).add(class_id)
95
+ for child in value.values():
96
+ visit(child)
97
+ elif isinstance(value, list):
98
+ for child in value:
99
+ visit(child)
100
+
101
+ visit(payload)
102
+ return found
103
+
104
+
105
+ def login(
106
+ email: str,
107
+ password: str,
108
+ *,
109
+ headless: bool = True,
110
+ timeout: float = 120,
111
+ action_delay: float = 0.5,
112
+ user_agent: str | None = None,
113
+ locale: str = "uk-UA",
114
+ timezone_id: str = "Europe/Kyiv",
115
+ viewport: tuple[int, int] = (1366, 768),
116
+ email_selector: str = 'input[placeholder="youremail@gmail.com"]',
117
+ password_selector: str = 'input[type="password"]',
118
+ submit_selector: str | None = None,
119
+ ) -> AuthResult:
120
+ """Sign in using a fresh browser and return the active school/user IDs.
121
+
122
+ Selectors are configurable until the live login form has been verified.
123
+ A school must be selected in the UI if the account has no default school.
124
+ With headless=False the user can complete additional interactive steps.
125
+ No credentials, browser profile or token are written to disk.
126
+ Browser settings are configurable and do not bypass automation detection.
127
+ """
128
+ if not email or not password or timeout <= 0:
129
+ raise ValueError("Provide email, password and a positive timeout")
130
+ if action_delay < 0:
131
+ raise ValueError("action_delay must be non-negative")
132
+ if len(viewport) != 2 or any(size <= 0 for size in viewport):
133
+ raise ValueError("viewport must contain a positive width and height")
134
+ result = None
135
+ detected_classes: dict[tuple[str, str], set[str]] = {}
136
+
137
+ def capture(response):
138
+ nonlocal result
139
+ url = requests.utils.urlparse(response.url)
140
+ if url.hostname in {"api.nit.school", "is.nit.school", "app.nit.school"} and response.status >= 400:
141
+ # Exclude query strings and response bodies, which may contain secrets.
142
+ logger.warning("Browser received HTTP %s from %s%s", response.status, url.hostname, url.path)
143
+ if url.hostname != "api.nit.school" or not 200 <= response.status < 300:
144
+ return
145
+ if 'json' in response.headers.get('content-type', '').lower():
146
+ try:
147
+ for identity, ids in _profile_classes(response.json()).items():
148
+ detected_classes.setdefault(identity, set()).update(ids)
149
+ except (ValueError, PlaywrightError):
150
+ logger.debug("Could not inspect API response for student class metadata")
151
+ if url.path.rstrip("/") != "/api/v1/dashboard/diary":
152
+ return
153
+ headers = response.request.all_headers()
154
+ authorization = headers.get("authorization", "")
155
+ school = headers.get("x-nit-requested-school-id")
156
+ user = headers.get("x-nit-requested-user-id")
157
+ if authorization.lower().startswith("bearer ") and school and user:
158
+ if result is None:
159
+ logger.info("Diary access confirmed in browser; token, school and user IDs captured")
160
+ # Carry application metadata into requests without copying cookies.
161
+ metadata = {
162
+ key: value for key, value in headers.items()
163
+ if key in {"user-agent", "x-nit-client-version", "x-nit-client", "x-nit-locale"}
164
+ }
165
+ result = AuthResult(authorization[7:], school, user, metadata)
166
+
167
+ try:
168
+ with sync_playwright() as playwright:
169
+ logger.info("Launching Chromium (headless=%s)", headless)
170
+ try:
171
+ browser = playwright.chromium.launch(headless=headless)
172
+ except PlaywrightError as exc:
173
+ if "Executable doesn't exist" in str(exc):
174
+ command = f"{shlex.quote(sys.executable)} -m playwright install chromium"
175
+ logger.error("Chromium is not installed. Run: %s", command)
176
+ raise LoginError(f"Chromium is not installed. Run: {command}") from None
177
+ logger.error("Chromium could not start")
178
+ raise LoginError("Chromium could not start; check the browser installation and desktop environment") from None
179
+ try:
180
+ # Match the User-Agent version to the browser actually launched.
181
+ browser_platform = {
182
+ "Darwin": "Macintosh; Intel Mac OS X 10_15_7",
183
+ "Windows": "Windows NT 10.0; Win64; x64",
184
+ }.get(platform.system(), "X11; Linux x86_64")
185
+ default_user_agent = (
186
+ f"Mozilla/5.0 ({browser_platform}) AppleWebKit/537.36 "
187
+ f"(KHTML, like Gecko) Chrome/{browser.version} Safari/537.36"
188
+ )
189
+ logger.info("Creating browser context (locale=%s, timezone=%s)", locale, timezone_id)
190
+ context = browser.new_context(
191
+ user_agent=user_agent or default_user_agent,
192
+ locale=locale,
193
+ timezone_id=timezone_id,
194
+ viewport={"width": viewport[0], "height": viewport[1]},
195
+ color_scheme="light",
196
+ )
197
+ context.on("response", capture)
198
+ page = context.new_page()
199
+ deadline = monotonic() + timeout
200
+
201
+ def remaining():
202
+ seconds = deadline - monotonic()
203
+ if seconds <= 0:
204
+ raise LoginError("Timed out waiting for a successful diary request. Open the diary in the browser after login and select the intended student/school.")
205
+ return seconds * 1000
206
+
207
+ logger.info("Opening NIT login page")
208
+ page.goto("https://app.nit.school/login", timeout=remaining())
209
+ logger.info("Waiting for email field and entering email")
210
+ page.locator(email_selector).first.fill(email, timeout=remaining())
211
+ logger.info("Pausing for %.2f seconds", action_delay)
212
+ page.wait_for_timeout(min(action_delay * 1000, remaining()))
213
+ logger.info("Entering password")
214
+ page.locator(password_selector).first.fill(password, timeout=remaining())
215
+ logger.info("Pausing for %.2f seconds before submitting", action_delay)
216
+ page.wait_for_timeout(min(action_delay * 1000, remaining()))
217
+ logger.info("Submitting login form")
218
+ submit = (
219
+ page.locator(submit_selector).first
220
+ if submit_selector is not None
221
+ else page.get_by_role("button", name="Увійти", exact=True)
222
+ )
223
+ submit.click(timeout=remaining())
224
+ logger.info("Waiting for a successful diary request; open the diary in the browser if it does not open automatically")
225
+ while result is None:
226
+ page.wait_for_timeout(min(200, remaining()))
227
+ # Give profile requests that finish after the diary a short grace period.
228
+ class_deadline = min(deadline, monotonic() + 2)
229
+ identity = (str(result.school_id), result.user_id)
230
+ while not detected_classes.get(identity) and monotonic() < class_deadline:
231
+ page.wait_for_timeout(min(100, max(0, (class_deadline - monotonic()) * 1000)))
232
+ for origin in context.storage_state().get('origins', []):
233
+ if origin.get('origin') != 'https://app.nit.school':
234
+ continue
235
+ for item in origin.get('localStorage', []):
236
+ try:
237
+ metadata = json.loads(item['value'])
238
+ except (ValueError, TypeError):
239
+ continue
240
+ for key, ids in _profile_classes(metadata).items():
241
+ detected_classes.setdefault(key, set()).update(ids)
242
+ candidates = detected_classes.get(identity, set())
243
+ if not candidates:
244
+ logger.info("Requesting the authenticated user's profile to determine class ID")
245
+ try:
246
+ profile_response = context.request.get(
247
+ 'https://api.nit.school/api/v1/users/' + requests.utils.quote(result.user_id, safe=''),
248
+ headers={
249
+ **result.headers,
250
+ 'Authorization': f'Bearer {result.token}',
251
+ 'X-NIT-REQUESTED-SCHOOL-ID': result.school_id,
252
+ 'X-NIT-REQUESTED-USER-ID': result.user_id,
253
+ 'Alias': 'users',
254
+ 'Accept': 'application/json',
255
+ 'Referer': 'https://app.nit.school/',
256
+ },
257
+ timeout=remaining(),
258
+ )
259
+ try:
260
+ if profile_response.ok:
261
+ candidates = _profile_classes(profile_response.json()).get(identity, set())
262
+ else:
263
+ logger.warning("Class discovery profile request returned HTTP %s", profile_response.status)
264
+ finally:
265
+ profile_response.dispose()
266
+ except (ValueError, PlaywrightError):
267
+ logger.warning("Could not read class metadata from the authenticated profile")
268
+ class_id = next(iter(candidates)) if len(candidates) == 1 else None
269
+ if class_id:
270
+ logger.info("Student class ID detected for the selected user and school")
271
+ else:
272
+ logger.warning("Student class ID unavailable or ambiguous; pass class_id explicitly for my_class")
273
+ cookies = context.cookies("https://api.nit.school/")
274
+ local_storage = _capture_local_storage(context, result.token)
275
+ if local_storage:
276
+ logger.info("Access token found in localStorage; captured %s authentication entries", len(local_storage))
277
+ else:
278
+ logger.info("No matching access token in localStorage; using the confirmed API request token")
279
+ logger.info("Login completed; captured %s API session cookies", len(cookies))
280
+ return AuthResult(result.token, result.school_id, result.user_id, result.headers, cookies, local_storage, class_id)
281
+ finally:
282
+ logger.info("Closing browser")
283
+ browser.close()
284
+ except LoginError:
285
+ raise
286
+ except PlaywrightError:
287
+ logger.error("Browser login failed")
288
+ # Playwright errors may contain filled values or request details.
289
+ raise LoginError("NIT browser login failed; check credentials, selectors and browser installation") from None
290
+
291
+
292
+ def load_auth(path: Path) -> AuthResult | None:
293
+ """Read saved credentials without logging their values."""
294
+ path = Path(path)
295
+ if not path.exists():
296
+ return None
297
+ try:
298
+ data = json.loads(path.read_text(encoding="utf-8"))
299
+ values = [data[key] for key in ("token", "school_id", "user_id")]
300
+ if not all(isinstance(value, str) and value.strip() for value in values):
301
+ raise ValueError("Invalid credential fields")
302
+ headers = data.get("headers", {})
303
+ if not isinstance(headers, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in headers.items()):
304
+ raise ValueError("Invalid saved headers")
305
+ cookies = data.get("cookies", [])
306
+ if not isinstance(cookies, list) or not all(
307
+ isinstance(cookie, dict) and all(isinstance(cookie.get(key), str) for key in ("name", "value", "domain"))
308
+ and isinstance(cookie.get("expires", -1), (int, float))
309
+ for cookie in cookies
310
+ ):
311
+ raise ValueError("Invalid saved cookies")
312
+ logger.info("Loaded saved authentication data")
313
+ local_storage = data.get("local_storage", {})
314
+ if not isinstance(local_storage, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in local_storage.items()):
315
+ raise ValueError("Invalid saved localStorage")
316
+ class_id = data.get('class_id')
317
+ if class_id is not None and (not isinstance(class_id, str) or not class_id.strip()):
318
+ raise ValueError("Invalid saved class_id")
319
+ return AuthResult(*values, headers=headers, cookies=cookies, local_storage=local_storage, class_id=class_id)
320
+ except (ValueError, KeyError, TypeError):
321
+ logger.warning("Saved authentication file is invalid; login is required")
322
+ return None
323
+
324
+
325
+ def save_auth(path: Path, auth: AuthResult) -> None:
326
+ """Atomically save the token and IDs in an owner-only file."""
327
+ path = Path(path)
328
+ path.parent.mkdir(parents=True, exist_ok=True)
329
+ temporary = None
330
+ try:
331
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as handle:
332
+ temporary = Path(handle.name)
333
+ os.chmod(temporary, 0o600)
334
+ json.dump({"token": auth.token, "school_id": auth.school_id, "user_id": auth.user_id, "headers": auth.headers, "cookies": auth.cookies, "local_storage": auth.local_storage, "class_id": auth.class_id}, handle, indent=2)
335
+ temporary.replace(path)
336
+ finally:
337
+ if temporary is not None:
338
+ temporary.unlink(missing_ok=True)
339
+ logger.info("Saved authentication data to %s", path)
340
+
341
+
342
+ def auto_auth(
343
+ email: str | None = None,
344
+ password: str | None = None,
345
+ *,
346
+ path: str | Path = ".nit-auth.json",
347
+ force: bool = False,
348
+ require_class_id: bool = False,
349
+ credential_provider: Callable[[], tuple[str, str]] | None = None,
350
+ **login_options,
351
+ ) -> AuthResult:
352
+ """Reuse saved authentication, or log in and save a new browser session.
353
+
354
+ Credentials are required only for a fresh login. Pass them directly, set
355
+ NIT_EMAIL/NIT_PASSWORD, or supply a lazy credential_provider. Login options
356
+ such as headless and action_delay are forwarded to login(). Set force=True
357
+ when used after an HTTP 401 to avoid reloading the rejected credentials.
358
+ Loading a file does not validate its token with the server.
359
+ """
360
+ path = Path(path)
361
+ if not force:
362
+ saved = load_auth(path)
363
+ if saved is not None:
364
+ if not require_class_id or saved.class_id is not None:
365
+ return saved
366
+ logger.info("Saved session has no class ID; refreshing authentication to capture student class metadata")
367
+ email = email or os.environ.get("NIT_EMAIL")
368
+ password = password or os.environ.get("NIT_PASSWORD")
369
+ if (not email or not password) and credential_provider is not None:
370
+ supplied_email, supplied_password = credential_provider()
371
+ email = email or supplied_email
372
+ password = password or supplied_password
373
+ if not email or not password:
374
+ raise ValueError("Login requires email and password: pass them to auto_auth(), set NIT_EMAIL/NIT_PASSWORD, or provide credential_provider")
375
+ logger.info("No reusable authentication or forced refresh; starting browser login")
376
+ result = login(email, password, **login_options)
377
+ save_auth(path, result)
378
+ if require_class_id and result.class_id is None:
379
+ raise LoginError(
380
+ "Login succeeded, but the student class was not found in profile responses. "
381
+ "The session was saved. Provide class_id explicitly or inspect the student's profile response structure."
382
+ )
383
+ return result
384
+
385
+