"""Bounded Calendar-preparation interaction, composing the existing VFS helper. This adapter never declares success: Italy's next preflight must observe the actual response field AND an enabled AVANTI. No refresh, reset, token injection, OTP action, blanket DFS search, or final submission lives here. """ from __future__ import annotations import json from plugins.ita_calendar_query import CalendarGateError from plugins.ita_calendar_session import BookingPreflightStage from utils.cloudflare_bypass_for_scraping import CloudflareBypasser class ItalyTurnstileRecovery: """One instance per Query/Book preparation; three attempts across stages.""" MAX_ATTEMPTS = 3 INITIAL_DELAY = 5 RETRY_INTERVAL = 10 def __init__(self, page, *, check_current): self.page = page self.check_current = check_current self.attempts = 0 self._stage = None self._next_attempt = self.INITIAL_DELAY self._helper = None def __call__(self, raw, *, stage, elapsed, remaining): if not isinstance(stage, BookingPreflightStage): raise CalendarGateError("Italy Turnstile interaction stage invalid") if (not isinstance(raw, dict) or raw.get("pathMatches") is not True or raw.get("formPresent") is not True or type(raw.get("turnstileCount")) is not int or raw.get("turnstileCount") != 1): raise CalendarGateError("Italy Turnstile interaction requires the verified booking form") if raw.get("turnstileTokenPresent") is not False: return # Never touch a verified widget to fix an unrelated button. if self._stage is not stage: self._stage = stage self._next_attempt = self.INITIAL_DELAY if self.attempts >= self.MAX_ATTEMPTS or elapsed < self._next_attempt or remaining < 2: return self.check_current() self.attempts += 1 self._next_attempt = elapsed + self.RETRY_INTERVAL clicked = False failed = False try: if self._helper is None: # Reuse the exact helper used by VFS. Suppress its free-form # browser exceptions; emit only fixed Italy metadata below. self._helper = CloudflareBypasser(self.page, log=False) # Do NOT use bypass(): its page-title success check would accept # "Booking - Prenot@Mi" while the embedded widget is still pending. clicked = self._helper.click_verification_button(is_dfs=False) is True except Exception: failed = True self.check_current() print("ITA_BOOK_TURNSTILE_INTERACTION=" + json.dumps({ "contract": "ita-book-preflight-v2", "stage": stage.value, "attempt": self.attempts, "maxAttempts": self.MAX_ATTEMPTS, "clicked": clicked, "helperFailed": failed, }, sort_keys=True), flush=True)