| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- """Compose Italy's verified site adapters behind the normal plugin interface.
- No scheduler, queue, or local test-gate dependency. Calendar preparation uses
- one explicit manual/cloud OTP provider for either role. Only applicant Book
- may enter the separately enabled final submission and receipt reconciliation.
- """
- from __future__ import annotations
- import re
- import sys
- from time import monotonic
- from threading import Lock
- from plugins import ita_calendar_session as preparation
- from plugins.ita_calendar_book import wait_for_calendar_service
- from plugins.ita_calendar_query import CALENDAR_PATH, CalendarGateError, guard_calendar, listen_once, same_origin_path
- from plugins.ita_booking_final import FinalBookingAttempt, FinalOutcomeUnknown, NativeFinalSubmitter, VerifiedSubmission
- from plugins.ita_final_read_port import FinalReceiptReadPort
- from plugins.ita_protocol import ItaCapability
- from plugins.ita_otp import fetch_otp_from_cloud, utc_sent_at, validate_cloud_otp_environment
- from plugins.ita_turnstile import ItalyTurnstileRecovery
- from vs_types import BizLogicError, PermissionDeniedError
- # Reuse the existing preparation lock, including cloud reads: no competing OTP
- # requests inside this process. This does not coordinate other worker processes.
- _OTP_INPUT_LOCK = Lock()
- def prepare_calendar(plugin, route, *, role):
- """One native OTP + AVANTI, using the same functions as the tested gate."""
- if (role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
- or route.calendar_scan is None):
- raise BizLogicError("Italy Calendar preparation requires a single-tourism route")
- cloud = plugin.free_config.get("otp_mode") == "cloud"
- if cloud:
- query_config = plugin.free_config.get("query_mode", "services_probe") == "calendar"
- if ((role == "query") != query_config
- or plugin._book_final_configuration_valid() is not True):
- raise PermissionDeniedError("Italy automatic OTP requires a matching Query/Book role and valid final configuration")
- validate_cloud_otp_environment(route.mail, plugin.config.account.username)
- elif plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty():
- raise PermissionDeniedError("Italy Calendar needs an attached terminal for manual OTP (ITA-OTP-01)")
- page, generation = plugin.page, plugin.session_create_time
- username = plugin.config.account.username.strip().casefold()
- tab_id = page.tab_id
- booking_path = plugin._booking_path(route)
- def current(path):
- if (plugin.page is not page or page.tab_id != tab_id or plugin.session_create_time != generation
- or plugin.config.account.username.strip().casefold() != username
- or same_origin_path(page.url)[0] != path):
- raise CalendarGateError("Italy preparation Session or page changed")
- def packet_current(packet):
- if getattr(packet, "tab_id", None) != tab_id or getattr(packet, "is_failed", None) is not False:
- raise CalendarGateError("Italy preparation response came from another tab or failed")
- def click(selector):
- current(booking_path)
- plugin.mouse.human_click_ele(preparation._element_or_fail(page, selector))
- # A failed partial preparation cannot resend OTP on every Query signal.
- # A fresh login/session permits another operator-assisted attempt.
- preparation_key = (generation, tab_id, route.routing_key)
- with _OTP_INPUT_LOCK:
- if getattr(plugin, "_manual_preparation_attempt", None) == preparation_key:
- raise PermissionDeniedError("Italy preparation failed; restore the session before retrying")
- current(booking_path)
- script = preparation.guarded_preflight_script(route, booking_path)
- check_form = lambda: current(booking_path)
- # Both roles must pass the same form before entering Calendar. Reuse
- # one bounded recovery across both stages; prepared scans skip this path.
- recovery = ItalyTurnstileRecovery(page, check_current=check_form)
- plugin._log(f"Italy {role} Calendar preparation: reusing bounded Turnstile recovery.")
- preparation.wait_for_booking_preflight(page, script=script,
- check_current=check_form, wait_action=recovery)
- plugin._manual_preparation_attempt = preparation_key
- sent_at, sent_monotonic = None, None
- def send_otp():
- nonlocal sent_at, sent_monotonic
- if cloud:
- validate_cloud_otp_environment(route.mail, username)
- sent_at, sent_monotonic = utc_sent_at(), monotonic()
- click("#otp-send")
- def check_cloud_window():
- if cloud and (sent_monotonic is None or
- not 0 <= monotonic() - sent_monotonic < route.mail.expiry_seconds):
- raise CalendarGateError("Italy OTP local read window expired; no automatic resend")
- packet = listen_once(page, target=preparation.OTP_PATH, method="GET", timeout=30,
- action=send_otp)
- packet_current(packet)
- preparation.validate_otp_packet(packet, service_id=route.service_id)
- current(booking_path)
- if cloud:
- check_cloud_window()
- plugin._log(f"Italy {role} OTP sent; waiting for the authorized mailbox (one read attempt).")
- otp = fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
- else:
- plugin._log(f"Italy {role} OTP sent; enter the code in this terminal.")
- otp = preparation._read_manual_otp()
- try:
- pattern = r"[0-9]{6}" if cloud else r"[0-9]{4,12}"
- if not isinstance(otp, str) or re.fullmatch(pattern, otp) is None:
- raise CalendarGateError("Italy OTP format rejected")
- current(booking_path)
- check_cloud_window()
- try:
- preparation._enter_otp(plugin, otp)
- except Exception:
- if cloud:
- # Browser transport exceptions may contain typed values.
- raise CalendarGateError("Italy automatic OTP DOM write verification failed") from None
- raise
- if cloud:
- plugin._log("Italy automatic OTP DOM write verified; continuing to Calendar.")
- finally:
- del otp
- preparation.wait_for_booking_preflight(
- page, script=script, stage=preparation.BookingPreflightStage.AFTER_OTP_SEND,
- check_current=check_form, wait_action=recovery,
- )
- check_cloud_window()
- try:
- page.set.auto_handle_alert(accept=True)
- packet = listen_once(page, target=booking_path, method="POST", timeout=30,
- action=lambda: click("#btnAvanti"))
- packet_current(packet)
- preparation._wait_for_calendar(page)
- current(CALENDAR_PATH)
- preparation.validate_avanti_packet(packet, booking_path=booking_path, final_page_url=page.url)
- finally:
- page.set.auto_handle_alert(on_off=False)
- guard_calendar(page)
- wait_for_calendar_service(page, session_is_current=lambda: current(CALENDAR_PATH) is None)
- if role == "query":
- plugin._record_calendar_query_prepared_route(route)
- else:
- plugin._record_calendar_book_prepared_route(route)
- plugin._manual_preparation_attempt = None
- def prepare_query_if_needed(plugin, apt_type):
- """Return a negative entry result, or prepare and let Query scan real dates."""
- if same_origin_path(plugin.page.url)[0] == CALENDAR_PATH:
- return None # Existing Query continuity checks remain authoritative.
- route = plugin._resolve_route(apt_type)
- entry = plugin._query_once(apt_type, query_mode="services_probe")
- if not entry.success:
- return entry
- plugin._clear_calendar_query_state()
- prepare_calendar(plugin, route, role="query")
- return None
- def book(plugin, slot_info, user_inputs):
- """Applicant-owned Calendar → existing pre-final adapter → standard result."""
- if plugin._book_final_configuration_valid() is not True:
- raise PermissionDeniedError("Italy final submission configuration is invalid")
- if not isinstance(user_inputs, dict) or not isinstance(user_inputs.get("username"), str):
- raise BizLogicError("Italy Book requires the applicant username")
- username = user_inputs["username"].strip().casefold()
- if (not username or username != plugin.config.account.username.strip().casefold()
- or plugin.free_config.get("query_mode", "services_probe") == "calendar"
- or getattr(plugin, "_calendar_query_route_key", None) is not None):
- raise BizLogicError("Italy Book requires a separate applicant Session, not a Query Session")
- route = plugin._resolve_route(slot_info.apt_type)
- attempt = getattr(plugin, "_production_final_attempt", None)
- if attempt is not None and attempt.state not in {"blocked", "rejected"}:
- # The same task may retry success reporting, but must never submit twice.
- result = getattr(plugin, "_production_book_result", None)
- if (attempt.state == "confirmed" and result is not None
- and attempt.target.applicant == username and attempt.target.routing_key == route.routing_key):
- return result
- raise FinalOutcomeUnknown()
- if same_origin_path(plugin.page.url)[0] != CALENDAR_PATH:
- entry = plugin._book_discovery_or_prepared(slot_info, user_inputs)
- if entry.label != "booking-form-ready-before-avanti":
- return entry
- prepare_calendar(plugin, route, role="book")
- elif plugin._calendar_book_context_matches(route, username):
- # Refresh inventory on the next signal after a definite negative result.
- plugin._calendar_book_attempted = False
- result = plugin._book_discovery_or_prepared(slot_info, user_inputs)
- if plugin.last_booking_precommit is None or plugin.free_config.get("final_submit_enabled") is not True:
- return result
- return submit_final(plugin, route)
- def submit_final(plugin, route, *, request_audit: preparation.CalendarRequestAudit | None = None):
- """Reuse native submission and attribution with one audit per page.
- A caller observing the whole workflow may lend its live audit. Ownership
- stays with that caller; standalone production calls own their audit as
- before. Neither path replaces callbacks or interrupts request coverage.
- """
- port = FinalReceiptReadPort(plugin, route)
- owns_audit = request_audit is None
- audit = preparation.CalendarRequestAudit(plugin.page, include_time_slots=True) if owns_audit else request_audit
- if owns_audit:
- audit.start()
- else:
- audit.require_active_on(plugin.page)
- if "timeSlotRequests" not in audit.snapshot():
- raise CalendarGateError("Final request audit must include time slots")
- try:
- before = audit.settled_snapshot()
- def submit():
- native = NativeFinalSubmitter(plugin.page, port.target, port.session_is_current)
- signal = native()
- after = audit.settled_snapshot()
- if (after["finalRequests"] - before["finalRequests"] == 1
- and all(after[key] == before[key] for key in before if key != "finalRequests")
- and isinstance(native.submitted_selection, VerifiedSubmission)):
- port.record_submission(native.submitted_selection)
- return signal
- attempt = FinalBookingAttempt(port.target, read_reservations=port, submit_native=submit,
- session_is_current=port.session_is_current)
- plugin._production_final_attempt = attempt
- result = attempt.execute(enabled=True)
- plugin._production_book_result = result if result.success else None
- return result
- finally:
- # A diagnostic teardown failure must not turn a verified success into a
- # generic booking failure (and a second real booking on the next signal).
- if owns_audit:
- try:
- audit.stop()
- except Exception:
- plugin._log("Italy passive request audit cleanup failed; session needs cleanup.")
|