| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- """Read-only Prenot@Mi receipt adapter, not a final-submit read port.
- These objects contain observed display facts, not an inferred service/account
- binding or proof linking an assigned appointment time to a selected slot.
- Only observed Italian cancelled/confirmed states are classified; others stay UNKNOWN.
- No navigation, credentials, OTP, form writes or final actions live here.
- """
- from __future__ import annotations
- import math
- import re
- import time
- from dataclasses import dataclass, field
- from datetime import date
- from plugins.ita_booking_final import ReservationState
- from plugins.ita_calendar_query import same_origin_path
- from plugins.ita_protocol import MAX_PROTOCOL_ITEMS
- LIST_PATH = "/Reservation"
- DETAIL_PREFIX = "/ReservationDetail/Index/"
- HEADERS = ("Codice Prenotazione", "Ufficio", "Servizio", "Data", "Ora", "Stato", "Dati Richiedente")
- DETAIL_LABELS = ("Servizio Consolare", "Servizio Erogato", "Codice Prenotazione",
- "Tipo Prenotazione", "Data", "Ora", "Stato")
- MONTHS_IT = ("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio",
- "agosto", "settembre", "ottobre", "novembre", "dicembre")
- class ReservationReadError(ValueError):
- """Only adapter-owned reason codes; never include DOM text or browser errors."""
- def __init__(self, reason: str):
- self.reason = reason
- super().__init__(f"Italy reservation read rejected: {reason}")
- @dataclass(frozen=True, slots=True, repr=False)
- class ReservationDetail:
- reference: str
- office: str
- service_name: str
- booking_type: str
- day: date
- appointment_time: str
- status_text: str
- status_code: str
- state: ReservationState
- @dataclass(frozen=True, slots=True, repr=False)
- class ReservationListRow:
- reference: str
- detail_url: str
- office: str
- service_name: str
- day: date
- appointment_time: str
- status_text: str
- state: ReservationState
- @dataclass(frozen=True, slots=True)
- class ReservationListing:
- """Coverage of the loaded client data, NOT a fresh account-bound snapshot."""
- rows: tuple[ReservationListRow, ...] = field(repr=False)
- page_count: int
- waitlist_count: int = 0
- _CONTEXT_JS = r"""
- const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
- const fail = reason => ({error: reason});
- if (window.location.origin !== 'https://prenotami.esteri.it') return fail('wrong_page');
- if (document.readyState !== 'complete') return fail('not_ready');
- if (!document.querySelector('.app-menu')) return fail('authentication_missing');
- """
- DETAIL_READ_SCRIPT = _CONTEXT_JS + r"""
- /* coordinate:ita-reservation-detail-readonly */
- if (!/^\/ReservationDetail\/Index\/[^/]+$/.test(window.location.pathname)) return fail('wrong_page');
- const headings = Array.from(document.querySelectorAll('h4'));
- const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
- const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
- if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
- const root = booking[0].parentElement;
- if (!root || !root.classList.contains('my-col-6') || root.contains(applicant[0])) return fail('unsafe_scope');
- const nameOf = e => clean(e.textContent).match(
- /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:\s*$/)?.[1];
- const labels = Array.from(root.querySelectorAll('label')).filter(nameOf);
- if (labels.length !== 7 || new Set(labels.map(nameOf)).size !== 7) return fail('fields_ambiguous');
- const fields = {};
- for (const label of labels) {
- const row = label.parentElement;
- if (labels.filter(e => row.contains(e)).length !== 1) return fail('row_ambiguous');
- const values = [];
- for (const node of row.childNodes) {
- if (node === label || node.nodeType === 8) continue;
- // The observed values are text siblings or one b. Do not read nested
- // forms, print payloads, applicant sections or arbitrary HTML as values.
- if (node.nodeType !== 3 && !(node.nodeType === 1 && node.tagName === 'B' && node.children.length === 0))
- return fail('value_structure_changed');
- const value = clean(node.textContent);
- if (value) values.push(value);
- }
- if (values.length !== 1 || values[0].length > 256) return fail('value_ambiguous');
- fields[nameOf(label)] = values[0];
- }
- const codes = document.querySelectorAll('input#IDTipoStatoPrenotazione');
- if (codes.length !== 1 || codes[0].type !== 'hidden' || codes[0].name !== 'IDTipoStatoPrenotazione')
- return fail('status_control_ambiguous');
- return {path: window.location.pathname, fields, statusCode: clean(codes[0].value)};
- """
- LIST_READ_SCRIPT = _CONTEXT_JS + r"""
- /* coordinate:ita-reservation-list-readonly */
- if (window.location.pathname !== '/Reservation') return fail('wrong_page');
- const readDateCell = cell => {
- // Observed shape: optional hidden element(s), one non-empty text sibling.
- // Do not use the whole cell's textContent (includes hidden metadata), nor
- // innerText (unrendered DataTables pages can fall back to textContent).
- const nodes = Array.from(cell.childNodes), values = [];
- if (nodes.length > 16) return null;
- for (const node of nodes) {
- if (node.nodeType === 8) continue;
- if (node.nodeType === 3) {
- const value = clean(node.textContent);
- if (value) values.push(value);
- continue;
- }
- if (node.nodeType !== 1) return null;
- const style = window.getComputedStyle(node);
- // Own inline/hidden markers remain checkable for detached client rows.
- // visibility:hidden only proves a leaf hidden: descendants can override it.
- const hidden = node.hidden === true || node.style.display === 'none' || style.display === 'none';
- const hiddenLeaf = node.children.length === 0 &&
- (node.style.visibility === 'hidden' || style.visibility === 'hidden');
- if (!hidden && !hiddenLeaf) return null;
- // Hidden metadata is excluded structurally; never parse or log its value.
- }
- return values.length === 1 ? values[0] : null;
- };
- const $ = window.jQuery;
- const ids = ['dataTableReservations', 'dataTableReservationsWL'];
- const tables = [];
- for (const id of ids) {
- const matches = document.querySelectorAll('#' + id);
- if (matches.length !== 1) return fail('table_ambiguous');
- const table = matches[0];
- const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
- if (!$?.fn?.dataTable?.isDataTable(table)) {
- const empty = table.querySelectorAll('tbody tr').length === 0 && headers.length === 0 &&
- !table.classList.contains('dataTable') && !table.closest('.dataTables_wrapper');
- if (id !== ids[1] || !empty) return fail('not_ready');
- tables.push({id, structuralEmpty: true});
- continue;
- }
- // This getter is only used after isDataTable: it must never initialize a table.
- const api = $(table).DataTable(), pageInfo = api.page.info();
- const info = Object.fromEntries(['page', 'pages', 'start', 'end', 'length',
- 'recordsTotal', 'recordsDisplay', 'serverSide'].map(k => [k, pageInfo[k]]));
- const count = api.rows().count();
- if (!Number.isInteger(count) || count < 0 || count > 512) return fail('row_limit');
- if (info.serverSide !== false || api.search() || api.columns().search().toArray().some(Boolean) ||
- count !== info.recordsTotal || count !== info.recordsDisplay || api.rows({search: 'applied'}).count() !== count)
- return fail('coverage_incomplete');
- if (id === ids[1]) {
- if (count !== 0) return fail('waitlist_schema_unverified');
- tables.push({id, structuralEmpty: false, count, info});
- continue;
- }
- const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
- if (![7, 8].includes(headers.length) || expected.some((h, i) => headers[i] !== h) ||
- (headers.length === 8 && headers[7] !== '')) return fail('headers_changed');
- const nodes = api.rows().nodes().toArray();
- if (nodes.length !== count) return fail('row_nodes_incomplete');
- const rows = [];
- for (const node of nodes) {
- const cells = Array.from(node.children);
- if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
- const links = cells[0].querySelectorAll('a[href]');
- if (links.length !== 1) return fail('detail_link_ambiguous');
- const date = readDateCell(cells[3]);
- if (date === null) return fail('date_cell_structure_changed');
- const row = {reference: clean(cells[0].textContent), detailUrl: links[0].href,
- office: clean(cells[1].textContent), service: clean(cells[2].textContent),
- date, time: clean(cells[4].textContent), status: clean(cells[5].textContent)};
- if (Object.values(row).some(v => typeof v !== 'string' || !v || v.length > 256)) return fail('field_invalid');
- rows.push(row);
- // Do not access applicant cell 6 or unnamed cell 7.
- }
- tables.push({id, structuralEmpty: false, headers, count, info, rows});
- }
- return {path: window.location.pathname, tables};
- """
- DATE_DIAGNOSTIC_SCRIPT = _CONTEXT_JS + r"""
- /* coordinate:ita-reservation-date-diagnostic-readonly */
- if (window.location.pathname !== '/Reservation') return fail('wrong_page');
- const tables = document.querySelectorAll('#dataTableReservations');
- if (tables.length !== 1) return fail('table_ambiguous');
- const table = tables[0], $ = window.jQuery;
- const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
- const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
- if (![7,8].includes(headers.length) || expected.some((v,i) => headers[i] !== v) ||
- (headers.length === 8 && headers[7] !== '') || !$?.fn?.dataTable?.isDataTable(table))
- return fail('headers_changed');
- const nodes = $(table).DataTable().rows().nodes().toArray();
- if (nodes.length > 512) return fail('row_limit');
- const samples = [];
- for (const row of nodes.slice(0,3)) {
- const cells = Array.from(row.children);
- if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
- // Only the verified Data column. No reference, account, applicant, HTML or attributes.
- const cell = cells[3], children = Array.from(cell.childNodes);
- const text = clean(cell.textContent), rendered = clean(cell.innerText);
- if (text.length > 256 || rendered.length > 256) return fail('field_invalid');
- const parts = children.slice(0,6).map(n => {
- const style = n.nodeType === 1 ? window.getComputedStyle(n) : null;
- return {kind: n.nodeType === 3 ? 'text' : (n.nodeType === 1 &&
- ['SPAN','B','I','BR'].includes(n.tagName) ? n.tagName.toLowerCase() : 'other'),
- text: clean(n.textContent), hidden: !!style && (style.display === 'none' || style.visibility === 'hidden')};
- });
- samples.push({text, rendered, parts, partsTruncated: children.length > 6});
- }
- return {path: window.location.pathname, samples, rowsTruncated: nodes.length > 3};
- """
- def _date_shape(value: object) -> dict:
- """Only structural symbols and known month indexes; never emit raw field text."""
- if not isinstance(value, str) or len(value) > 256:
- raise ValueError()
- normalized = " ".join(value.split())
- shape = "".join("D" if c.isdecimal() else "L" if c.isalpha() else c if c in " /:.,-" else "?"
- for c in normalized[:96])
- months = [i for i, month in enumerate(MONTHS_IT, 1)
- if re.search(r"(?<![A-Za-z])" + month + r"(?![A-Za-z])", normalized, re.IGNORECASE)]
- try:
- _day(normalized)
- accepted = True
- except ReservationReadError:
- accepted = False
- return {"shape": shape, "length": len(normalized), "truncated": len(normalized) > 96,
- "italianMonths": months, "acceptedByCurrentParser": accepted}
- def read_reservation_date_diagnostic(page: object) -> dict:
- """One bounded extra read on a failed list parse, not an alternate parser.
- The raw verified date-cell strings stay local; only allowlisted shapes leave
- this function. A malformed diagnostic cannot leak arbitrary browser output.
- """
- try:
- raw = _read_current(page, DATE_DIAGNOSTIC_SCRIPT, detail=False)
- if (set(raw) != {"path", "samples", "rowsTruncated"} or
- type(raw["rowsTruncated"]) is not bool or not isinstance(raw["samples"], list) or
- len(raw["samples"]) > 3):
- raise ValueError()
- samples = []
- for item in raw["samples"]:
- if (not isinstance(item, dict) or set(item) != {"text", "rendered", "parts", "partsTruncated"} or
- type(item["partsTruncated"]) is not bool or not isinstance(item["parts"], list) or
- len(item["parts"]) > 6):
- raise ValueError()
- parts = []
- for part in item["parts"]:
- if (not isinstance(part, dict) or set(part) != {"kind", "text", "hidden"} or
- part["kind"] not in ("text", "span", "b", "i", "br", "other") or
- type(part["hidden"]) is not bool):
- raise ValueError()
- parts.append({"kind": part["kind"], "hidden": part["hidden"], **_date_shape(part["text"])})
- samples.append({"text": _date_shape(item["text"]), "rendered": _date_shape(item["rendered"]),
- "textEqualsRendered": item["text"] == item["rendered"],
- "parts": parts, "partsTruncated": item["partsTruncated"]})
- return {"available": True, "samples": samples, "rowsTruncated": raw["rowsTruncated"]}
- except Exception:
- return {"available": False}
- def _text(value: object) -> str:
- if (not isinstance(value, str) or not 0 < len(value) <= 256 or value != value.strip()
- or any(ord(c) < 32 or ord(c) == 127 for c in value)):
- raise ReservationReadError("field_invalid")
- return value
- def _day(value: object) -> date:
- value = _text(value)
- match = re.fullmatch(r"([0-9]{1,2}) ([A-Za-z]+) ([0-9]{4})", value)
- if match:
- try:
- return date(int(match[3]), MONTHS_IT.index(match[2].casefold()) + 1, int(match[1]))
- except ValueError:
- pass
- raise ReservationReadError("date_unrecognized") from None
- def _appointment_time(value: object) -> str:
- value = _text(value)
- if re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", value) is None:
- raise ReservationReadError("time_unrecognized")
- return value
- def _state(text: str, code: str | None = None) -> ReservationState:
- # A list label is a candidate; a detail must also have its observed code.
- # Never infer ACTIVE from "not cancelled" or from the numeric code alone.
- if text.casefold() == "annullata" and code in (None, "3"):
- return ReservationState.CANCELLED
- if text.casefold() == "confermata" and code in (None, "2"):
- return ReservationState.ACTIVE
- return ReservationState.UNKNOWN
- def _detail_path(url: object) -> str:
- try:
- path, parsed = same_origin_path(url)
- suffix = path.removeprefix(DETAIL_PREFIX)
- if (not path.startswith(DETAIL_PREFIX) or not suffix or len(suffix) > 256
- or any(c in suffix for c in "/\\%") or suffix in {".", ".."}
- or parsed.query or parsed.fragment):
- raise ValueError()
- return path
- except Exception:
- raise ReservationReadError("detail_url_invalid") from None
- def parse_reservation_detail(raw: object) -> ReservationDetail:
- if not isinstance(raw, dict) or set(raw) != {"path", "fields", "statusCode"}:
- raise ReservationReadError("detail_schema_changed")
- _detail_path("https://prenotami.esteri.it" + raw["path"] if isinstance(raw["path"], str) else None)
- fields = raw["fields"]
- if not isinstance(fields, dict) or set(fields) != set(DETAIL_LABELS):
- raise ReservationReadError("fields_ambiguous")
- values = {key: _text(value) for key, value in fields.items()}
- code = raw["statusCode"]
- if not isinstance(code, str) or not re.fullmatch(r"[0-9]{1,4}", code):
- raise ReservationReadError("status_code_invalid")
- return ReservationDetail(
- values["Codice Prenotazione"], values["Servizio Consolare"], values["Servizio Erogato"],
- values["Tipo Prenotazione"], _day(values["Data"]), _appointment_time(values["Ora"]),
- values["Stato"], code, _state(values["Stato"], code),
- )
- def _coverage(table: dict) -> tuple[int, int]:
- info, count = table.get("info"), table.get("count")
- if not isinstance(info, dict) or type(count) is not int or not 0 <= count <= MAX_PROTOCOL_ITEMS:
- raise ReservationReadError("coverage_invalid")
- keys = ("recordsTotal", "recordsDisplay", "page", "pages", "start", "end", "length")
- if any(type(info.get(k)) is not int for k in keys) or info.get("serverSide") is not False:
- raise ReservationReadError("coverage_invalid")
- total, displayed, page, pages, start, end, length = (info[k] for k in keys)
- if total != count or displayed != count or not 0 <= start <= end <= count:
- raise ReservationReadError("coverage_incomplete")
- expected_pages = (math.ceil(count / length) if length > 0 else 1) if count else 0
- if (length not in (-1,) and length <= 0) or pages != expected_pages or not 0 <= page < max(1, pages):
- raise ReservationReadError("pagination_invalid")
- if start != (page * length if length > 0 else 0) or end != (min(start + length, count) if length > 0 else count):
- raise ReservationReadError("pagination_invalid")
- return count, pages
- def parse_reservation_listing(raw: object) -> ReservationListing:
- if not isinstance(raw, dict) or set(raw) != {"path", "tables"} or raw["path"] != LIST_PATH:
- raise ReservationReadError("list_schema_changed")
- tables = raw["tables"]
- if not isinstance(tables, list) or len(tables) != 2 or not all(isinstance(t, dict) for t in tables):
- raise ReservationReadError("table_ambiguous")
- main, waitlist = tables
- if main.get("id") != "dataTableReservations" or waitlist.get("id") != "dataTableReservationsWL":
- raise ReservationReadError("table_ambiguous")
- if main.get("structuralEmpty") is not False or main.get("headers") not in (list(HEADERS), [*HEADERS, ""]):
- raise ReservationReadError("headers_changed")
- count, pages = _coverage(main)
- if waitlist.get("structuralEmpty") is True:
- if set(waitlist) != {"id", "structuralEmpty"}:
- raise ReservationReadError("waitlist_ambiguous")
- elif waitlist.get("structuralEmpty") is not False or _coverage(waitlist)[0] != 0:
- raise ReservationReadError("waitlist_schema_unverified")
- rows = main.get("rows")
- if not isinstance(rows, list) or len(rows) != count:
- raise ReservationReadError("row_nodes_incomplete")
- result, references, destinations = [], set(), set()
- for row in rows:
- if not isinstance(row, dict) or set(row) != {"reference", "detailUrl", "office", "service", "date", "time", "status"}:
- raise ReservationReadError("row_schema_changed")
- values = {key: _text(value) for key, value in row.items()}
- path = _detail_path(values["detailUrl"])
- if values["reference"] in references or path in destinations:
- raise ReservationReadError("duplicate_record")
- references.add(values["reference"])
- destinations.add(path)
- result.append(ReservationListRow(values["reference"], values["detailUrl"], values["office"],
- values["service"], _day(values["date"]), _appointment_time(values["time"]),
- values["status"], _state(values["status"])))
- return ReservationListing(tuple(result), pages)
- def _read_current(page: object, script: str, *, detail: bool) -> object:
- try:
- before_url, before_tab = page.url, page.tab_id
- path, parsed = same_origin_path(before_url)
- if parsed.query or parsed.fragment or (not detail and path != LIST_PATH):
- raise ReservationReadError("wrong_page")
- if detail:
- _detail_path(before_url)
- if not isinstance(before_tab, str) or not before_tab:
- raise ReservationReadError("context_changed")
- raw = page.run_js(script)
- if page.url != before_url or page.tab_id != before_tab:
- raise ReservationReadError("context_changed")
- if not isinstance(raw, dict) or raw.get("path") != path:
- reason = "not_ready" if isinstance(raw, dict) and raw == {"error": "not_ready"} else "page_read_rejected"
- raise ReservationReadError(reason)
- return raw
- except ReservationReadError:
- raise
- except Exception:
- raise ReservationReadError("browser_read_failed") from None
- def read_reservation_detail(page: object) -> ReservationDetail:
- """Read the current detail page once. No URL, reference or PII is logged."""
- return parse_reservation_detail(_read_current(page, DETAIL_READ_SCRIPT, detail=True))
- def read_reservation_listing(page: object, *, timeout: float = 5, poll_interval: float = 0.25) -> ReservationListing:
- """Two stable reads within a bound, reusing the existing count tool pattern.
- Only not-ready states are polled; unsupported schemas/coverage fail closed.
- This checks the current page and never navigates, draws or clears filters.
- """
- if (any(type(v) not in (int, float) or not math.isfinite(v) or v <= 0 for v in (timeout, poll_interval))
- or poll_interval > timeout or timeout > 60):
- raise ReservationReadError("wait_config_invalid")
- try:
- binding = (page.url, page.tab_id)
- except Exception:
- raise ReservationReadError("browser_read_failed") from None
- deadline, previous = time.monotonic() + timeout, None
- while time.monotonic() < deadline:
- try:
- try:
- context_matches = (page.url, page.tab_id) == binding
- except Exception:
- raise ReservationReadError("browser_read_failed") from None
- if not context_matches:
- raise ReservationReadError("context_changed")
- current = parse_reservation_listing(_read_current(page, LIST_READ_SCRIPT, detail=False))
- except ReservationReadError as error:
- if error.reason != "not_ready":
- raise
- previous = None
- else:
- if current == previous:
- return current
- previous = current
- time.sleep(min(poll_interval, max(0, deadline - time.monotonic())))
- raise ReservationReadError("stability_timeout")
|