librus-python-api 1.9.0__py3-none-any.whl → 1.10.1__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.
@@ -1,7 +1,7 @@
1
1
  """Independent bounded async client. General live compatibility is unqualified."""
2
2
 
3
3
  # Before the imports: config reads it for the User-Agent.
4
- __version__ = "1.9.0"
4
+ __version__ = "1.10.1"
5
5
 
6
6
  from librus_python_api.attachments import AttachmentStream, ModernAttachmentStream
7
7
  from librus_python_api.budget import RequestBudget
@@ -38,6 +38,8 @@ from librus_python_api.models import (
38
38
  AttendanceView,
39
39
  AttendanceWindow,
40
40
  Availability,
41
+ BehaviourPointEntry,
42
+ BehaviourPoints,
41
43
  ClassFreeDay,
42
44
  ClassFreeDays,
43
45
  CompletedLesson,
@@ -64,6 +66,9 @@ from librus_python_api.models import (
64
66
  HomeworkItem,
65
67
  HomeworkRangeRequest,
66
68
  Identity,
69
+ Justification,
70
+ Justifications,
71
+ JustificationStatus,
67
72
  LuckyNumber,
68
73
  MessageAttachment,
69
74
  MessageAttachmentReference,
@@ -259,6 +264,8 @@ __all__ = [
259
264
  "DescriptiveGradeSummary",
260
265
  "FinalGrades",
261
266
  "FormativeGrade",
267
+ "BehaviourPointEntry",
268
+ "BehaviourPoints",
262
269
  "GradeCorrection",
263
270
  "GradeKind",
264
271
  "GradeRecords",
@@ -267,6 +274,9 @@ __all__ = [
267
274
  "GradeView",
268
275
  "GradeWindow",
269
276
  "Identity",
277
+ "Justification",
278
+ "Justifications",
279
+ "JustificationStatus",
270
280
  "LibrusService",
271
281
  "LuckyNumber",
272
282
  "NumericGrade",
@@ -503,6 +503,17 @@ ENDPOINTS: Mapping[str, Endpoint] = MappingProxyType(
503
503
  True,
504
504
  Evidence.INDEPENDENTLY_OBSERVED,
505
505
  ),
506
+ # The e-Justifications list as the page shows it unfiltered. Both
507
+ # parent logins got it, both student logins the "Brak dostępu"
508
+ # page (2026-11-13). The filter form's POST is not used.
509
+ Endpoint(
510
+ "justifications",
511
+ "GET",
512
+ "/eusprawiedliwienia",
513
+ SideEffect.NONE,
514
+ True,
515
+ Evidence.INDEPENDENTLY_OBSERVED,
516
+ ),
506
517
  Endpoint(
507
518
  "gateway_attendance",
508
519
  "GET",
@@ -749,11 +760,13 @@ TOOLTIP_LABELS = frozenset(
749
760
  "Maksymalna ilość punktów",
750
761
  "Nauczyciel",
751
762
  "Obowiązek wyk. zadania",
763
+ "Obszar oceniania",
752
764
  "Ocena",
753
765
  "Poprawa oceny",
754
766
  "Rodzaj",
755
767
  "Suma punktów",
756
768
  "Temat zajęć",
769
+ "Umiejętność",
757
770
  "Waga",
758
771
  "Zakres do",
759
772
  "Zakres od",
@@ -796,12 +809,29 @@ GRADE_PERIOD_HEADERS = MappingProxyType(
796
809
  "Ocena roczna": 0,
797
810
  }
798
811
  )
799
- # New-schema descriptive grading: the page renders this table either with empty
812
+ # New-schema descriptive grading: the page renders this table with empty
800
813
  # `gradesCell` semester cells, which its script fills from the gateway routes
801
- # above, or with bare semester text, which needs no gateway read.
814
+ # above, with bare semester text, or with grade boxes and filled detail rows;
815
+ # the last two need no gateway read.
802
816
  DESCRIPTIVE_TABLE_CLASS = "newSchemaGradesByStudentTable"
803
817
  DESCRIPTIVE_ROW_CLASS = "studentRow"
804
818
  DESCRIPTIVE_DETAILS_ROW_CLASS = "studentGradesDetailsRow"
819
+ DESCRIPTIVE_DETAILS_CELL_CLASS = "studentGradesDetailsCell"
820
+ # A filled detail row's table (2026-11-15, reported page, #173): these column
821
+ # labels, then per period a heading row with one `DESCRIPTIVE_PERIOD_LABELS` cell and
822
+ # either `detail-grades` rows or one empty-marker row.
823
+ DESCRIPTIVE_DETAIL_COLUMNS = (
824
+ "Ocena",
825
+ "K",
826
+ "Obszar oceniania",
827
+ "Umiejętność",
828
+ "Data",
829
+ "Nauczyciel",
830
+ "Treść oceny",
831
+ "Dodał",
832
+ )
833
+ DESCRIPTIVE_DETAIL_GRADE_ROW_CLASS = "detail-grades"
834
+ DESCRIPTIVE_PERIOD_LABELS = MappingProxyType({"Okres 1": 1, "Okres 2": 2})
805
835
  # Gateway account and student identifiers are opaque strings, unlike every
806
836
  # other `{id}` route, which takes a numeric ID.
807
837
  DESCRIPTIVE_IDENTIFIER = re.compile(r"[A-Za-z0-9_-]{1,128}")
@@ -877,6 +907,11 @@ FORMATIVE_DETAIL_PATH_PREFIX = "/przegladaj_oceny/szczegoly/ksztaltujace/"
877
907
  BEHAVIOUR_POINTS_DETAIL_PATH_PREFIX = "/przegladaj_oceny/zachowanie_szczegoly/"
878
908
  # Tooltip labels of a behaviour grade symbol entry (#114, synthetic example).
879
909
  BEHAVIOUR_GRADE_LABELS = frozenset({"Data wystawienia", "Dodał", "Komentarz"})
910
+ # Tooltip labels after a behaviour-point entry's unlabelled first line, as the
911
+ # 1.6.2 synthetic entry has them; any other label fails the read (#138).
912
+ BEHAVIOUR_POINT_LABELS = frozenset(
913
+ {"Zakres od", "Zakres do", "Data wystawienia", "Dodał", "Komentarz"}
914
+ )
880
915
  # Recognition only: point-grade detail links are classified, never requested.
881
916
  POINT_GRADE_DETAIL_PATH_PREFIX = "/przegladaj_oceny_punktowe/szczegoly/"
882
917
  # Recognition only: an ordinary grade's own detail link gives its stable grade
@@ -1034,6 +1069,35 @@ PAGE_NOTICES = MappingProxyType(
1034
1069
  )
1035
1070
  MODULE_UNAVAILABLE_PATH = "/modul_niedostepny"
1036
1071
  CLASS_FREE_DAYS_MAX_RECORDS = 4096
1072
+ # e-Justifications list (`/eusprawiedliwienia`, structure observed on two
1073
+ # parent logins on 2026-11-13). The list table's classes, its seven header
1074
+ # cells in page order (`td`, not `th`, in `thead`) and the status words. The
1075
+ # status words are the filter's options; `odrzucone` has not been seen on an
1076
+ # entry. A decided entry adds " (" + the deciding person's name + ")".
1077
+ JUSTIFICATION_TABLE_CLASSES = frozenset({"decorated", "stretch", "center"})
1078
+ JUSTIFICATION_HEADERS = (
1079
+ "Załącznik",
1080
+ "Okres usprawiedliwienia",
1081
+ "Liczba usprawiedliwionych nieobecności",
1082
+ "Treść",
1083
+ "Powiadomieni nauczyciele",
1084
+ "Data wysłania",
1085
+ "Status",
1086
+ )
1087
+ JUSTIFICATION_STATUSES = MappingProxyType(
1088
+ {"wysłane": "sent", "usprawiedliwione": "justified", "odrzucone": "rejected"}
1089
+ )
1090
+ # `Me.Account.GroupId` of the logins that may request the list: 5 on both
1091
+ # parent logins, 8 on both student logins (one school, 2026-11-13). Opening
1092
+ # the list on a student login ends its session, so any other or missing group
1093
+ # is refused before the request.
1094
+ JUSTIFICATION_ACCOUNT_GROUP = 5
1095
+ # The filter form's date inputs, filled with the window the list shows.
1096
+ JUSTIFICATION_WINDOW_FIELDS = ("data_od", "data_do")
1097
+ JUSTIFICATION_MAX_ITEMS = 512
1098
+ JUSTIFICATION_MAX_CONTENT_LENGTH = 8192
1099
+ JUSTIFICATION_MAX_TEACHERS = 64
1100
+ JUSTIFICATION_MAX_TOTAL_TEXT_LENGTH = 262144
1037
1101
  COMPLETED_LESSONS_MAX_WINDOW_DAYS = 371
1038
1102
  COMPLETED_LESSONS_MAX_PAGE_COUNT = 1000
1039
1103
  COMPLETED_LESSONS_MAX_PAGE_ITEMS = 256
@@ -255,6 +255,7 @@ def _redaction_vocabulary() -> tuple[
255
255
  *config.GRADE_PERIOD_HEADERS,
256
256
  *config.GRADE_PREDICTED_PERIOD_HEADERS,
257
257
  *config.GRADE_AVERAGE_HEADERS,
258
+ *config.JUSTIFICATION_HEADERS,
258
259
  }
259
260
  texts |= {label.casefold() for label in config.FORMATIVE_HEADERS}
260
261
  profile = (*config.PROFILE_LABELS, *config.PROFILE_OWNER_LABELS)
@@ -4,13 +4,16 @@ The grades page of a school on the new descriptive grading schema renders a
4
4
  subject table whose semester cells are empty; the page script then loads the
5
5
  grades from gateway JSON routes. Routes and field names come from public client
6
6
  code and the official page script. One authorized read on 2026-10-28 parsed four
7
- PartialGrades records on one school; pagination keys are still unknown, so every
8
- unexpected shape fails instead of producing a partial collection.
7
+ PartialGrades records on one school. A structure-only read on 2026-11-13 recorded
8
+ the pagination member, `{"limit", "page", "total"}` integers beside `data` or
9
+ `Users` (Subjects has none), and only that member is checked; every unexpected
10
+ shape fails instead of producing a partial collection.
9
11
 
10
12
  Another school renders the same table with plain text in its semester cells and
11
- no script hooks (#115, from a reporter's synthetic example). The grade record
12
- parser reads those cells like any descriptive row, so that table needs no
13
- gateway read.
13
+ no script hooks (#115, from a reporter's synthetic example), and another with
14
+ grade boxes in them and filled detail rows that list the same grades (#173,
15
+ from a reporter's sanitized page). The grade record parser reads those cells
16
+ like any descriptive row, so neither table needs a gateway read.
14
17
  """
15
18
 
16
19
  import re
@@ -25,13 +28,18 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_valida
25
28
 
26
29
  from librus_python_api import markup
27
30
  from librus_python_api.config import (
31
+ DESCRIPTIVE_DETAIL_COLUMNS,
32
+ DESCRIPTIVE_DETAIL_GRADE_ROW_CLASS,
33
+ DESCRIPTIVE_DETAILS_CELL_CLASS,
28
34
  DESCRIPTIVE_DETAILS_ROW_CLASS,
29
35
  DESCRIPTIVE_IDENTIFIER,
30
36
  DESCRIPTIVE_MAX_NAME_LENGTH,
31
37
  DESCRIPTIVE_MAX_SUBJECTS,
32
38
  DESCRIPTIVE_MAX_USERS,
39
+ DESCRIPTIVE_PERIOD_LABELS,
33
40
  DESCRIPTIVE_ROW_CLASS,
34
41
  DESCRIPTIVE_TABLE_CLASS,
42
+ GRADE_EMPTY_MARKERS,
35
43
  GRADE_MAX_METADATA_LENGTH,
36
44
  GRADE_MAX_RECORDS,
37
45
  GRADE_MAX_SUBJECTS,
@@ -55,29 +63,6 @@ _DATE = re.compile(
55
63
  r"(?:[T ][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]{1,9})?)?"
56
64
  r"(?:Z|[+-][0-9]{2}:?[0-9]{2})?)?"
57
65
  )
58
- # Keys (lower case, without separators) that, in any object beside `data`,
59
- # show that the collection continues on another page.
60
- _TOTAL_KEYS = frozenset(
61
- {
62
- "total",
63
- "totalcount",
64
- "totalitems",
65
- "totalrecords",
66
- "totalresults",
67
- "count",
68
- "itemcount",
69
- "itemscount",
70
- "recordcount",
71
- }
72
- )
73
- _PAGE_COUNT_KEYS = frozenset(
74
- {"pages", "totalpages", "pagecount", "pagescount", "lastpage", "numberofpages"}
75
- )
76
- _NEXT_KEYS = frozenset({"next", "nextpage", "nexturl", "nextpageurl", "nextlink"})
77
- _MORE_KEYS = frozenset({"hasmore", "hasnext", "hasnextpage", "more"})
78
- _PAGE_SIZE_KEYS = frozenset(
79
- {"limit", "perpage", "pagesize", "itemsperpage", "pagelimit"}
80
- )
81
66
 
82
67
 
83
68
  class _TokenInfoWire(BaseModel):
@@ -199,52 +184,33 @@ def _decode_collection(body: bytes, key: str, maximum: int) -> dict[str, Any]:
199
184
  return data
200
185
 
201
186
 
202
- def _count(value: Any) -> int | None:
203
- if type(value) is int:
204
- return value
205
- if type(value) is str and re.fullmatch(r"[0-9]{1,18}", value):
206
- return int(value)
207
- return None
208
-
209
-
210
- def _continues(envelope: dict[str, Any], received: int) -> bool:
211
- """Whether a pagination member shows more items than this response holds.
187
+ def _check_pagination(
188
+ envelope: dict[str, Any], received: int, *, required: bool
189
+ ) -> None:
190
+ """Read the recorded `pagination` member; anything else decides nothing.
212
191
 
213
- No paginated response was observed, so its field names are unknown. Every
214
- object beside `data`, to depth three, is checked for obvious signals: a
215
- total above the items received, more than one page, a next link or page,
216
- a true has-more flag, or a full page of a stated size with no total.
192
+ Observed 2026-11-13: `{"limit": int, "page": int, "total": int}` beside
193
+ `data` (PartialGrades) or `Users`. Subjects carries no member. Only the
194
+ first page is ever read, so the member must show page 1 and a total equal
195
+ to the items received (the limit is not a fixed page size and is only
196
+ checked to be an integer). Anything else fails instead of returning a
197
+ possibly partial collection.
217
198
  """
218
- totals: list[int] = []
219
- sizes: list[int] = []
220
- more = False
221
- pending: list[tuple[dict[str, Any], int]] = [
222
- ({k: v for k, v in envelope.items() if k != "data"}, 0)
223
- ]
224
- while pending:
225
- item, depth = pending.pop()
226
- for key, value in item.items():
227
- name = re.sub(r"[^a-z]", "", str(key).lower())
228
- if name in _NEXT_KEYS:
229
- more = more or value not in (None, "", False, {}, [])
230
- continue
231
- if isinstance(value, dict):
232
- if depth < 3:
233
- pending.append((value, depth + 1))
234
- continue
235
- number = _count(value)
236
- if name in _TOTAL_KEYS and number is not None:
237
- totals.append(number)
238
- elif name in _PAGE_COUNT_KEYS and number is not None:
239
- more = more or number > 1
240
- elif name in _MORE_KEYS:
241
- more = more or value is True
242
- elif name in _PAGE_SIZE_KEYS and number is not None:
243
- sizes.append(number)
244
- if any(total > received for total in totals):
245
- return True
246
- full_page = any(0 < size <= received for size in sizes)
247
- return more or (full_page and not totals)
199
+ if "pagination" not in envelope:
200
+ if required:
201
+ raise LibrusError(ErrorKind.PARSE)
202
+ return
203
+ member = envelope["pagination"]
204
+ if not isinstance(member, dict):
205
+ raise LibrusError(ErrorKind.PARSE)
206
+ limit, page, total = member.get("limit"), member.get("page"), member.get("total")
207
+ # `type(...) is int` rejects booleans, strings and floats.
208
+ if type(limit) is not int or type(page) is not int or type(total) is not int:
209
+ raise LibrusError(ErrorKind.PARSE)
210
+ if limit < 1 or total < received:
211
+ raise LibrusError(ErrorKind.PARSE)
212
+ if page != 1 or total > received:
213
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
248
214
 
249
215
 
250
216
  def parse_token_info(body: bytes) -> str:
@@ -281,9 +247,8 @@ def _day(value: str) -> date:
281
247
  def parse_partial_grades(body: bytes) -> tuple[PartialGrade, ...]:
282
248
  data = _decode_collection(body, "data", GRADE_MAX_RECORDS)
283
249
  wire = _validate(_PartialGradesWire, data)
284
- if _continues(data, len(wire.data)):
285
- # Returning the first page alone would be a silently partial result.
286
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
250
+ # Returning the first page alone would be a silently partial result.
251
+ _check_pagination(data, len(wire.data), required=True)
287
252
  return tuple(
288
253
  PartialGrade(
289
254
  item.subjectId,
@@ -303,8 +268,7 @@ def parse_partial_grades(body: bytes) -> tuple[PartialGrade, ...]:
303
268
  def parse_gateway_subjects(body: bytes) -> Mapping[str, GatewaySubject]:
304
269
  data = _decode_collection(body, "data", DESCRIPTIVE_MAX_SUBJECTS)
305
270
  wire = _validate(_SubjectsWire, data)
306
- if _continues(data, len(wire.data)):
307
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
271
+ _check_pagination(data, len(wire.data), required=False)
308
272
  result: dict[str, GatewaySubject] = {}
309
273
  numeric: set[int] = set()
310
274
  for item in wire.data:
@@ -323,6 +287,7 @@ def parse_gateway_users(body: bytes) -> Mapping[str, str]:
323
287
  """Account IDs to "LastName FirstName"; a user with neither is omitted."""
324
288
  data = _decode_collection(body, "Users", DESCRIPTIVE_MAX_USERS)
325
289
  wire = _validate(_UsersWire, data)
290
+ _check_pagination(data, len(wire.Users), required=False)
326
291
  result: dict[str, str] = {}
327
292
  seen: dict[str, tuple[str | None, str | None]] = {}
328
293
  for user in wire.Users:
@@ -350,14 +315,118 @@ def _classes(element: html.HtmlElement) -> set[str]:
350
315
  return set(element.get("class", "").split())
351
316
 
352
317
 
318
+ _Grades = list[tuple[str, date]]
319
+
320
+
321
+ def _box_grades(cell: html.HtmlElement) -> _Grades | None:
322
+ """Value and date of each grade box in a semester cell of the box layout.
323
+
324
+ The cell has no attributes and holds either only grade boxes, each one
325
+ link with no markup, or a bare empty marker (no grades). Anything else is
326
+ None. The record parser reads and validates the same boxes.
327
+ """
328
+ if cell.attrib:
329
+ return None
330
+ elements = [node for node in cell if isinstance(node.tag, str)]
331
+ if not elements:
332
+ value = markup.text(cell)
333
+ return [] if value and value in GRADE_EMPTY_MARKERS else None
334
+ if (cell.text or "").strip() or any((node.tail or "").strip() for node in cell):
335
+ return None
336
+ result: _Grades = []
337
+ for box in elements:
338
+ links = [node for node in box if isinstance(node.tag, str)]
339
+ if (
340
+ box.tag != "span"
341
+ or "grade-box" not in _classes(box)
342
+ or (box.text or "").strip()
343
+ or len(links) != 1
344
+ or links[0].tag != "a"
345
+ or len(links[0])
346
+ or (links[0].tail or "").strip()
347
+ ):
348
+ return None
349
+ fields = markup.tooltip_fields(links[0])
350
+ result.append((markup.text(links[0]), markup.civil_date(fields.get("Data"))))
351
+ return result
352
+
353
+
354
+ def _detail_grades(cell: html.HtmlElement) -> dict[int, _Grades]:
355
+ """Value and date of each grade in a filled detail row, by period.
356
+
357
+ The cell holds one table: `DESCRIPTIVE_DETAIL_COLUMNS` as its header, then
358
+ per period a heading row and either grade rows or one empty-marker row,
359
+ and an empty footer. A grade row with `Treść oceny` text fails: the grade
360
+ boxes carry no such field, so the text would be lost.
361
+ """
362
+ unsupported = LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
363
+ tables = [node for node in cell if isinstance(node.tag, str)]
364
+ if (
365
+ len(tables) != 1
366
+ or tables[0].tag != "table"
367
+ or (cell.text or "").strip()
368
+ or (tables[0].tail or "").strip()
369
+ ):
370
+ raise unsupported
371
+ result: dict[int, _Grades] = {}
372
+ empty: set[int] = set()
373
+ header = False
374
+ period: int | None = None
375
+ for row in markup.rows(tables[0]):
376
+ cells = markup.cells(row)
377
+ texts = [markup.text(item) for item in cells]
378
+ if markup.in_header(row):
379
+ if header or texts != list(DESCRIPTIVE_DETAIL_COLUMNS):
380
+ raise unsupported
381
+ header = True
382
+ elif next(row.iterancestors("tfoot"), None) is not None:
383
+ if any(texts) or any(len(item) for item in cells):
384
+ raise unsupported
385
+ elif len(cells) == 1 and texts[0] in DESCRIPTIVE_PERIOD_LABELS:
386
+ period = DESCRIPTIVE_PERIOD_LABELS[texts[0]]
387
+ if period in result or len(cells[0]):
388
+ raise unsupported
389
+ result[period] = []
390
+ elif period is None or period in empty:
391
+ raise unsupported
392
+ elif len(cells) == 1:
393
+ if result[period] or texts[0] not in GRADE_EMPTY_MARKERS - {""}:
394
+ raise unsupported
395
+ if len(cells[0]):
396
+ raise unsupported
397
+ empty.add(period)
398
+ elif (
399
+ DESCRIPTIVE_DETAIL_GRADE_ROW_CLASS in _classes(row)
400
+ and len(cells) == len(DESCRIPTIVE_DETAIL_COLUMNS)
401
+ and texts[0]
402
+ and not texts[DESCRIPTIVE_DETAIL_COLUMNS.index("Treść oceny")]
403
+ ):
404
+ day = texts[DESCRIPTIVE_DETAIL_COLUMNS.index("Data")]
405
+ result[period].append((texts[0], markup.civil_date(day)))
406
+ else:
407
+ raise unsupported
408
+ if not header or sorted(result) != [1, 2]:
409
+ raise unsupported
410
+ if any(not result[key] and key not in empty for key in result):
411
+ raise unsupported
412
+ return result
413
+
414
+
353
415
  def read_descriptive_table(document: html.HtmlElement) -> DescriptiveTable | None:
354
416
  """The new-schema subject table, or None when the page has none.
355
417
 
356
- Its rows hold an expander, the subject and two semester cells. Either
357
- every row has empty `gradesCell` cells that the page script fills from
358
- the gateway, or every row has plain cells the page filled itself, which
359
- `read_grade_records` reads and validates. A script cell the page already
360
- filled would duplicate the gateway records, so it is unsupported.
418
+ Its rows hold an expander, the subject and two semester cells, in one of
419
+ three layouts that `read_grade_records` reads, with no gateway grades
420
+ except in the first:
421
+
422
+ - empty `gradesCell` cells that the page script fills from the gateway;
423
+ - bare text cells the page filled itself (#115), with no detail rows;
424
+ - grade boxes or a bare empty marker (2026-11-15, #173), with a filled
425
+ `studentGradesDetailsRow` for every subject row that lists the same
426
+ grades, value and date, in the same order.
427
+
428
+ A script cell the page already filled would duplicate the gateway records,
429
+ so it is unsupported, as is any other cell or a table mixing layouts.
361
430
  """
362
431
  tables = [
363
432
  table
@@ -379,6 +448,26 @@ def read_descriptive_table(document: html.HtmlElement) -> DescriptiveTable | Non
379
448
  if not populated:
380
449
  return None
381
450
  tables = populated
451
+ detail_rows = [
452
+ row
453
+ for row in markup.rows(tables[0])
454
+ if DESCRIPTIVE_DETAILS_ROW_CLASS in _classes(row)
455
+ ]
456
+ # Detail rows the page script fills from the gateway are empty; filled
457
+ # ones hold a table and belong to the box layout.
458
+ rendered = any(next(row.iter("table"), None) is not None for row in detail_rows)
459
+ details: dict[str, dict[int, _Grades]] = {}
460
+ if rendered:
461
+ for row in detail_rows:
462
+ cells = markup.cells(row)
463
+ if len(cells) != 1 or DESCRIPTIVE_DETAILS_CELL_CLASS not in _classes(
464
+ cells[0]
465
+ ):
466
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
467
+ key = row.get("data-subject_id", "")
468
+ if key in details:
469
+ raise LibrusError(ErrorKind.PARSE)
470
+ details[key] = _detail_grades(cells[0])
382
471
  subjects: dict[int, str] = {}
383
472
  students: set[str | None] = set()
384
473
  layouts: set[bool] = set()
@@ -391,26 +480,36 @@ def read_descriptive_table(document: html.HtmlElement) -> DescriptiveTable | Non
391
480
  ):
392
481
  raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
393
482
  semesters = cells[2:]
394
- # A filled cell is bare text: no attributes and no markup, so a renamed
395
- # or moved script hook never passes as a filled table.
396
- filled = all(
397
- not cell.attrib
398
- and markup.text(cell)
399
- and not any(isinstance(node.tag, str) for node in cell)
400
- for cell in semesters
401
- )
402
- if not filled and (
403
- [cell.get("data-semester") for cell in semesters] != ["1", "2"]
404
- or not all("gradesCell" in _classes(cell) for cell in semesters)
405
- ):
406
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
407
- layouts.add(filled)
408
- if not filled and any(
409
- markup.text(cell) or any(isinstance(node.tag, str) for node in cell)
410
- for cell in semesters
411
- ):
412
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
413
483
  identifier = row.get("data-subject_id", "")
484
+ if rendered:
485
+ boxes = [_box_grades(cell) for cell in semesters]
486
+ if boxes[0] is None or boxes[1] is None:
487
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
488
+ # The detail row must list exactly the grades the boxes show; any
489
+ # other grade there would be dropped.
490
+ if details.pop(identifier, None) != {1: boxes[0], 2: boxes[1]}:
491
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
492
+ filled = True
493
+ else:
494
+ # A filled cell is bare text: no attributes and no markup, so a
495
+ # renamed or moved script hook never passes as a filled table.
496
+ filled = all(
497
+ not cell.attrib
498
+ and markup.text(cell)
499
+ and not any(isinstance(node.tag, str) for node in cell)
500
+ for cell in semesters
501
+ )
502
+ if not filled and (
503
+ [cell.get("data-semester") for cell in semesters] != ["1", "2"]
504
+ or not all("gradesCell" in _classes(cell) for cell in semesters)
505
+ ):
506
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
507
+ if not filled and any(
508
+ markup.text(cell) or any(isinstance(node.tag, str) for node in cell)
509
+ for cell in semesters
510
+ ):
511
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
512
+ layouts.add(filled)
414
513
  name = markup.text(cells[1])
415
514
  if not re.fullmatch(r"[0-9]{1,18}", identifier) or not name:
416
515
  raise LibrusError(ErrorKind.PARSE)
@@ -423,13 +522,12 @@ def read_descriptive_table(document: html.HtmlElement) -> DescriptiveTable | Non
423
522
  if len(students) > 1:
424
523
  # One page shows one student; rows of several students are unknown.
425
524
  raise LibrusError(ErrorKind.PARSE)
426
- if len(layouts) > 1:
525
+ if len(layouts) > 1 or details:
526
+ # Mixed layouts, or a filled detail row without its subject row.
427
527
  raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
428
- if layouts == {True} and any(
429
- DESCRIPTIVE_DETAILS_ROW_CLASS in _classes(row) for row in markup.rows(tables[0])
430
- ):
431
- # Detail rows are what the page script fills from the gateway; a filled
432
- # table that still has them may also have gateway grades.
528
+ if not rendered and layouts == {True} and detail_rows:
529
+ # Empty detail rows are what the page script fills from the gateway; a
530
+ # bare-text table that still has them may also have gateway grades.
433
531
  raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
434
532
  return DescriptiveTable(MappingProxyType(subjects), layouts == {True})
435
533