ita_plugin.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. """Prenot@Mi Query/Book adapter; Italy-specific production code stays here."""
  2. from __future__ import annotations
  3. import html
  4. import json
  5. import os
  6. import random
  7. import re
  8. import sys
  9. import time
  10. import uuid
  11. from dataclasses import asdict, dataclass, field
  12. from datetime import date, datetime, time as datetime_time, timezone
  13. from enum import Enum
  14. from threading import Lock
  15. from typing import Any, Mapping, Sequence
  16. from urllib.parse import urljoin, urlparse
  17. from DrissionPage import ChromiumPage
  18. import vs_plg as _ita_host
  19. from vs_plg import IVSPlg
  20. from vs_types import (
  21. AvailabilityStatus, BizLogicError, NotFoundError,
  22. DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
  23. SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
  24. )
  25. from toolkit.vs_cloud_api import VSCloudApi
  26. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  27. from utils.flow_engine import BaseFlow, done, guard, on
  28. from utils.keyboard import HumanKeyboard
  29. from utils.mouse import HumanMouse
  30. from utils.plugin_utils import (
  31. cleanup_browser_workspace, filter_dates_in_range, init_chromium_options,
  32. perform_browser_fetch,
  33. )
  34. MAX_PROTOCOL_ITEMS = 512
  35. MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
  36. MAX_LOOKAHEAD_MONTHS = 120
  37. PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
  38. _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  39. _OTP_PATTERN = re.compile(r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)", re.I)
  40. class ItaProtocolError(ValueError):
  41. def __init__(self, code: str, message: str = "rejected", *, path: str = ""):
  42. self.code, self.path = code, path
  43. super().__init__(f"Italy protocol error [{code}]" + (f" at {path}" if path else "") + f": {message}")
  44. class ItaCapability(str, Enum):
  45. SERVICES_PROBE_ONLY = "services_probe_only"
  46. SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
  47. @dataclass(frozen=True, slots=True)
  48. class FormControlConfig:
  49. control_id: str
  50. value: str
  51. labels: tuple[str, ...]
  52. @dataclass(frozen=True, slots=True)
  53. class OtpMailConfig:
  54. authorization_email: str | None = field(default=None, repr=False)
  55. subject_keywords: str = "OTP Code"
  56. body_keywords: str = "OTP Code:"
  57. expiry_seconds: int = 300
  58. authorization_source: str = "configured"
  59. def __post_init__(self):
  60. if self.authorization_source not in {"account", "configured"}:
  61. raise ItaProtocolError("otp_authorization_source_invalid")
  62. if self.authorization_source == "account" and self.authorization_email is not None:
  63. raise ItaProtocolError("otp_authorization_source_conflict")
  64. if self.authorization_source == "configured":
  65. self.mailbox_for("")
  66. if type(self.expiry_seconds) is not int or not 1 <= self.expiry_seconds <= 300:
  67. raise ItaProtocolError("otp_expiry_invalid")
  68. if (self.subject_keywords, self.body_keywords) != ("OTP Code", "OTP Code:"):
  69. raise ItaProtocolError("otp_filter_invalid")
  70. def mailbox_for(self, account_email: str) -> str:
  71. value = account_email if self.authorization_source == "account" else self.authorization_email
  72. if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
  73. raise ItaProtocolError("otp_authorization_email_invalid", path="mail.authorization_email")
  74. return value.strip()
  75. @dataclass(frozen=True, slots=True)
  76. class ItaRouteConfig:
  77. routing_key: str
  78. service_id: int
  79. capability: ItaCapability
  80. lookahead_months: int = 0
  81. booking_type: FormControlConfig | None = None
  82. purpose: FormControlConfig | None = None
  83. mail: OtpMailConfig | None = None
  84. @dataclass(frozen=True, slots=True)
  85. class CalendarDay:
  86. day: date
  87. slots_free: int
  88. slots_remaining: int
  89. @property
  90. def is_available(self):
  91. return self.slots_free > 0
  92. @dataclass(frozen=True, slots=True)
  93. class SlotCandidate(CalendarDay):
  94. start_time: datetime_time
  95. end_time: datetime_time
  96. daily_calendar_id: str = field(repr=False)
  97. @property
  98. def time_label(self):
  99. return f"{self.start_time:%H:%M} - {self.end_time:%H:%M}"
  100. def _positive_int(value, path, maximum=None):
  101. if type(value) is not int or value <= 0:
  102. raise ItaProtocolError("positive_integer_required", path=path)
  103. if maximum is not None and value > maximum:
  104. raise ItaProtocolError("lookahead_too_large", path=path)
  105. return value
  106. def _mapping(value, path):
  107. if not isinstance(value, Mapping):
  108. raise ItaProtocolError("mapping_required", path=path)
  109. return value
  110. def _text(value, path):
  111. if not isinstance(value, str) or not value.strip():
  112. raise ItaProtocolError("string_required", path=path)
  113. return value.strip()
  114. def _control(form, prefix, path):
  115. labels = form.get(f"{prefix}_labels")
  116. if isinstance(labels, (str, bytes)) or not isinstance(labels, Sequence) or not labels:
  117. raise ItaProtocolError("labels_required", path=path)
  118. labels = tuple(_text(value, path) for value in labels)
  119. if len(set(labels)) != len(labels):
  120. raise ItaProtocolError("labels_duplicate", path=path)
  121. return FormControlConfig(
  122. _text(form.get(f"{prefix}_control_id"), path),
  123. _text(form.get(f"{prefix}_value"), path),
  124. labels,
  125. )
  126. def resolve_route_config(configs: Mapping[str, Any], routing_key: str) -> ItaRouteConfig:
  127. configs, key = _mapping(configs, "apt_configs"), _text(routing_key, "routing_key")
  128. if key not in configs:
  129. raise ItaProtocolError("route_missing", path="apt_configs")
  130. raw = _mapping(configs[key], key)
  131. capability_name = _text(raw.get("capability"), f"{key}.capability")
  132. try:
  133. capability = ItaCapability(capability_name)
  134. except ValueError:
  135. raise ItaProtocolError("capability_unsupported", path=f"{key}.capability") from None
  136. service = _positive_int(raw.get("service_id"), f"{key}.service_id")
  137. if capability is ItaCapability.SERVICES_PROBE_ONLY:
  138. return ItaRouteConfig(key, service, capability)
  139. form = _mapping(raw.get("form"), f"{key}.form")
  140. scan = _mapping(raw.get("calendar_scan"), f"{key}.calendar_scan")
  141. mail_raw = raw.get("mail")
  142. mail = None
  143. if mail_raw is not None:
  144. mail_raw = _mapping(mail_raw, f"{key}.mail")
  145. if str(mail_raw.get("sender", PRENOTAMI_OTP_SENDER)).strip().casefold() != PRENOTAMI_OTP_SENDER:
  146. raise ItaProtocolError("otp_sender_not_allowlisted", path=f"{key}.mail.sender")
  147. source = mail_raw.get("authorization_source", "configured")
  148. mail = OtpMailConfig(
  149. mail_raw.get("authorization_email"),
  150. mail_raw.get("subject_keywords", "OTP Code"),
  151. mail_raw.get("body_keywords", "OTP Code:"),
  152. mail_raw.get("expiry_seconds", 300), source,
  153. )
  154. return ItaRouteConfig(
  155. key, service, capability,
  156. _positive_int(scan.get("lookahead_months"), f"{key}.calendar_scan", MAX_LOOKAHEAD_MONTHS),
  157. _control(form, "booking_type", f"{key}.form"),
  158. _control(form, "purpose", f"{key}.form"),
  159. mail,
  160. )
  161. def decode_double_json_array(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
  162. if not isinstance(payload, str) or not payload:
  163. raise ItaProtocolError("payload_type")
  164. if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
  165. raise ItaProtocolError("payload_too_large")
  166. if type(max_items) is not int or max_items <= 0:
  167. raise ItaProtocolError("max_items_invalid")
  168. try:
  169. inner = json.loads(payload)
  170. except json.JSONDecodeError as exc:
  171. raise ItaProtocolError("outer_json_invalid") from exc
  172. if not isinstance(inner, str):
  173. raise ItaProtocolError("payload_layer_count")
  174. try:
  175. records = json.loads(inner)
  176. except json.JSONDecodeError as exc:
  177. raise ItaProtocolError("inner_json_invalid") from exc
  178. if not isinstance(records, list):
  179. raise ItaProtocolError("payload_layer_count")
  180. if len(records) > max_items:
  181. raise ItaProtocolError("item_limit_exceeded")
  182. if not all(isinstance(item, Mapping) for item in records):
  183. raise ItaProtocolError("item_type")
  184. return tuple(records)
  185. def _site_date(value, path):
  186. if not isinstance(value, str) or not re.fullmatch(r"\d{2}/\d{2}/\d{4} 00:00:00", value):
  187. raise ItaProtocolError("date_format", path=path)
  188. try:
  189. return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
  190. except ValueError as exc:
  191. raise ItaProtocolError("date_invalid", path=path) from exc
  192. def _integer(item, key, path):
  193. if key not in item:
  194. raise ItaProtocolError("field_missing", path=f"{path}.{key}")
  195. if type(item[key]) is not int:
  196. raise ItaProtocolError("integer_required", path=f"{path}.{key}")
  197. return item[key]
  198. def _clock(value, path):
  199. value = _mapping(value, path)
  200. parts = [_integer(value, key, path) for key in (
  201. "Hours", "Minutes", "Seconds", "Milliseconds")]
  202. if parts[2] or parts[3]:
  203. raise ItaProtocolError("time_precision", path=path)
  204. try:
  205. return datetime_time(parts[0], parts[1])
  206. except ValueError as exc:
  207. raise ItaProtocolError("time_invalid", path=path) from exc
  208. def _parse_calendar_items(payload, time_slots=False, max_items=MAX_PROTOCOL_ITEMS):
  209. records, identities, daily_ids = [], set(), set()
  210. for index, item in enumerate(decode_double_json_array(payload, max_items=max_items)):
  211. path = f"{'time_slots' if time_slots else 'availability'}[{index}]"
  212. free, remaining = _integer(item, "SlotLiberi", path), _integer(item, "SlotRimanenti", path)
  213. if not ((free > 0 and remaining >= 0) or (free == 0 and remaining < 0)):
  214. raise ItaProtocolError("inventory_conflict", path=path)
  215. day = _site_date(item.get("Data" if time_slots else "DateLibere"), path)
  216. if time_slots:
  217. start = _clock(item.get("OrarioInizioFascia"), f"{path}.OrarioInizioFascia")
  218. end = _clock(item.get("OrarioFineFascia"), f"{path}.OrarioFineFascia")
  219. if start >= end:
  220. raise ItaProtocolError("time_range_invalid", path=path)
  221. daily_id = _integer(item, "IDCalendarioServizioGiornaliero", path)
  222. if daily_id <= 0:
  223. raise ItaProtocolError("positive_integer_required", path=path)
  224. if daily_id in daily_ids:
  225. raise ItaProtocolError("duplicate_daily_id", path=path)
  226. daily_ids.add(daily_id)
  227. record = SlotCandidate(day, free, remaining, start, end, str(daily_id))
  228. identity = day, start, end
  229. else:
  230. record, identity = CalendarDay(day, free, remaining), day
  231. if identity in identities:
  232. raise ItaProtocolError("duplicate_time_range" if time_slots else "duplicate_calendar_day")
  233. identities.add(identity)
  234. records.append(record)
  235. return tuple(sorted(records, key=lambda item: (item.day, getattr(item, "start_time", datetime_time.min))))
  236. def parse_calendar_availability(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
  237. return _parse_calendar_items(payload, max_items=max_items)
  238. def parse_time_slots(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
  239. return _parse_calendar_items(payload, time_slots=True, max_items=max_items)
  240. def _available_inventory(items, *, start_day=None, end_day=None):
  241. if start_day and end_day and start_day > end_day:
  242. raise ItaProtocolError("date_range_invalid")
  243. allowed = set(filter_dates_in_range(
  244. [item.day.isoformat() for item in items],
  245. (start_day or date.min).isoformat(), (end_day or date.max).isoformat(),
  246. shuffle=False,
  247. ))
  248. return tuple(item for item in sorted(
  249. (item for item in items if item.is_available and item.day.isoformat() in allowed),
  250. key=lambda item: (item.day, getattr(item, "start_time", datetime_time.min)),
  251. ))
  252. available_calendar_days = available_slot_candidates = _available_inventory
  253. def parse_otp_body(body: str, *, max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS):
  254. if not isinstance(body, str) or not body.strip():
  255. raise ItaProtocolError("otp_body_invalid")
  256. if len(body) > max_chars:
  257. raise ItaProtocolError("otp_body_too_large")
  258. values = set(_OTP_PATTERN.findall(html.unescape(re.sub(r"<[^>]*>", " ", body))))
  259. if len(values) != 1:
  260. raise ItaProtocolError("otp_not_found" if not values else "otp_ambiguous")
  261. return values.pop()
  262. def month_starts(anchor_day: date, lookahead_months: int):
  263. months = _positive_int(lookahead_months, "lookahead_months", MAX_LOOKAHEAD_MONTHS)
  264. return tuple(date(anchor_day.year + (anchor_day.month - 1 + i) // 12,
  265. (anchor_day.month - 1 + i) % 12 + 1, 1) for i in range(months))
  266. CALENDAR_PATH = "/BookingCalendar"
  267. AVAILABILITY_PATH = "/BookingCalendar/RetrieveCalendarAvailability"
  268. TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
  269. DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
  270. # Compatibility names for older diagnostics/tests. Runtime code raises the
  271. # framework exceptions directly so the host can apply its standard policy.
  272. CalendarGateError = BizLogicError
  273. CalendarAuthenticationExpiredError = SessionExpiredOrInvalidError
  274. CalendarRateLimitedError = RateLimiteddError
  275. CalendarAccessDeniedError = PermissionDeniedError
  276. CalendarTransientError = BizLogicError
  277. CalendarBookError = BizLogicError
  278. def same_origin_path(raw_url):
  279. try:
  280. parsed = urlparse(str(raw_url or ""))
  281. port = parsed.port
  282. except ValueError:
  283. raise BizLogicError("Italy request left the expected origin") from None
  284. if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
  285. or port not in (None, 443)):
  286. raise BizLogicError("Italy request left the expected origin")
  287. return parsed.path
  288. CALENDAR_DOM_SCRIPT = r"""
  289. const [mode, serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
  290. const all = (selector, root = document) => Array.from(root.querySelectorAll(selector));
  291. const services = all('#idServizio'), timeline = all('.events a.selected[data-date]');
  292. const service = services.length === 1 ? services[0].value : '';
  293. const selectedDay = timeline.length === 1 ? timeline[0].dataset.date : '';
  294. if (mode === 'context') return {path: location.pathname, service, day: selectedDay};
  295. const contextReady = location.pathname === '/BookingCalendar' && service === serviceId;
  296. const links = all('.events a[data-date]').filter(item => item.dataset.date === day);
  297. const link = links.length === 1 ? links[0] : null;
  298. if (mode === 'date') {
  299. const candidateReady = Boolean(contextReady && link &&
  300. !link.classList.contains('notAvailableDay') && !link.classList.contains('disabled'));
  301. let selected = Boolean(candidateReady && link.classList.contains('selected')), clicked = false;
  302. if (shouldClick && candidateReady && !selected) { link.click(); clicked = true; }
  303. selected = Boolean(candidateReady && link.classList.contains('selected'));
  304. return {contextReady, candidateCount: links.length, candidateReady, selected, clicked};
  305. }
  306. const content = all('.events-content li.selected').find(item => item.dataset.date === day);
  307. const matches = content ? all('.fascia', content).filter(slot => {
  308. const input = slot.querySelector('#idHiddenFasciaServizio');
  309. return input && input.value === dailyId;
  310. }) : [];
  311. const slot = matches.length === 1 ? matches[0] : null, spans = slot ? slot.querySelectorAll('span') : [];
  312. const clean = value => String(value || '').replace(/\s+/g, ' ').trim();
  313. const candidateReady = Boolean(contextReady && slot && !slot.classList.contains('notAvailableFascia') &&
  314. spans.length === 2 && clean(spans[0].textContent) === timeLabel &&
  315. clean(spans[1].textContent) === `(${capacity})`);
  316. let selected = Boolean(candidateReady && slot.classList.contains('act')), clicked = false;
  317. if (shouldClick && candidateReady && !selected) { slot.click(); clicked = true; }
  318. selected = Boolean(candidateReady && slot.classList.contains('act'));
  319. return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
  320. """
  321. def _runtime_id(value):
  322. if value is None or isinstance(value, bool):
  323. raise BizLogicError("Italy Calendar service id is invalid")
  324. value = str(value).strip()
  325. if not re.fullmatch(r"[1-9]\d{0,127}", value):
  326. raise BizLogicError("Italy Calendar service id is invalid")
  327. return value
  328. def _request_day(value):
  329. try:
  330. return date.fromisoformat(str(value))
  331. except ValueError:
  332. raise BizLogicError("Italy Calendar date format changed") from None
  333. def read_calendar_context(page):
  334. if same_origin_path(page.url) != CALENDAR_PATH:
  335. raise BizLogicError("Italy Calendar page is not current")
  336. raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
  337. if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
  338. raise BizLogicError("Italy Calendar context is not ready")
  339. return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
  340. def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
  341. deadline = time.monotonic() + timeout
  342. while time.monotonic() < deadline:
  343. if session_is_current() is not True:
  344. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  345. try:
  346. service = read_calendar_context(page)[0]
  347. except BizLogicError:
  348. time.sleep(0.1)
  349. continue
  350. if expected_service and service != _runtime_id(expected_service):
  351. raise BizLogicError("Italy Calendar service changed")
  352. return service
  353. raise BizLogicError("Italy Calendar service did not initialize")
  354. def _calendar_post(page, path, payload, parser):
  355. response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
  356. status, host = response.status_code, urlparse(str(response.url or "")).hostname
  357. if host == "iam.esteri.it" or status == 401:
  358. raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
  359. if status == 403:
  360. raise PermissionDeniedError("Italy Calendar access denied")
  361. if status == 429:
  362. raise RateLimiteddError("Italy Calendar rate limited")
  363. if status in {0, 408, 502, 503, 504}:
  364. raise BizLogicError("Italy Calendar temporarily unavailable")
  365. if status != 200 or same_origin_path(response.url) != path:
  366. raise BizLogicError("Italy Calendar returned an unexpected response")
  367. try:
  368. return parser(response.text)
  369. except ItaProtocolError as exc:
  370. raise BizLogicError(f"Italy Calendar response rejected ({exc.code})") from exc
  371. def fetch_calendar_month(page, service, selected_day):
  372. selected = selected_day.strftime("%d/%m/%Y")
  373. return _calendar_post(
  374. page, AVAILABILITY_PATH,
  375. {"_Servizio": _runtime_id(service), "selectedDay": selected},
  376. parse_calendar_availability,
  377. )
  378. def fetch_calendar_slots(page, service, selected_day):
  379. slots = _calendar_post(
  380. page, TIME_SLOTS_PATH,
  381. {"selectedDay": selected_day.isoformat(), "idService": _runtime_id(service)},
  382. parse_time_slots,
  383. )
  384. if any(slot.day != selected_day for slot in slots):
  385. raise BizLogicError("Italy Calendar returned slots for another day")
  386. return slots
  387. def scan_until_first_available_month(
  388. page, *, lookahead_months, log=None,
  389. month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  390. ):
  391. service, anchor = read_calendar_context(page)
  392. scans = []
  393. for index, month in enumerate(month_starts(anchor, lookahead_months)):
  394. if index and month_click_interval_seconds:
  395. time.sleep(month_click_interval_seconds)
  396. days = fetch_calendar_month(page, service, month)
  397. scans.append(days)
  398. available = available_calendar_days(days)
  399. if log:
  400. log(f"Italy Calendar probe index={index} available={len(available)}")
  401. if available:
  402. break
  403. return tuple(scans)
  404. def click_next_month(page, *, timeout=10, diagnostic=None):
  405. control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
  406. if not control:
  407. raise NotFoundError("Italy Calendar next-month control is unavailable")
  408. control.click(by_js=True)
  409. def _snapshot(page, mode, service, day, candidate=None, click=False):
  410. candidate = candidate or SlotCandidate(day, 0, -1, datetime_time.min, datetime_time.min, "")
  411. raw = page.run_js(
  412. CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
  413. candidate.time_label, candidate.slots_free, click,
  414. )
  415. if not isinstance(raw, dict) or not raw.get("contextReady") or raw.get("candidateCount") != 1:
  416. raise BizLogicError("Italy Calendar selection context changed")
  417. return raw
  418. def verify_precommit_selection(page, *, runtime_service, candidate):
  419. raw = _snapshot(
  420. page, "slot", runtime_service, candidate.day, candidate, False)
  421. if not raw.get("candidateReady") or not raw.get("selected"):
  422. raise BizLogicError("Italy Calendar selected slot changed")
  423. return candidate
  424. def select_slot_before_final(
  425. page, *, target_day, days, slots, runtime_service,
  426. dom_timeout=5, session_is_current=None,
  427. ):
  428. inventory = [item for item in days if item.day == target_day and item.is_available]
  429. candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
  430. if not inventory or not candidates:
  431. return None
  432. candidate, deadline = candidates[0], time.monotonic() + dom_timeout
  433. _snapshot(page, "date", runtime_service, target_day, click=True)
  434. while time.monotonic() < deadline:
  435. if session_is_current and session_is_current() is not True:
  436. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  437. date_state = _snapshot(page, "date", runtime_service, target_day)
  438. slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
  439. if date_state.get("selected") and slot_state.get("candidateReady"):
  440. if not slot_state.get("selected"):
  441. _snapshot(page, "slot", runtime_service, target_day, candidate, True)
  442. return verify_precommit_selection(
  443. page, runtime_service=runtime_service, candidate=candidate)
  444. time.sleep(0.1)
  445. raise BizLogicError("Italy Calendar slot did not finish loading")
  446. def book_date_preferences(user_inputs):
  447. values = []
  448. for key, default in (("expected_start_date", "2000-01-01"),
  449. ("expected_end_date", "2100-01-01")):
  450. try:
  451. values.append(date.fromisoformat(user_inputs.get(key, default)))
  452. except (AttributeError, TypeError, ValueError):
  453. raise BizLogicError(f"Italy {key} must use YYYY-MM-DD") from None
  454. if values[0] > values[1]:
  455. raise BizLogicError("Italy date preference is inverted")
  456. return tuple(values)
  457. def _move_to_month(page, service, target, timeout):
  458. current = read_calendar_context(page)[1]
  459. while (current.year, current.month) < target:
  460. expected = (current.year + 1, 1) if current.month == 12 else (current.year, current.month + 1)
  461. click_next_month(page, timeout=timeout)
  462. deadline = time.monotonic() + timeout
  463. while time.monotonic() < deadline:
  464. actual_service, current = read_calendar_context(page)
  465. if actual_service != service:
  466. raise BizLogicError("Italy Calendar service changed")
  467. if (current.year, current.month) == expected:
  468. break
  469. time.sleep(0.1)
  470. else:
  471. raise BizLogicError("Italy Calendar month did not load")
  472. if (current.year, current.month) != target:
  473. raise BizLogicError("Italy Calendar cannot navigate backwards")
  474. def recheck_calendar_before_final(
  475. page, *, lookahead_months, start_day, end_day, session_is_current,
  476. month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  477. timeout=30, dom_timeout=5, log=None,
  478. ):
  479. service, anchor = read_calendar_context(page)
  480. for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
  481. if session_is_current() is not True:
  482. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  483. if index and month_click_interval_seconds:
  484. time.sleep(month_click_interval_seconds)
  485. inventory = fetch_calendar_month(page, service, month_start)
  486. days = available_calendar_days(inventory, start_day=start_day, end_day=end_day)
  487. selected_month = month_start.year, month_start.month
  488. if log:
  489. log(f"Italy Book Calendar month={month_start:%Y-%m} candidates={len(days)}")
  490. if days:
  491. _move_to_month(page, service, selected_month, timeout)
  492. for item in days:
  493. slots = fetch_calendar_slots(page, service, item.day)
  494. candidate = select_slot_before_final(
  495. page, target_day=item.day, days=inventory, slots=slots,
  496. runtime_service=service, dom_timeout=dom_timeout,
  497. session_is_current=session_is_current,
  498. )
  499. if candidate:
  500. return candidate
  501. if selected_month >= (end_day.year, end_day.month):
  502. break
  503. return None
  504. FINAL_PATH = "/BookingCalendar/InsertNewBooking"
  505. FINAL_FAILED_LABEL = "italy-final-failed"
  506. FINAL_ACCEPTED_LABEL = "italy-final-accepted"
  507. def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
  508. try:
  509. page = plugin.page
  510. username = plugin.config.account.username.strip().casefold()
  511. prepared = plugin._require_calendar_context(route, role="book", username=username)
  512. if (not username or not isinstance(slot, SlotCandidate)
  513. or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
  514. raise BizLogicError("Italy final context is not current")
  515. verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
  516. response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
  517. "idCalendarioGiornaliero": slot.daily_calendar_id,
  518. "selectedDay": slot.day.isoformat(),
  519. "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
  520. })
  521. data = response.json()
  522. if (response.status_code == 200 and same_origin_path(response.url) == FINAL_PATH
  523. and isinstance(data, dict) and not str(data.get("errorMessage", "")).strip()
  524. and isinstance(data.get("url"), str) and data["url"].strip()):
  525. same_origin_path(urljoin("https://prenotami.esteri.it", data["url"]))
  526. return VSBookResult(
  527. success=True,
  528. account=username,
  529. label=FINAL_ACCEPTED_LABEL,
  530. book_date=slot.day.isoformat(),
  531. book_time=slot.time_label,
  532. )
  533. except Exception as exc:
  534. plugin._log(f"Italy final submission failed: {type(exc).__name__}")
  535. # The next Booker signal must re-enter the form and obtain fresh IDs.
  536. plugin._reset_calendar_state()
  537. return VSBookResult(success=False, label=FINAL_FAILED_LABEL)
  538. _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
  539. _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", Lock())
  540. def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
  541. if not route.booking_type or not route.purpose:
  542. raise BizLogicError("Italy route is missing form controls")
  543. config = {"path": booking_path, "booking": asdict(route.booking_type),
  544. "purpose": asdict(route.purpose)}
  545. return f"""
  546. const cfg = {json.dumps(config, ensure_ascii=False)};
  547. const form = document.querySelector('#bookingForm');
  548. const norm = value => String(value || '').replace(/\\s+/g, ' ').trim().toLowerCase();
  549. function choose(item) {{
  550. const control = document.getElementById(item.control_id);
  551. const option = control && Array.from(control.options).find(value => value.value === item.value);
  552. if (!option || !item.labels.map(norm).includes(norm(option.textContent))) return false;
  553. if (control.value !== item.value) {{
  554. control.value = item.value;
  555. control.dispatchEvent(new Event('change', {{bubbles: true}}));
  556. }}
  557. return control.value === item.value;
  558. }}
  559. const booking = choose(cfg.booking), purpose = choose(cfg.purpose);
  560. const privacy = document.querySelector('#PrivacyCheck');
  561. if (privacy && !privacy.checked) privacy.click();
  562. const otp = document.querySelector('#otp-input'), send = document.querySelector('#otp-send');
  563. const avanti = document.querySelector('#btnAvanti');
  564. const token = document.querySelector('input[name="cf-turnstile-response"]');
  565. return {{
  566. formReady: Boolean(location.pathname === cfg.path && form && booking && purpose && privacy && privacy.checked),
  567. turnstileReady: Boolean(token && token.value),
  568. otpValuePresent: Boolean(otp && otp.value.trim()),
  569. otpSendEnabled: Boolean(send && !send.disabled),
  570. avantiEnabled: Boolean(avanti && !avanti.disabled),
  571. }};
  572. """
  573. def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
  574. if type(after_otp) is not bool or type(allow_pending) is not bool:
  575. raise BizLogicError("Italy booking preflight policy is invalid")
  576. if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
  577. "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
  578. raise BizLogicError("Italy booking form structure changed")
  579. if raw["otpValuePresent"] is not after_otp:
  580. raise BizLogicError("Italy booking OTP stage changed")
  581. ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
  582. raw["turnstileReady"] and raw["avantiEnabled"])
  583. if not allow_pending and not ready:
  584. raise BizLogicError("Italy booking verification is not ready")
  585. def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
  586. diagnostic=None, wait_action=None, check_current=None):
  587. deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
  588. while time.monotonic() < deadline:
  589. if check_current:
  590. check_current()
  591. raw = page.run_js(script)
  592. validate_booking_preflight(raw, after_otp=after_otp, allow_pending=True)
  593. form_ready = raw["formReady"] and (after_otp or raw["otpSendEnabled"])
  594. if form_ready and raw["turnstileReady"] and raw["avantiEnabled"]:
  595. return raw
  596. if form_ready and not raw["turnstileReady"] and attempts < 3:
  597. bypasser = bypasser or CloudflareBypasser(page, log=False)
  598. try:
  599. bypasser.click_verification_button(is_dfs=False)
  600. except Exception:
  601. pass
  602. attempts += 1
  603. time.sleep(1)
  604. reason = ("form_pending" if not raw or not raw["formReady"] else
  605. "otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
  606. "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
  607. raise BizLogicError(f"Italy booking verification timed out: {reason}")
  608. def _element_or_fail(page, selector):
  609. element = page.ele(selector, timeout=5)
  610. if not element:
  611. raise NotFoundError(f"Italy booking element is missing: {selector}")
  612. return element
  613. def _read_manual_otp():
  614. value = input("Italy booking OTP: ").strip()
  615. if not re.fullmatch(r"[0-9]{4,12}", value):
  616. raise BizLogicError("Italy OTP format rejected")
  617. return value
  618. def _enter_otp(plugin, otp):
  619. field = _element_or_fail(plugin.page, "#otp-input")
  620. plugin.mouse.human_click_ele(field)
  621. field.input(otp, clear=True)
  622. if field.run_js("return this.value === arguments[0];", otp) is not True:
  623. raise BizLogicError("Italy OTP write failed")
  624. def validate_cloud_otp_environment(mail_config, recipient):
  625. if not isinstance(mail_config, OtpMailConfig):
  626. raise BizLogicError("Italy OTP mail configuration is missing")
  627. if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
  628. raise BizLogicError("Italy OTP recipient is invalid")
  629. mail_config.mailbox_for(recipient)
  630. return recipient.strip()
  631. def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
  632. validate_cloud_otp_environment(mail_config, recipient)
  633. try:
  634. datetime.strptime(sent_at, _SENT_AT_FORMAT)
  635. except (TypeError, ValueError):
  636. raise BizLogicError("Italy OTP sent time is invalid") from None
  637. try:
  638. body = (api or VSCloudApi.Instance()).fetch_mail_content(
  639. email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
  640. subject_keywords="OTP Code", body_keywords="OTP Code:",
  641. sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
  642. )
  643. return parse_otp_body(body)
  644. except ItaProtocolError as exc:
  645. raise BizLogicError(f"Italy OTP body invalid ({exc.code})") from None
  646. except PermissionDeniedError:
  647. raise PermissionDeniedError("Italy OTP mailbox not permitted") from None
  648. except SessionExpiredOrInvalidError:
  649. raise SessionExpiredOrInvalidError("Italy OTP mailbox session expired") from None
  650. except RateLimiteddError:
  651. raise RateLimiteddError("Italy OTP mailbox rate limited") from None
  652. except NotFoundError:
  653. raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
  654. except BizLogicError as exc:
  655. status = re.search(r"\bHTTP Error (\d{3})\b", str(getattr(exc, "message", "")))
  656. if status and int(status.group(1)) == 404:
  657. raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
  658. if status and int(status.group(1)) in {408, 502, 503, 504}:
  659. raise BizLogicError("Italy OTP mailbox provider timed out") from None
  660. raise BizLogicError("Italy OTP mailbox read failed") from None
  661. except Exception:
  662. raise BizLogicError("Italy OTP mailbox read failed") from None
  663. def _wait_for_calendar(page, timeout=30):
  664. deadline = time.monotonic() + timeout
  665. while time.monotonic() < deadline:
  666. if urlparse(str(page.url or "")).path.rstrip("/") == CALENDAR_PATH:
  667. page.wait.doc_loaded()
  668. return
  669. time.sleep(0.25)
  670. raise BizLogicError("Italy AVANTI did not reach Calendar")
  671. def prepare_calendar(plugin, route, *, role):
  672. if role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM:
  673. raise BizLogicError("Italy Calendar preparation requires a tourism route")
  674. cloud = plugin.free_config.get("otp_mode") == "cloud"
  675. if not cloud and (plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty()):
  676. raise PermissionDeniedError("Italy Calendar requires automatic OTP or an attached terminal")
  677. username, page, booking_path = (
  678. plugin.config.account.username.strip().casefold(), plugin.page, plugin._booking_path(route))
  679. if cloud:
  680. validate_cloud_otp_environment(route.mail, username)
  681. def current(path):
  682. if plugin.page is not page or same_origin_path(page.url) != path:
  683. raise SessionExpiredOrInvalidError("Italy preparation page changed")
  684. def click(selector):
  685. current(booking_path)
  686. plugin.mouse.human_click_ele(_element_or_fail(page, selector))
  687. with _OTP_INPUT_LOCK:
  688. script = guarded_preflight_script(route, booking_path)
  689. wait_for_booking_preflight(page, script=script, check_current=lambda: current(booking_path))
  690. sent_at = datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
  691. click("#otp-send")
  692. plugin._log(f"Italy {role} OTP sent.")
  693. otp = (fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
  694. if cloud else _read_manual_otp())
  695. _enter_otp(plugin, otp)
  696. wait_for_booking_preflight(
  697. page, script=script, after_otp=True, check_current=lambda: current(booking_path))
  698. page.set.auto_handle_alert(accept=True)
  699. try:
  700. click("#btnAvanti")
  701. _wait_for_calendar(page)
  702. finally:
  703. page.set.auto_handle_alert(on_off=False)
  704. wait_for_calendar_service(
  705. page, session_is_current=lambda: plugin.page is page,
  706. expected_service=route.service_id,
  707. )
  708. plugin._record_calendar_prepared_route(route, role=role)
  709. BOOKING_RECHECK_NONE_AVAILABLE_LABEL = "no-availability-after-user-recheck"
  710. BOOKING_CALENDAR_PREFINAL_STOP_LABEL = "calendar-ready-before-final"
  711. RADWARE_VALIDATION_HOSTS = frozenset({"validate.perfdrive.com"})
  712. SERVICE_LINK_WAIT_SECONDS = 15
  713. SERVICES_PROBE_QUERY_MODE = "services_probe"
  714. CALENDAR_QUERY_MODE = "calendar"
  715. # Compatibility names retained for callers of older Italy diagnostics.
  716. ItaAuthenticationChallengeError = PermissionDeniedError
  717. ItaTargetServiceLinkMissingError = NotFoundError
  718. ItaCalendarTransientError = BizLogicError
  719. @dataclass(frozen=True, repr=False, eq=False)
  720. class _PreparedCalendar:
  721. username: str
  722. routing_key: str
  723. runtime_service: str
  724. tab_id: str
  725. role: str
  726. class ItaLoginFlow(BaseFlow):
  727. """Italy page rules on the host flow engine; never resubmit credentials."""
  728. def __init__(self, plugin):
  729. self.plugin = plugin
  730. self.entered = self.submitted = False
  731. super().__init__(plugin.page, interval=3, logger=plugin._log, max_stuck_cycles=None)
  732. def at(self, host, path):
  733. url = urlparse(self.page.url)
  734. return url.hostname == host and (url.path.rstrip("/") or "/") == path
  735. @guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
  736. def radware(self):
  737. raise PermissionDeniedError(
  738. "Italy authentication requires Radware browser validation; automatic retry is disabled")
  739. @guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
  740. urlparse(f.page.url).netloc.lower() not in {
  741. "prenotami.esteri.it", "iam.esteri.it", "prenotami.esteri.it:443", "iam.esteri.it:443"}, priority=2)
  742. def foreign_origin(self):
  743. raise BizLogicError("Italy authentication left the expected website")
  744. @guard(predicate=lambda f: any(value in f.page.html for value in (
  745. "Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
  746. def blocked(self):
  747. raise PermissionDeniedError("Italy authentication was blocked; automatic retry is disabled")
  748. @guard(predicate=lambda f: any(value in f.page.html for value in (
  749. "502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
  750. def server_error(self):
  751. if self.entered or self.submitted:
  752. raise BizLogicError("Italy authentication failed after login started; no resubmission")
  753. self.page.refresh()
  754. self.plugin._random_sleep(10, 15)
  755. @guard(title="just a moment", priority=5)
  756. @guard(title="cloudflare", priority=5)
  757. def verification_pending(self):
  758. self.log("Waiting for the website's human verification")
  759. time.sleep(5)
  760. @on(ele=".app-menu", predicate=lambda f: f.at("prenotami.esteri.it", "/UserArea") and
  761. bool(f.page.ele("@href=/Services", timeout=0.2)), priority=20)
  762. @done
  763. def authenticated(self):
  764. self.plugin._log("Successfully reached authenticated /UserArea.")
  765. self.plugin.session_create_time = time.time()
  766. self.plugin.is_healthy = True
  767. @on(ele="#pingid-button", predicate=lambda f: f.at("prenotami.esteri.it", "/") and not f.entered, priority=30)
  768. def enter(self):
  769. self.entered = True
  770. self.plugin.mouse.human_click_ele(self.page.ele("#pingid-button"))
  771. self.plugin._log("Redirecting to PingID...")
  772. self.plugin._random_sleep(3, 5)
  773. @on(ele="@name=callback_1", predicate=lambda f: f.at("iam.esteri.it", "/signin") and not f.submitted, priority=40)
  774. def credentials(self):
  775. username, password, submit = [self.page.ele(selector, timeout=0.2) for selector in
  776. ("@name=callback_1", "@name=callback_2", "tag:button@type=submit")]
  777. if not all((username, password, submit)):
  778. return # IAM can render its controls in separate updates.
  779. for label, element, value in (("username", username, self.plugin.config.account.username),
  780. ("password", password, self.plugin.config.account.password)):
  781. self.plugin._log(f"Entering {label}...")
  782. self.plugin.mouse.human_click_ele(element)
  783. element.input(value, clear=True)
  784. time.sleep(1)
  785. self.submitted = True
  786. self.plugin.mouse.human_click_ele(submit)
  787. self.plugin._log("Login form submitted. Waiting for dashboard to load...")
  788. self.plugin._random_sleep(5, 7)
  789. class ItaPlugin(IVSPlg):
  790. name = "ita_plugin"
  791. version = "1.0.2"
  792. description = "意大利 Prenot@Mi 查询与预约插件"
  793. def __init__(self, group_id):
  794. self.group_id = group_id
  795. self.config = None
  796. self.free_config = {}
  797. self.is_healthy = True
  798. self.logger = self.page = self.tunnel = None
  799. self.ita_url = "https://prenotami.esteri.it"
  800. self.instance_id = uuid.uuid4().hex[:8]
  801. self.root_workspace = os.path.abspath(
  802. os.path.join("data/temp_browser_data", f"{group_id}.{self.instance_id}"))
  803. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  804. os.makedirs(self.root_workspace, exist_ok=True)
  805. self.session_create_time = 0
  806. self._prepared_calendar = None
  807. def set_log(self, logger):
  808. self.logger = logger
  809. def _log(self, message):
  810. (self.logger or print)(f"[ItaPlugin] [{self.group_id}] {message}")
  811. def _random_sleep(self, minimum=30, maximum=60):
  812. seconds = random.uniform(minimum, maximum)
  813. self._log(f"Anti-Rate-Limit: Sleeping for {seconds:.2f} seconds...")
  814. time.sleep(seconds)
  815. def set_config(self, config):
  816. self.config, self.free_config = config, config.free_config or {}
  817. query_mode = self.free_config.get("query_mode", SERVICES_PROBE_QUERY_MODE)
  818. otp_mode = self.free_config.get("otp_mode")
  819. final = self.free_config.get("final_submit_enabled", False)
  820. if query_mode not in {SERVICES_PROBE_QUERY_MODE, CALENDAR_QUERY_MODE}:
  821. raise BizLogicError("Italy query_mode is invalid")
  822. if otp_mode not in {None, "manual", "cloud"}:
  823. raise BizLogicError("Italy otp_mode is invalid")
  824. if final is not False and not (
  825. final is True and otp_mode in {"manual", "cloud"}
  826. and query_mode == SERVICES_PROBE_QUERY_MODE):
  827. raise BizLogicError("Italy final submission configuration is invalid")
  828. self._prepared_calendar = None
  829. def _resolve_route(self, apt_type):
  830. try:
  831. return resolve_route_config(
  832. self.free_config.get("apt_configs", {}), apt_type.routing_key)
  833. except (AttributeError, ItaProtocolError) as exc:
  834. detail = getattr(exc, "code", type(exc).__name__)
  835. raise BizLogicError(f"Italy route configuration rejected: {detail}") from exc
  836. @staticmethod
  837. def _booking_path(route):
  838. return f"/Services/Booking/{route.service_id}"
  839. def _authenticated_path(self):
  840. host = urlparse(str(self.page.url or "")).hostname
  841. if host == "iam.esteri.it" or self.page.ele("#pingid-button", timeout=0.2):
  842. raise SessionExpiredOrInvalidError("Italy Session expired")
  843. return same_origin_path(self.page.url)
  844. def _reset_calendar_state(self):
  845. self._prepared_calendar = None
  846. def _calendar_context_matches(self, route, *, role, username=None):
  847. state = self._prepared_calendar
  848. try:
  849. account = self.config.account.username.strip().casefold()
  850. return (
  851. isinstance(state, _PreparedCalendar) and self.is_healthy and
  852. state.tab_id == self.page.tab_id and state.username == account and
  853. state.routing_key == route.routing_key and state.role == role and
  854. (username is None or username == account)
  855. )
  856. except Exception:
  857. return False
  858. def _record_calendar_prepared_route(self, route, *, role):
  859. try:
  860. self._prepared_calendar = _PreparedCalendar(
  861. self.config.account.username.strip().casefold(), route.routing_key,
  862. read_calendar_context(self.page)[0], self.page.tab_id, role)
  863. except Exception:
  864. self._prepared_calendar = None
  865. raise BizLogicError("Italy Calendar identity is unavailable") from None
  866. def _require_calendar_context(self, route, *, role, username=None):
  867. if not self._calendar_context_matches(route, role=role, username=username):
  868. raise BizLogicError("Italy Calendar Session changed")
  869. if read_calendar_context(self.page)[0] != self._prepared_calendar.runtime_service:
  870. raise BizLogicError("Italy Calendar service changed")
  871. return self._prepared_calendar
  872. def _invalidate_query_session(self):
  873. self.is_healthy = False
  874. self._prepared_calendar = None
  875. def keep_alive(self):
  876. pass
  877. def health_check(self):
  878. if not self.is_healthy or not self.page:
  879. return False
  880. try:
  881. alive = self.page.run_js("return 1;") == 1
  882. except Exception:
  883. alive = False
  884. expired = self.config.session_max_life > 0 and (
  885. time.time() - self.session_create_time > self.config.session_max_life)
  886. if not alive or expired:
  887. self._invalidate_query_session()
  888. return False
  889. return True
  890. def create_session(self):
  891. self._log(f"Initializing Session (ID: {self.instance_id})...")
  892. self._invalidate_query_session()
  893. options, self.tunnel = init_chromium_options(
  894. user_data_path=self.user_data_path,
  895. username_seed=self.config.account.username,
  896. proxy=self.config.proxy,
  897. headless=False,
  898. window_size="1920,1080",
  899. logger=self._log,
  900. )
  901. self.page = ChromiumPage(options)
  902. self.page.get(self.ita_url)
  903. self.mouse, self.keyboard = HumanMouse(self.page, debug=True), HumanKeyboard(self.page)
  904. width, height = self.page.rect.viewport_size
  905. self.mouse.move(random.randint(10, width - 10), random.randint(10, height - 10))
  906. flow = ItaLoginFlow(self)
  907. try:
  908. flow.run(max_steps=40, timeout=120)
  909. except BizLogicError:
  910. raise
  911. except Exception as exc:
  912. raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
  913. def query(self, apt_type):
  914. if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
  915. raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
  916. route = self._resolve_route(apt_type)
  917. if same_origin_path(self.page.url) != CALENDAR_PATH:
  918. entry = self._enter_service(apt_type, route=route)
  919. if not entry.success:
  920. return entry
  921. self._reset_calendar_state()
  922. prepare_calendar(self, route, role="query")
  923. self._require_calendar_context(route, role="query")
  924. probes = scan_until_first_available_month(
  925. self.page, lookahead_months=route.lookahead_months, log=self._log)
  926. available = available_calendar_days(probes[-1])
  927. if not available:
  928. return VSQueryResult(
  929. success=False, apt_type=apt_type,
  930. availability_status=AvailabilityStatus.NoneAvailable)
  931. earliest = datetime.combine(available[0].day, datetime.min.time())
  932. self._log(f"Italy Calendar earliest_date={earliest.date().isoformat()}")
  933. return VSQueryResult(
  934. success=True, apt_type=apt_type,
  935. availability_status=AvailabilityStatus.Available,
  936. earliest_date=earliest,
  937. availability=[DateAvailability(date=earliest, times=[])])
  938. def _enter_service(self, apt_type, *, route=None):
  939. route, path = route or self._resolve_route(apt_type), None
  940. booking_path = self._booking_path(route)
  941. self.page.get(f"{self.ita_url}/Services")
  942. self.page.wait.doc_loaded()
  943. if self._authenticated_path() != "/Services":
  944. raise BizLogicError("Italy service list is unavailable")
  945. link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
  946. if not link:
  947. raise NotFoundError(f"Italy service link is missing: {booking_path}")
  948. self.mouse.human_click_ele(link)
  949. self.page.wait.load_start()
  950. self.page.wait.doc_loaded()
  951. path = self._authenticated_path()
  952. empty = VSQueryResult(
  953. success=False, apt_type=apt_type,
  954. availability_status=AvailabilityStatus.NoneAvailable)
  955. if path == "/Services":
  956. marker = self.page.ele("#WNotAvailable", timeout=1)
  957. notice = self.page.ele(".jconfirm-content", timeout=1)
  958. text = ((marker.attr("value") if marker else "") or
  959. (notice.text if notice else "") or "").strip().casefold()
  960. if text and ("posti disponibili" in text or marker):
  961. return empty
  962. raise BizLogicError("Italy service returned an unknown response")
  963. if path != booking_path or not self.page.ele("#bookingForm", timeout=2):
  964. raise BizLogicError("Italy booking form is unavailable")
  965. return VSQueryResult(
  966. success=True, apt_type=apt_type,
  967. availability_status=AvailabilityStatus.NoneAvailable)
  968. def book(self, slot_info, user_inputs=None):
  969. if not self.page or not isinstance(slot_info, VSQueryResult):
  970. raise BizLogicError("Italy Book requires a Query signal")
  971. route = self._resolve_route(slot_info.apt_type)
  972. inputs = user_inputs if isinstance(user_inputs, Mapping) else {}
  973. username = str(inputs.get("username", "")).strip().casefold()
  974. if not username or username != self.config.account.username.strip().casefold():
  975. raise BizLogicError("Italy Book requires the applicant account")
  976. if self._prepared_calendar is None:
  977. entry = self._enter_service(slot_info.apt_type, route=route)
  978. if not entry.success:
  979. return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  980. prepare_calendar(self, route, role="book")
  981. start, end = book_date_preferences(inputs)
  982. slot = recheck_calendar_before_final(
  983. self.page,
  984. lookahead_months=route.lookahead_months,
  985. start_day=start,
  986. end_day=end,
  987. session_is_current=lambda: self._calendar_context_matches(
  988. route, role="book", username=username),
  989. log=self._log,
  990. )
  991. if not slot:
  992. return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  993. self._log(f"Italy Book selected {slot.day} {slot.time_label}")
  994. if self.free_config.get("final_submit_enabled") is True:
  995. return _submit_final_once(self, route, slot)
  996. return VSBookResult(success=False, label=BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  997. def cleanup(self):
  998. self._invalidate_query_session()
  999. cleanup_browser_workspace(
  1000. self.page, self.root_workspace, self.tunnel, self._log)
  1001. self.page = self.tunnel = None
  1002. def get_plugin_status(self):
  1003. proxy = self.config.proxy if self.config else None
  1004. return PluginStatus(
  1005. instance_id=self.instance_id,
  1006. is_healthy=self.is_healthy,
  1007. state="running" if self.is_healthy else "unhealthy",
  1008. current_url=str(self.page.url if self.page else ""),
  1009. account=self.config.account.username if self.config else "",
  1010. proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
  1011. session_age_sec=0,
  1012. last_active_at=utc_now_str(),
  1013. )
  1014. def __del__(self):
  1015. try:
  1016. self.cleanup()
  1017. except Exception:
  1018. pass