ita_workflow.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """Compose Italy's verified site adapters behind the normal plugin interface.
  2. No scheduler, queue, or local test-gate dependency. Calendar preparation uses
  3. one explicit manual/cloud OTP provider for either role. Only applicant Book
  4. may enter the separately enabled final submission and receipt reconciliation.
  5. """
  6. from __future__ import annotations
  7. import re
  8. import sys
  9. from time import monotonic
  10. from threading import Lock
  11. from plugins import ita_calendar_session as preparation
  12. from plugins.ita_calendar_book import wait_for_calendar_service
  13. from plugins.ita_calendar_query import CALENDAR_PATH, CalendarGateError, guard_calendar, listen_once, same_origin_path
  14. from plugins.ita_booking_final import FinalBookingAttempt, FinalOutcomeUnknown, NativeFinalSubmitter, VerifiedSubmission
  15. from plugins.ita_final_read_port import FinalReceiptReadPort
  16. from plugins.ita_protocol import ItaCapability
  17. from plugins.ita_otp import fetch_otp_from_cloud, utc_sent_at, validate_cloud_otp_environment
  18. from plugins.ita_turnstile import ItalyTurnstileRecovery
  19. from vs_types import BizLogicError, PermissionDeniedError
  20. # Reuse the existing preparation lock, including cloud reads: no competing OTP
  21. # requests inside this process. This does not coordinate other worker processes.
  22. _OTP_INPUT_LOCK = Lock()
  23. def prepare_calendar(plugin, route, *, role):
  24. """One native OTP + AVANTI, using the same functions as the tested gate."""
  25. if (role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
  26. or route.calendar_scan is None):
  27. raise BizLogicError("Italy Calendar preparation requires a single-tourism route")
  28. cloud = plugin.free_config.get("otp_mode") == "cloud"
  29. if cloud:
  30. query_config = plugin.free_config.get("query_mode", "services_probe") == "calendar"
  31. if ((role == "query") != query_config
  32. or plugin._book_final_configuration_valid() is not True):
  33. raise PermissionDeniedError("Italy automatic OTP requires a matching Query/Book role and valid final configuration")
  34. validate_cloud_otp_environment(route.mail, plugin.config.account.username)
  35. elif plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty():
  36. raise PermissionDeniedError("Italy Calendar needs an attached terminal for manual OTP (ITA-OTP-01)")
  37. page, generation = plugin.page, plugin.session_create_time
  38. username = plugin.config.account.username.strip().casefold()
  39. tab_id = page.tab_id
  40. booking_path = plugin._booking_path(route)
  41. def current(path):
  42. if (plugin.page is not page or page.tab_id != tab_id or plugin.session_create_time != generation
  43. or plugin.config.account.username.strip().casefold() != username
  44. or same_origin_path(page.url)[0] != path):
  45. raise CalendarGateError("Italy preparation Session or page changed")
  46. def packet_current(packet):
  47. if getattr(packet, "tab_id", None) != tab_id or getattr(packet, "is_failed", None) is not False:
  48. raise CalendarGateError("Italy preparation response came from another tab or failed")
  49. def click(selector):
  50. current(booking_path)
  51. plugin.mouse.human_click_ele(preparation._element_or_fail(page, selector))
  52. # A failed partial preparation cannot resend OTP on every Query signal.
  53. # A fresh login/session permits another operator-assisted attempt.
  54. preparation_key = (generation, tab_id, route.routing_key)
  55. with _OTP_INPUT_LOCK:
  56. if getattr(plugin, "_manual_preparation_attempt", None) == preparation_key:
  57. raise PermissionDeniedError("Italy preparation failed; restore the session before retrying")
  58. current(booking_path)
  59. script = preparation.guarded_preflight_script(route, booking_path)
  60. check_form = lambda: current(booking_path)
  61. # Both roles must pass the same form before entering Calendar. Reuse
  62. # one bounded recovery across both stages; prepared scans skip this path.
  63. recovery = ItalyTurnstileRecovery(page, check_current=check_form)
  64. plugin._log(f"Italy {role} Calendar preparation: reusing bounded Turnstile recovery.")
  65. preparation.wait_for_booking_preflight(page, script=script,
  66. check_current=check_form, wait_action=recovery)
  67. plugin._manual_preparation_attempt = preparation_key
  68. sent_at, sent_monotonic = None, None
  69. def send_otp():
  70. nonlocal sent_at, sent_monotonic
  71. if cloud:
  72. validate_cloud_otp_environment(route.mail, username)
  73. sent_at, sent_monotonic = utc_sent_at(), monotonic()
  74. click("#otp-send")
  75. def check_cloud_window():
  76. if cloud and (sent_monotonic is None or
  77. not 0 <= monotonic() - sent_monotonic < route.mail.expiry_seconds):
  78. raise CalendarGateError("Italy OTP local read window expired; no automatic resend")
  79. packet = listen_once(page, target=preparation.OTP_PATH, method="GET", timeout=30,
  80. action=send_otp)
  81. packet_current(packet)
  82. preparation.validate_otp_packet(packet, service_id=route.service_id)
  83. current(booking_path)
  84. if cloud:
  85. check_cloud_window()
  86. plugin._log(f"Italy {role} OTP sent; waiting for the authorized mailbox (one read attempt).")
  87. otp = fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
  88. else:
  89. plugin._log(f"Italy {role} OTP sent; enter the code in this terminal.")
  90. otp = preparation._read_manual_otp()
  91. try:
  92. pattern = r"[0-9]{6}" if cloud else r"[0-9]{4,12}"
  93. if not isinstance(otp, str) or re.fullmatch(pattern, otp) is None:
  94. raise CalendarGateError("Italy OTP format rejected")
  95. current(booking_path)
  96. check_cloud_window()
  97. try:
  98. preparation._enter_otp(plugin, otp)
  99. except Exception:
  100. if cloud:
  101. # Browser transport exceptions may contain typed values.
  102. raise CalendarGateError("Italy automatic OTP DOM write verification failed") from None
  103. raise
  104. if cloud:
  105. plugin._log("Italy automatic OTP DOM write verified; continuing to Calendar.")
  106. finally:
  107. del otp
  108. preparation.wait_for_booking_preflight(
  109. page, script=script, stage=preparation.BookingPreflightStage.AFTER_OTP_SEND,
  110. check_current=check_form, wait_action=recovery,
  111. )
  112. check_cloud_window()
  113. try:
  114. page.set.auto_handle_alert(accept=True)
  115. packet = listen_once(page, target=booking_path, method="POST", timeout=30,
  116. action=lambda: click("#btnAvanti"))
  117. packet_current(packet)
  118. preparation._wait_for_calendar(page)
  119. current(CALENDAR_PATH)
  120. preparation.validate_avanti_packet(packet, booking_path=booking_path, final_page_url=page.url)
  121. finally:
  122. page.set.auto_handle_alert(on_off=False)
  123. guard_calendar(page)
  124. wait_for_calendar_service(page, session_is_current=lambda: current(CALENDAR_PATH) is None)
  125. if role == "query":
  126. plugin._record_calendar_query_prepared_route(route)
  127. else:
  128. plugin._record_calendar_book_prepared_route(route)
  129. plugin._manual_preparation_attempt = None
  130. def prepare_query_if_needed(plugin, apt_type):
  131. """Return a negative entry result, or prepare and let Query scan real dates."""
  132. if same_origin_path(plugin.page.url)[0] == CALENDAR_PATH:
  133. return None # Existing Query continuity checks remain authoritative.
  134. route = plugin._resolve_route(apt_type)
  135. entry = plugin._query_once(apt_type, query_mode="services_probe")
  136. if not entry.success:
  137. return entry
  138. plugin._clear_calendar_query_state()
  139. prepare_calendar(plugin, route, role="query")
  140. return None
  141. def book(plugin, slot_info, user_inputs):
  142. """Applicant-owned Calendar → existing pre-final adapter → standard result."""
  143. if plugin._book_final_configuration_valid() is not True:
  144. raise PermissionDeniedError("Italy final submission configuration is invalid")
  145. if not isinstance(user_inputs, dict) or not isinstance(user_inputs.get("username"), str):
  146. raise BizLogicError("Italy Book requires the applicant username")
  147. username = user_inputs["username"].strip().casefold()
  148. if (not username or username != plugin.config.account.username.strip().casefold()
  149. or plugin.free_config.get("query_mode", "services_probe") == "calendar"
  150. or getattr(plugin, "_calendar_query_route_key", None) is not None):
  151. raise BizLogicError("Italy Book requires a separate applicant Session, not a Query Session")
  152. route = plugin._resolve_route(slot_info.apt_type)
  153. attempt = getattr(plugin, "_production_final_attempt", None)
  154. if attempt is not None and attempt.state not in {"blocked", "rejected"}:
  155. # The same task may retry success reporting, but must never submit twice.
  156. result = getattr(plugin, "_production_book_result", None)
  157. if (attempt.state == "confirmed" and result is not None
  158. and attempt.target.applicant == username and attempt.target.routing_key == route.routing_key):
  159. return result
  160. raise FinalOutcomeUnknown()
  161. if same_origin_path(plugin.page.url)[0] != CALENDAR_PATH:
  162. entry = plugin._book_discovery_or_prepared(slot_info, user_inputs)
  163. if entry.label != "booking-form-ready-before-avanti":
  164. return entry
  165. prepare_calendar(plugin, route, role="book")
  166. elif plugin._calendar_book_context_matches(route, username):
  167. # Refresh inventory on the next signal after a definite negative result.
  168. plugin._calendar_book_attempted = False
  169. result = plugin._book_discovery_or_prepared(slot_info, user_inputs)
  170. if plugin.last_booking_precommit is None or plugin.free_config.get("final_submit_enabled") is not True:
  171. return result
  172. return submit_final(plugin, route)
  173. def submit_final(plugin, route, *, request_audit: preparation.CalendarRequestAudit | None = None):
  174. """Reuse native submission and attribution with one audit per page.
  175. A caller observing the whole workflow may lend its live audit. Ownership
  176. stays with that caller; standalone production calls own their audit as
  177. before. Neither path replaces callbacks or interrupts request coverage.
  178. """
  179. port = FinalReceiptReadPort(plugin, route)
  180. owns_audit = request_audit is None
  181. audit = preparation.CalendarRequestAudit(plugin.page, include_time_slots=True) if owns_audit else request_audit
  182. if owns_audit:
  183. audit.start()
  184. else:
  185. audit.require_active_on(plugin.page)
  186. if "timeSlotRequests" not in audit.snapshot():
  187. raise CalendarGateError("Final request audit must include time slots")
  188. try:
  189. before = audit.settled_snapshot()
  190. def submit():
  191. native = NativeFinalSubmitter(plugin.page, port.target, port.session_is_current)
  192. signal = native()
  193. after = audit.settled_snapshot()
  194. if (after["finalRequests"] - before["finalRequests"] == 1
  195. and all(after[key] == before[key] for key in before if key != "finalRequests")
  196. and isinstance(native.submitted_selection, VerifiedSubmission)):
  197. port.record_submission(native.submitted_selection)
  198. return signal
  199. attempt = FinalBookingAttempt(port.target, read_reservations=port, submit_native=submit,
  200. session_is_current=port.session_is_current)
  201. plugin._production_final_attempt = attempt
  202. result = attempt.execute(enabled=True)
  203. plugin._production_book_result = result if result.success else None
  204. return result
  205. finally:
  206. # A diagnostic teardown failure must not turn a verified success into a
  207. # generic booking failure (and a second real booking on the next signal).
  208. if owns_audit:
  209. try:
  210. audit.stop()
  211. except Exception:
  212. plugin._log("Italy passive request audit cleanup failed; session needs cleanup.")