ita_final_read_port.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """Read-port adapter shared by production Book and local final validation.
  2. Preserves the applicant Calendar in its original tab. Reads existing receipts in
  3. an owned background tab of the SAME browser/context. Baselines allow only empty
  4. or cancelled history. A new confirmed receipt may bind to a verified native POST;
  5. observed receipt fields remain distinct from submission evidence.
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import json
  10. import threading
  11. import time
  12. from dataclasses import dataclass, field
  13. from uuid import uuid4
  14. from urllib.parse import parse_qsl
  15. from plugins.ita_booking_final import (
  16. FinalBookingError, FinalTarget, ReservationRecord, ReservationSnapshot, ReservationState, VerifiedSubmission,
  17. )
  18. from plugins.ita_calendar_query import CALENDAR_PATH, same_origin_path
  19. from plugins.ita_protocol import ItaCapability, ItaRouteConfig, PrecommitApproval
  20. from plugins.ita_reservation import read_reservation_detail, read_reservation_listing
  21. LIST_URL = "https://prenotami.esteri.it/Reservation"
  22. MAX_DETAIL_READS = 20
  23. @dataclass(frozen=True, repr=False)
  24. class ReceiptObservation:
  25. """Bound display evidence only; UNKNOWN is never promoted to success."""
  26. records: tuple = field(repr=False) # (verified list row, matching detail)
  27. def _require(condition, reason):
  28. if condition is not True:
  29. raise FinalBookingError(reason)
  30. def _cancelled_record(row, detail) -> ReservationRecord:
  31. _require(row.state is ReservationState.CANCELLED and detail.state is ReservationState.CANCELLED and
  32. detail.status_code == "3" and all(getattr(row, field) == getattr(detail, field) for field in (
  33. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  34. "Italy cancelled receipt is not verified")
  35. # Equality of fingerprints preserves changes to fields absent from the final
  36. # model (office, displayed service, booking type). It is NOT identity proof.
  37. facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
  38. detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
  39. digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
  40. return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.CANCELLED,
  41. appointment_time=detail.appointment_time, receipt_fingerprint=digest)
  42. def _confirmed_record(row, detail, submission: VerifiedSubmission) -> ReservationRecord:
  43. target, slot = submission.target, submission.target.approval.candidate
  44. _require(row.state is ReservationState.ACTIVE and detail.state is ReservationState.ACTIVE and
  45. detail.status_code == "2" and detail.booking_type == "Prenotazione Singola" and
  46. isinstance(target.service_name, str) and detail.service_name == target.service_name and
  47. detail.day == slot.day and slot.time_label[:5] <= detail.appointment_time <= slot.time_label[-5:] and
  48. all(getattr(row, key) == getattr(detail, key) for key in (
  49. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  50. "Italy confirmed receipt does not match the submitted selection")
  51. facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
  52. detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
  53. digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
  54. # The website receipt supplies neither service_id nor the selected interval.
  55. # Keep them None; the separate evidence explicitly identifies the native POST.
  56. return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.ACTIVE,
  57. appointment_time=detail.appointment_time, receipt_fingerprint=digest,
  58. submission=submission)
  59. class FinalReceiptReadPort:
  60. """Capture an existing applicant Book precommit, then read fresh snapshots.
  61. Uses the plugin's established session/route checks, not a caller-supplied
  62. username assertion. Constructor does no navigation. Calling the port reads
  63. only; it never touches final buttons, rebuilds calendars or generates OTP.
  64. The owning Book workflow must serialize this with other browser work.
  65. """
  66. def __init__(self, plugin, route: ItaRouteConfig, *, observe_tab=None):
  67. try:
  68. _require(isinstance(route, ItaRouteConfig) and
  69. route.capability is ItaCapability.SINGLE_SCHENGEN_TOURISM,
  70. "Italy final read route is invalid")
  71. self._plugin, self._route = plugin, route
  72. _require(observe_tab is None or callable(observe_tab), "Italy receipt observer is invalid")
  73. self._observe_tab = observe_tab
  74. self._page = plugin.page
  75. self._browser = self._page.browser
  76. self._browser_id = self._browser.id
  77. self._generation = plugin.session_create_time
  78. self._prepared = plugin._calendar_book_prepared_context
  79. self._approval = plugin.last_booking_precommit
  80. self._username = plugin.config.account.username.strip().casefold()
  81. _require(isinstance(self._approval, PrecommitApproval) and
  82. isinstance(self._prepared, tuple) and len(self._prepared) == 7 and
  83. isinstance(self._browser_id, str) and bool(self._browser_id) and
  84. same_origin_path(self._page.url)[0] == CALENDAR_PATH,
  85. "Italy final read requires the current Book precommit")
  86. _, calendar_url = same_origin_path(self._page.url)
  87. names = [value for key, value in parse_qsl(calendar_url.query, keep_blank_values=True)
  88. if key == "selectedService"]
  89. service_name = names[0] if len(names) == 1 and names[0] else None
  90. self._target = FinalTarget(self._username, uuid4().hex, self._page.tab_id,
  91. route.routing_key, str(route.service_id), self._prepared[5], self._approval,
  92. service_name=service_name)
  93. self._lock = threading.Lock()
  94. self._unusable = False
  95. self._baseline = None
  96. self._submission = None
  97. _require(self.session_is_current(), "Italy final read Session is not current")
  98. except Exception:
  99. raise FinalBookingError("Italy final read context could not be captured") from None
  100. @property
  101. def target(self):
  102. return self._target
  103. def session_is_current(self) -> bool:
  104. try:
  105. p = self._plugin
  106. same_origin_path(self._page.url)
  107. return (not self._unusable and p.page is self._page and self._page.browser is self._browser and
  108. self._browser.id == self._browser_id and self._page.tab_id == self._target.tab_id and
  109. p.session_create_time == self._generation and p.is_healthy is True and
  110. p.last_booking_precommit is self._approval and
  111. p._calendar_book_prepared_context == self._prepared and
  112. p.config.account.username.strip().casefold() == self._username and
  113. p._calendar_book_context_matches(self._route, self._username) is True)
  114. except Exception:
  115. return False
  116. def __call__(self) -> ReservationSnapshot:
  117. snapshot = self._read(observation=False)
  118. if self._submission is None:
  119. self._baseline = snapshot
  120. return snapshot
  121. def record_submission(self, submission: VerifiedSubmission) -> None:
  122. """Called only after a matched native POST and one-request audit."""
  123. _require(self.session_is_current() and self._baseline is not None and self._submission is None and
  124. isinstance(submission, VerifiedSubmission) and submission.target == self.target and
  125. self.target.service_name is not None, "Italy submission binding is not current")
  126. self._submission = submission
  127. def observe_receipts(self) -> ReceiptObservation:
  128. """Read unknown status text for controlled discovery, NOT reconciliation."""
  129. return self._read(observation=True)
  130. def _read(self, *, observation: bool):
  131. if not self._lock.acquire(blocking=False):
  132. raise FinalBookingError("Italy receipt read is already running")
  133. receipt_page = None
  134. finish_observation = None
  135. close_failed = False
  136. cleanup_interrupt = None
  137. try:
  138. _require(self.session_is_current(), "Italy final read Session changed")
  139. origin = (self._page.url, self._page.tab_id)
  140. candidate = self._browser.new_tab(background=True, new_context=False)
  141. # Only close a separately identified tab created by our own browser.
  142. # A broken factory returning the original/foreign page is not owned.
  143. _require(candidate is not self._page and candidate.browser is self._browser and
  144. isinstance(candidate.tab_id, str) and bool(candidate.tab_id) and
  145. candidate.tab_id != self._target.tab_id, "Italy receipt tab ownership is unverified")
  146. receipt_page, receipt_tab = candidate, candidate.tab_id
  147. if self._observe_tab is not None:
  148. finish_observation = self._observe_tab(receipt_page)
  149. _require(callable(finish_observation), "Italy receipt observer did not start")
  150. def context():
  151. _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin and
  152. receipt_page.browser is self._browser and receipt_page.tab_id == receipt_tab,
  153. "Italy receipt read context changed")
  154. def navigate(url):
  155. context()
  156. _require(receipt_page.get(url, retry=0, timeout=30) is not False,
  157. "Italy receipt navigation failed")
  158. context()
  159. same_origin_path(receipt_page.url)
  160. _require(receipt_page.url == url, "Italy receipt navigation was redirected")
  161. navigate(LIST_URL)
  162. before = read_reservation_listing(receipt_page)
  163. context()
  164. _require(before.waitlist_count == 0 and len(before.rows) <= MAX_DETAIL_READS,
  165. "Italy receipt coverage exceeds supported verification")
  166. if not observation and self._submission is None:
  167. _require(all(row.state is ReservationState.CANCELLED for row in before.rows),
  168. "Italy live receipt attribution is not verified")
  169. records = []
  170. for row in before.rows:
  171. # Only actual links accepted by the established listing parser.
  172. navigate(row.detail_url)
  173. detail = read_reservation_detail(receipt_page)
  174. context()
  175. _require(all(getattr(row, key) == getattr(detail, key) for key in (
  176. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  177. "Italy observed receipt does not match its list row")
  178. if observation:
  179. records.append((row, detail))
  180. elif row.state is ReservationState.CANCELLED:
  181. records.append(_cancelled_record(row, detail))
  182. else:
  183. _require(self._submission is not None and self._baseline is not None and
  184. row.reference not in {r.reference for r in self._baseline.records},
  185. "Italy receipt is not new to this submission")
  186. records.append(_confirmed_record(row, detail, self._submission))
  187. navigate(LIST_URL)
  188. after = read_reservation_listing(receipt_page)
  189. context()
  190. _require({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and
  191. before.waitlist_count == after.waitlist_count, "Italy receipt history changed during read")
  192. snapshot = (ReceiptObservation(tuple(records)) if observation else
  193. ReservationSnapshot(self._target.applicant, self._target.session_key,
  194. time.monotonic(), True, tuple(records)))
  195. except Exception:
  196. raise FinalBookingError("Italy bound receipt read could not be verified") from None
  197. finally:
  198. if callable(finish_observation):
  199. try:
  200. finish_observation()
  201. except BaseException as exc:
  202. self._unusable = True
  203. if isinstance(exc, Exception):
  204. close_failed = True
  205. else:
  206. cleanup_interrupt = exc
  207. if receipt_page is not None:
  208. try:
  209. receipt_page.close()
  210. except BaseException as exc:
  211. # Do not trust a later read after losing control of an owned tab.
  212. self._unusable = True
  213. if isinstance(exc, Exception):
  214. close_failed = True
  215. else:
  216. cleanup_interrupt = exc
  217. self._lock.release()
  218. if cleanup_interrupt is not None:
  219. raise cleanup_interrupt
  220. if close_failed:
  221. raise FinalBookingError("Italy owned receipt tab cleanup failed") from None
  222. _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin,
  223. "Italy final read context changed during cleanup")
  224. return snapshot