ita_turnstile.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Bounded Calendar-preparation interaction, composing the existing VFS helper.
  2. This adapter never declares success: Italy's next preflight must observe the
  3. actual response field AND an enabled AVANTI. No refresh, reset, token injection,
  4. OTP action, blanket DFS search, or final submission lives here.
  5. """
  6. from __future__ import annotations
  7. import json
  8. from plugins.ita_calendar_query import CalendarGateError
  9. from plugins.ita_calendar_session import BookingPreflightStage
  10. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  11. class ItalyTurnstileRecovery:
  12. """One instance per Query/Book preparation; three attempts across stages."""
  13. MAX_ATTEMPTS = 3
  14. INITIAL_DELAY = 5
  15. RETRY_INTERVAL = 10
  16. def __init__(self, page, *, check_current):
  17. self.page = page
  18. self.check_current = check_current
  19. self.attempts = 0
  20. self._stage = None
  21. self._next_attempt = self.INITIAL_DELAY
  22. self._helper = None
  23. def __call__(self, raw, *, stage, elapsed, remaining):
  24. if not isinstance(stage, BookingPreflightStage):
  25. raise CalendarGateError("Italy Turnstile interaction stage invalid")
  26. if (not isinstance(raw, dict) or raw.get("pathMatches") is not True
  27. or raw.get("formPresent") is not True or type(raw.get("turnstileCount")) is not int
  28. or raw.get("turnstileCount") != 1):
  29. raise CalendarGateError("Italy Turnstile interaction requires the verified booking form")
  30. if raw.get("turnstileTokenPresent") is not False:
  31. return # Never touch a verified widget to fix an unrelated button.
  32. if self._stage is not stage:
  33. self._stage = stage
  34. self._next_attempt = self.INITIAL_DELAY
  35. if self.attempts >= self.MAX_ATTEMPTS or elapsed < self._next_attempt or remaining < 2:
  36. return
  37. self.check_current()
  38. self.attempts += 1
  39. self._next_attempt = elapsed + self.RETRY_INTERVAL
  40. clicked = False
  41. failed = False
  42. try:
  43. if self._helper is None:
  44. # Reuse the exact helper used by VFS. Suppress its free-form
  45. # browser exceptions; emit only fixed Italy metadata below.
  46. self._helper = CloudflareBypasser(self.page, log=False)
  47. # Do NOT use bypass(): its page-title success check would accept
  48. # "Booking - Prenot@Mi" while the embedded widget is still pending.
  49. clicked = self._helper.click_verification_button(is_dfs=False) is True
  50. except Exception:
  51. failed = True
  52. self.check_current()
  53. print("ITA_BOOK_TURNSTILE_INTERACTION=" + json.dumps({
  54. "contract": "ita-book-preflight-v2", "stage": stage.value,
  55. "attempt": self.attempts, "maxAttempts": self.MAX_ATTEMPTS,
  56. "clicked": clicked, "helperFailed": failed,
  57. }, sort_keys=True), flush=True)