| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607 |
- """Shared browser adapter for read-only Prenot@Mi Calendar queries.
- The pure wire-format rules live in :mod:`plugins.ita_protocol`. This module
- owns only the browser-facing mechanics that production Query and the Q-CAL
- diagnostic tool must share: one-shot listeners, strict packet metadata,
- native month navigation, the final-button guard, and bounded scanning.
- """
- from __future__ import annotations
- import json
- import time
- from dataclasses import dataclass
- from datetime import date, datetime
- from typing import Any, Callable
- from urllib.parse import urljoin, urlparse
- from plugins.ita_protocol import (
- CalendarDay,
- ItaProtocolError,
- available_calendar_days,
- parse_calendar_availability,
- )
- CALENDAR_PATH = "/BookingCalendar"
- AVAILABILITY_PATH = "/BookingCalendar/RetrieveCalendarAvailability"
- MAX_QUERY_LOOKAHEAD_MONTHS = 120
- DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
- CALENDAR_GUARD_SCRIPT = r"""
- /* coordinate:ita-calendar-query-final-guard */
- const finalButtons = Array.from(
- document.querySelectorAll('#btnPrenotaNoOtp')
- );
- finalButtons.forEach((button) => {
- button.disabled = true;
- button.setAttribute('aria-disabled', 'true');
- button.dataset.coordinateFinalGuard = 'enabled';
- });
- const resources = performance.getEntriesByType('resource');
- return {
- path: window.location.pathname,
- calendarFunctionPresent:
- typeof window.CaricaTimelineOrizzontale === 'function',
- finalButtonCount: finalButtons.length,
- allFinalButtonsGuarded: finalButtons.every(
- (button) => button.disabled &&
- button.dataset.coordinateFinalGuard === 'enabled'
- ),
- finalRequestCount: resources.filter(
- (entry) => entry.name.includes(
- '/BookingCalendar/InsertNewBooking'
- )
- ).length,
- timeSlotRequestCount: resources.filter(
- (entry) => entry.name.includes(
- '/BookingCalendar/RetrieveTimeSlots'
- )
- ).length,
- };
- """
- NEXT_MONTH_CONTROL_SCRIPT = r"""
- /* coordinate:ita-calendar-query-next-month */
- const shouldClick = arguments[0] === true;
- const selector = '#datetimepicker th.dtpicker-next';
- const candidates = Array.from(document.querySelectorAll(selector));
- const isActionable = (element) => {
- if (
- !element.isConnected ||
- element.hasAttribute('disabled') ||
- element.getAttribute('aria-disabled') === 'true'
- ) {
- return false;
- }
- const style = window.getComputedStyle(element);
- if (
- style.display === 'none' ||
- style.visibility === 'hidden' ||
- style.pointerEvents === 'none' ||
- Number.parseFloat(style.opacity || '1') <= 0
- ) {
- return false;
- }
- const rect = element.getBoundingClientRect();
- const left = Math.max(0, rect.left);
- const right = Math.min(window.innerWidth, rect.right);
- const top = Math.max(0, rect.top);
- const bottom = Math.min(window.innerHeight, rect.bottom);
- if (right <= left || bottom <= top) return false;
- const topNode = document.elementFromPoint(
- (left + right) / 2,
- (top + bottom) / 2
- );
- return Boolean(topNode && (
- topNode === element || element.contains(topNode)
- ));
- };
- const actionable = candidates.filter(isActionable);
- let clicked = false;
- if (shouldClick && actionable.length === 1) {
- clicked = true;
- actionable[0].click();
- }
- return {
- pathMatches: window.location.pathname === '/BookingCalendar',
- candidateCount: candidates.length,
- actionableCount: actionable.length,
- clicked,
- };
- """
- class CalendarGateError(RuntimeError):
- """Fail-closed Calendar adapter error without sensitive response data."""
- class CalendarAuthenticationExpiredError(CalendarGateError):
- """An observed response explicitly rejected the authenticated session."""
- class CalendarRateLimitedError(CalendarGateError):
- """The server explicitly limited requests; callers must not rotate accounts."""
- class CalendarAccessDeniedError(CalendarGateError):
- """Permission or browser verification requires operator attention."""
- class CalendarTransientError(CalendarGateError):
- """A read failed without evidence that authentication or schema changed."""
- class CalendarNextMonthUnavailableError(CalendarGateError):
- """Raised when the native next-month control cannot be used safely."""
- def require_plain_nonnegative_int(value: object, name: str) -> int:
- if isinstance(value, bool) or not isinstance(value, int) or value < 0:
- raise CalendarGateError(f"{name} must be a nonnegative integer")
- return value
- def same_origin_path(raw_url: object) -> tuple[str, object]:
- parsed = urlparse(str(raw_url or ""))
- try:
- port = parsed.port
- except ValueError as exc:
- raise CalendarGateError(
- "Observed request used an unexpected origin"
- ) from exc
- if (
- parsed.scheme != "https"
- or parsed.hostname != "prenotami.esteri.it"
- or port not in (None, 443)
- or parsed.username is not None
- or parsed.password is not None
- ):
- raise CalendarGateError("Observed request used an unexpected origin")
- return parsed.path, parsed
- def header_value(headers: object, name: str) -> str:
- if not hasattr(headers, "items"):
- return ""
- for key, value in headers.items():
- if str(key).casefold() == name.casefold():
- return str(value)
- return ""
- @dataclass(frozen=True, slots=True)
- class CalendarProbeResult:
- days: tuple[CalendarDay, ...]
- selected_day: str
- def __post_init__(self) -> None:
- if not isinstance(self.selected_day, str) or not self.selected_day.strip():
- raise CalendarGateError("selected_day must be a non-empty string")
- if any(not isinstance(item, CalendarDay) for item in self.days):
- raise CalendarGateError("days must contain CalendarDay values")
- selected_month = self.selected_month
- if any(
- (item.day.year, item.day.month) != selected_month
- for item in self.days
- ):
- raise CalendarGateError(
- "Availability response escaped the requested month"
- )
- @property
- def item_count(self) -> int:
- return len(self.days)
- @property
- def available_days(self) -> tuple[CalendarDay, ...]:
- return available_calendar_days(self.days)
- @property
- def available_count(self) -> int:
- return len(self.available_days)
- @property
- def selected_month(self) -> tuple[int, int]:
- value = self.selected_day.strip()[:10]
- for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
- try:
- parsed = datetime.strptime(value, date_format)
- except ValueError:
- continue
- return parsed.year, parsed.month
- raise CalendarGateError(
- "Availability selectedDay used an unknown date format"
- )
- def next_month_value(value: tuple[int, int]) -> tuple[int, int]:
- year, month = value
- return (year + 1, 1) if month == 12 else (year, month + 1)
- def month_text(value: tuple[int, int]) -> str:
- return f"{value[0]:04d}-{value[1]:02d}"
- @dataclass(frozen=True, slots=True)
- class CalendarQueryScanResult:
- """Result of scanning until the first positive month or the horizon end."""
- probes: tuple[CalendarProbeResult, ...]
- lookahead_months: int
- stop_reason: str
- def __post_init__(self) -> None:
- _validate_lookahead_months(self.lookahead_months)
- if not self.probes or any(
- not isinstance(probe, CalendarProbeResult)
- for probe in self.probes
- ):
- raise CalendarGateError(
- "Calendar query scan requires parsed probe results"
- )
- if len(self.probes) > self.lookahead_months:
- raise CalendarGateError(
- "Calendar query scan exceeded the configured horizon"
- )
- for previous, current in zip(self.probes, self.probes[1:]):
- if current.selected_month != next_month_value(
- previous.selected_month
- ):
- raise CalendarGateError(
- "Calendar request did not advance exactly one month"
- )
- if self.stop_reason == "first_available_month":
- if self.probes[-1].available_count == 0:
- raise CalendarGateError(
- "first-available stop requires a positive final probe"
- )
- if any(probe.available_count for probe in self.probes[:-1]):
- raise CalendarGateError(
- "Calendar query scanned beyond the first positive month"
- )
- elif self.stop_reason == "horizon_exhausted":
- if len(self.probes) != self.lookahead_months:
- raise CalendarGateError(
- "Calendar query ended before the configured horizon"
- )
- if any(probe.available_count for probe in self.probes):
- raise CalendarGateError(
- "Calendar query ignored a positive month"
- )
- else:
- raise CalendarGateError(
- "Calendar query scan used an unknown stop reason"
- )
- @property
- def scanned_months(self) -> int:
- return len(self.probes)
- @property
- def available_days(self) -> tuple[CalendarDay, ...]:
- if self.stop_reason != "first_available_month":
- return ()
- return self.probes[-1].available_days
- @property
- def earliest_available_date(self) -> date | None:
- return (
- self.available_days[0].day
- if self.available_days
- else None
- )
- def _validate_lookahead_months(value: object) -> int:
- if (
- isinstance(value, bool)
- or not isinstance(value, int)
- or not 1 <= value <= MAX_QUERY_LOOKAHEAD_MONTHS
- ):
- raise CalendarGateError(
- "lookahead_months must be between 1 and 120"
- )
- return value
- def listen_once(
- page: object,
- *,
- target: str,
- method: str,
- action: Callable[[], Any],
- timeout: float,
- ) -> object:
- """Listen around one native action and always stop the listener."""
- page.listen.start(target, method=method)
- try:
- action()
- packet = page.listen.wait(timeout=timeout)
- if not packet:
- raise CalendarTransientError(
- f"Expected {method} {target} was not observed"
- )
- return packet
- finally:
- page.listen.stop()
- def parse_availability_packet(packet: object) -> CalendarProbeResult:
- path, _ = same_origin_path(packet.url)
- if str(packet.method).upper() != "POST" or path != AVAILABILITY_PATH:
- raise CalendarGateError("Availability request method or path changed")
- response = packet.response
- status = response.status
- if type(status) is not int:
- raise CalendarGateError("Availability HTTP status was not an integer")
- if status in {301, 302, 303, 307, 308}:
- location = header_value(getattr(response, "headers", None), "Location")
- destination = urlparse(urljoin(packet.url, location))
- if location and destination.scheme == "https" and destination.hostname == "iam.esteri.it":
- raise CalendarAuthenticationExpiredError("Calendar response redirected to IAM")
- response_url = getattr(response, "url", None)
- if isinstance(response_url, str) and response_url:
- destination = urlparse(response_url)
- if destination.scheme == "https" and destination.hostname == "iam.esteri.it":
- raise CalendarAuthenticationExpiredError("Calendar response returned to IAM")
- response_path, _ = same_origin_path(response_url)
- if response_path != AVAILABILITY_PATH:
- raise CalendarGateError("Availability response reached an unexpected path")
- if status == 401:
- raise CalendarAuthenticationExpiredError("Calendar authentication expired")
- if status == 429:
- raise CalendarRateLimitedError("Calendar request was rate limited")
- if status == 403:
- raise CalendarAccessDeniedError("Calendar access requires operator attention")
- if status in {0, 408, 502, 503, 504}:
- raise CalendarTransientError("Calendar request temporarily failed")
- if status != 200:
- raise CalendarGateError("Availability response status was not 200")
- post_data = packet.request.postData
- if isinstance(post_data, str):
- try:
- post_data = json.loads(post_data)
- except json.JSONDecodeError as exc:
- raise CalendarGateError(
- "Availability request body was not JSON"
- ) from exc
- if not isinstance(post_data, dict) or set(post_data) != {
- "_Servizio",
- "selectedDay",
- }:
- raise CalendarGateError("Availability request keys changed")
- if isinstance(post_data["_Servizio"], bool) or not str(
- post_data["_Servizio"]
- ).strip():
- raise CalendarGateError("Availability runtime service id was empty")
- if (
- not isinstance(post_data["selectedDay"], str)
- or not post_data["selectedDay"].strip()
- ):
- raise CalendarGateError("Availability selectedDay was empty")
- try:
- days = parse_calendar_availability(packet.response.raw_body)
- except ItaProtocolError as exc:
- raise CalendarGateError(
- f"Availability response rejected ({exc.code})"
- ) from exc
- return CalendarProbeResult(
- days=days,
- selected_day=post_data["selectedDay"],
- )
- def validate_next_month_snapshot(
- raw: object,
- *,
- expected_clicked: bool,
- allow_unready: bool = False,
- ) -> dict[str, object]:
- """Require the exact, non-sensitive Calendar month-control shape."""
- if not isinstance(raw, dict):
- raise CalendarGateError(
- "Calendar next-month control did not return an object"
- )
- expected_keys = {
- "pathMatches",
- "candidateCount",
- "actionableCount",
- "clicked",
- }
- if set(raw) != expected_keys:
- raise CalendarGateError(
- "Calendar next-month control returned unexpected fields"
- )
- if raw["pathMatches"] is not True:
- raise CalendarGateError(
- "Calendar next-month control was evaluated outside Calendar"
- )
- candidate_count = require_plain_nonnegative_int(
- raw["candidateCount"],
- "candidateCount",
- )
- actionable_count = require_plain_nonnegative_int(
- raw["actionableCount"],
- "actionableCount",
- )
- if actionable_count > candidate_count:
- raise CalendarGateError(
- "Calendar next-month actionable count exceeded candidates"
- )
- if not isinstance(expected_clicked, bool):
- raise CalendarGateError("expected_clicked must be a boolean")
- if raw["clicked"] is not expected_clicked:
- raise CalendarGateError(
- "Calendar next-month click acknowledgement changed"
- )
- if actionable_count != 1 and not (
- allow_unready and actionable_count == 0
- ):
- raise CalendarGateError(
- "Calendar next-month control was not uniquely actionable"
- )
- return raw
- def click_next_month(
- page: object,
- *,
- timeout: float = 10,
- diagnostic: Callable[[object], None] | None = None,
- ) -> None:
- """Click only the unique visible Bootstrap day-view month control."""
- deadline = time.monotonic() + timeout
- last_raw: object = None
- while time.monotonic() < deadline:
- last_raw = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, False)
- try:
- snapshot = validate_next_month_snapshot(
- last_raw,
- expected_clicked=False,
- allow_unready=True,
- )
- except CalendarGateError:
- if diagnostic:
- diagnostic(last_raw)
- raise
- if snapshot["actionableCount"] == 1:
- break
- time.sleep(0.25)
- else:
- if diagnostic:
- diagnostic(last_raw)
- raise CalendarNextMonthUnavailableError(
- "Calendar next-month control was not actionable before timeout"
- )
- clicked = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, True)
- if diagnostic:
- diagnostic(clicked)
- validate_next_month_snapshot(clicked, expected_clicked=True)
- def refresh_calendar(page: object) -> None:
- page.refresh()
- page.wait.doc_loaded()
- def guard_calendar(page: object) -> dict[str, object]:
- """Disable the final button and reject any observed final request."""
- raw = page.run_js(CALENDAR_GUARD_SCRIPT)
- if not isinstance(raw, dict):
- raise CalendarGateError("Calendar guard did not return an object")
- expected = {
- "path": CALENDAR_PATH,
- "calendarFunctionPresent": True,
- "finalButtonCount": 1,
- "allFinalButtonsGuarded": True,
- "finalRequestCount": 0,
- }
- for key, expected_value in expected.items():
- if raw.get(key) != expected_value:
- raise CalendarGateError(f"Calendar guard rejected {key}")
- return raw
- def capture_initial_probe(page: object) -> CalendarProbeResult:
- packet = listen_once(
- page,
- target=AVAILABILITY_PATH,
- method="POST",
- action=lambda: refresh_calendar(page),
- timeout=30,
- )
- probe = parse_availability_packet(packet)
- guard_calendar(page)
- return probe
- def capture_next_probe(page: object) -> CalendarProbeResult:
- packet = listen_once(
- page,
- target=AVAILABILITY_PATH,
- method="POST",
- action=lambda: click_next_month(page),
- timeout=30,
- )
- probe = parse_availability_packet(packet)
- guard_calendar(page)
- return probe
- def scan_until_first_available_month(
- page: object,
- *,
- lookahead_months: int,
- log: Callable[[str], None] | None = None,
- month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
- ) -> CalendarQueryScanResult:
- """Scan sequential months and stop immediately at the first positive one."""
- months = _validate_lookahead_months(lookahead_months)
- if (
- isinstance(month_click_interval_seconds, bool)
- or not isinstance(month_click_interval_seconds, (int, float))
- or month_click_interval_seconds < 0
- ):
- raise CalendarGateError(
- "month_click_interval_seconds must be nonnegative"
- )
- probes = [capture_initial_probe(page)]
- if log:
- log(
- "Italy Calendar probe "
- f"index=0 available={probes[0].available_count}"
- )
- if probes[0].available_count:
- return CalendarQueryScanResult(
- probes=tuple(probes),
- lookahead_months=months,
- stop_reason="first_available_month",
- )
- for index in range(1, months):
- if month_click_interval_seconds:
- time.sleep(month_click_interval_seconds)
- try:
- probe = capture_next_probe(page)
- except CalendarNextMonthUnavailableError as exc:
- raise CalendarGateError(
- "Calendar scan ended before the configured horizon"
- ) from exc
- if probe.selected_month != next_month_value(
- probes[-1].selected_month
- ):
- raise CalendarGateError(
- "Calendar request did not advance exactly one month"
- )
- probes.append(probe)
- if log:
- log(
- "Italy Calendar probe "
- f"index={index} available={probe.available_count}"
- )
- if probe.available_count:
- return CalendarQueryScanResult(
- probes=tuple(probes),
- lookahead_months=months,
- stop_reason="first_available_month",
- )
- return CalendarQueryScanResult(
- probes=tuple(probes),
- lookahead_months=months,
- stop_reason="horizon_exhausted",
- )
|