ita_plugin.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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, BizException, 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. def same_origin_path(raw_url):
  271. try:
  272. parsed = urlparse(str(raw_url or ""))
  273. port = parsed.port
  274. except ValueError:
  275. raise BizLogicError("Italy request left the expected origin") from None
  276. if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
  277. or port not in (None, 443) or parsed.username is not None):
  278. raise BizLogicError("Italy request left the expected origin")
  279. return parsed.path
  280. CALENDAR_DOM_SCRIPT = r"""
  281. const [mode, serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
  282. const all = (selector, root = document) => Array.from(root.querySelectorAll(selector));
  283. const services = all('#idServizio'), timeline = all('.events a.selected[data-date]');
  284. const service = services.length === 1 ? services[0].value : '';
  285. const selectedDay = timeline.length === 1 ? timeline[0].dataset.date : '';
  286. if (mode === 'context') return {path: location.pathname, service, day: selectedDay};
  287. const contextReady = location.pathname === '/BookingCalendar' && service === serviceId;
  288. const links = all('.events a[data-date]').filter(item => item.dataset.date === day);
  289. const link = links.length === 1 ? links[0] : null;
  290. if (mode === 'date') {
  291. const candidateReady = Boolean(contextReady && link &&
  292. !link.classList.contains('notAvailableDay') && !link.classList.contains('disabled'));
  293. let selected = Boolean(candidateReady && link.classList.contains('selected')), clicked = false;
  294. if (shouldClick && candidateReady && !selected) { link.click(); clicked = true; }
  295. selected = Boolean(candidateReady && link.classList.contains('selected'));
  296. return {contextReady, candidateCount: links.length, candidateReady, selected, clicked};
  297. }
  298. const content = all('.events-content li.selected').find(item => item.dataset.date === day);
  299. const matches = content ? all('.fascia', content).filter(slot => {
  300. const input = slot.querySelector('#idHiddenFasciaServizio');
  301. return input && input.value === dailyId;
  302. }) : [];
  303. const slot = matches.length === 1 ? matches[0] : null, spans = slot ? slot.querySelectorAll('span') : [];
  304. const clean = value => String(value || '').replace(/\s+/g, ' ').trim();
  305. const candidateReady = Boolean(contextReady && slot && !slot.classList.contains('notAvailableFascia') &&
  306. spans.length === 2 && clean(spans[0].textContent) === timeLabel &&
  307. clean(spans[1].textContent) === `(${capacity})`);
  308. let selected = Boolean(candidateReady && slot.classList.contains('act')), clicked = false;
  309. if (shouldClick && candidateReady && !selected) { slot.click(); clicked = true; }
  310. selected = Boolean(candidateReady && slot.classList.contains('act'));
  311. return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
  312. """
  313. def _runtime_id(value):
  314. if value is None or isinstance(value, bool):
  315. raise BizLogicError("Italy Calendar service id is invalid")
  316. value = str(value).strip()
  317. if not re.fullmatch(r"[1-9]\d{0,127}", value):
  318. raise BizLogicError("Italy Calendar service id is invalid")
  319. return value
  320. def _request_day(value):
  321. try:
  322. return date.fromisoformat(str(value))
  323. except ValueError:
  324. raise BizLogicError("Italy Calendar date format changed") from None
  325. def read_calendar_context(page):
  326. if same_origin_path(page.url) != CALENDAR_PATH:
  327. raise BizLogicError("Italy Calendar page is not current")
  328. raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
  329. if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
  330. raise BizLogicError("Italy Calendar context is not ready")
  331. return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
  332. def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
  333. deadline = time.monotonic() + timeout
  334. while time.monotonic() < deadline:
  335. if session_is_current() is not True:
  336. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  337. try:
  338. service = read_calendar_context(page)[0]
  339. except BizLogicError:
  340. time.sleep(0.1)
  341. continue
  342. if expected_service and service != _runtime_id(expected_service):
  343. raise BizLogicError("Italy Calendar service changed")
  344. return service
  345. raise BizLogicError("Italy Calendar service did not initialize")
  346. def _calendar_post(page, path, payload, parser, *, form=False):
  347. try:
  348. response = perform_browser_fetch(
  349. page, "POST", path, **{"data" if form else "json_data": payload}, timeout=30)
  350. except BizException:
  351. raise
  352. except Exception as exc:
  353. raise BizLogicError(f"Italy Calendar request failed: {type(exc).__name__}") from exc
  354. status, host = response.status_code, urlparse(str(response.url or "")).hostname
  355. if host == "iam.esteri.it" or status == 401:
  356. raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
  357. if status == 403:
  358. raise PermissionDeniedError("Italy Calendar access denied")
  359. if status == 429:
  360. raise RateLimiteddError("Italy Calendar rate limited")
  361. if status == 404:
  362. raise NotFoundError("Italy Calendar endpoint is unavailable")
  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 (ValueError, TypeError) as exc:
  370. raise BizLogicError(
  371. f"Italy Calendar response rejected ({getattr(exc, 'code', type(exc).__name__)})") from exc
  372. def fetch_calendar_month(page, service, selected_day):
  373. selected = selected_day.strftime("%d/%m/%Y")
  374. days = _calendar_post(
  375. page, AVAILABILITY_PATH,
  376. {"_Servizio": _runtime_id(service), "selectedDay": selected},
  377. parse_calendar_availability,
  378. )
  379. if any(item.day.replace(day=1) != selected_day.replace(day=1) for item in days):
  380. raise BizLogicError("Italy Calendar returned dates for another month")
  381. return days
  382. def fetch_calendar_slots(page, service, selected_day):
  383. slots = _calendar_post(
  384. page, TIME_SLOTS_PATH,
  385. {"selectedDay": selected_day.isoformat(), "idService": _runtime_id(service)},
  386. parse_time_slots,
  387. )
  388. if any(slot.day != selected_day for slot in slots):
  389. raise BizLogicError("Italy Calendar returned slots for another day")
  390. return slots
  391. def scan_until_first_available_month(
  392. page, *, lookahead_months, log=None, check_current=None,
  393. month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  394. ):
  395. service, anchor = read_calendar_context(page)
  396. scans = []
  397. for index, month in enumerate(month_starts(anchor, lookahead_months)):
  398. if index and month_click_interval_seconds:
  399. time.sleep(month_click_interval_seconds)
  400. if check_current:
  401. check_current()
  402. days = fetch_calendar_month(page, service, month)
  403. if check_current:
  404. check_current()
  405. scans.append(days)
  406. available = available_calendar_days(days)
  407. if log:
  408. log(f"Italy Calendar probe index={index} available={len(available)}")
  409. if available:
  410. break
  411. return tuple(scans)
  412. def click_next_month(page, *, timeout=10):
  413. control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
  414. if not control:
  415. raise NotFoundError("Italy Calendar next-month control is unavailable")
  416. control.click(by_js=True)
  417. def _snapshot(page, mode, service, day, candidate=None, click=False):
  418. candidate = candidate or SlotCandidate(day, 0, -1, datetime_time.min, datetime_time.min, "")
  419. raw = page.run_js(
  420. CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
  421. candidate.time_label, candidate.slots_free, click,
  422. )
  423. if (not isinstance(raw, dict) or type(raw.get("candidateCount")) is not int
  424. or any(type(raw.get(key)) is not bool for key in (
  425. "contextReady", "candidateReady", "selected", "clicked"))
  426. or not raw["contextReady"] or raw["candidateCount"] not in (0, 1)
  427. or (raw["candidateCount"] == 0 and (mode != "slot" or click
  428. or raw["candidateReady"] or raw["selected"] or raw["clicked"]))):
  429. raise BizLogicError("Italy Calendar selection context changed")
  430. return raw
  431. def verify_precommit_selection(page, *, runtime_service, candidate):
  432. raw = _snapshot(
  433. page, "slot", runtime_service, candidate.day, candidate, False)
  434. if (not candidate.is_available or raw["candidateCount"] != 1
  435. or not raw["candidateReady"] or not raw["selected"]):
  436. raise BizLogicError("Italy Calendar selected slot changed")
  437. return candidate
  438. def select_slot_before_final(
  439. page, *, target_day, days, slots, runtime_service,
  440. dom_timeout=5, session_is_current=None,
  441. ):
  442. inventory = [item for item in days if item.day == target_day and item.is_available]
  443. candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
  444. if not inventory or not candidates:
  445. return None
  446. candidate, deadline = candidates[0], time.monotonic() + dom_timeout
  447. if session_is_current and session_is_current() is not True:
  448. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  449. _snapshot(page, "date", runtime_service, target_day, click=True)
  450. while time.monotonic() < deadline:
  451. if session_is_current and session_is_current() is not True:
  452. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  453. date_state = _snapshot(page, "date", runtime_service, target_day)
  454. slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
  455. if date_state.get("selected") and slot_state.get("candidateReady"):
  456. if not slot_state.get("selected"):
  457. _snapshot(page, "slot", runtime_service, target_day, candidate, True)
  458. return verify_precommit_selection(
  459. page, runtime_service=runtime_service, candidate=candidate)
  460. time.sleep(0.1)
  461. raise BizLogicError("Italy Calendar slot did not finish loading")
  462. def book_date_preferences(user_inputs):
  463. values = []
  464. for key, default in (("expected_start_date", "2000-01-01"),
  465. ("expected_end_date", "2100-01-01")):
  466. try:
  467. values.append(date.fromisoformat(user_inputs.get(key, default)))
  468. except (AttributeError, TypeError, ValueError):
  469. raise BizLogicError(f"Italy {key} must use YYYY-MM-DD") from None
  470. if values[0] > values[1]:
  471. raise BizLogicError("Italy date preference is inverted")
  472. return tuple(values)
  473. def _move_to_month(page, service, target, timeout):
  474. current = read_calendar_context(page)[1]
  475. while (current.year, current.month) < target:
  476. expected = (current.year + 1, 1) if current.month == 12 else (current.year, current.month + 1)
  477. click_next_month(page, timeout=timeout)
  478. deadline = time.monotonic() + timeout
  479. while time.monotonic() < deadline:
  480. actual_service, current = read_calendar_context(page)
  481. if actual_service != service:
  482. raise BizLogicError("Italy Calendar service changed")
  483. if (current.year, current.month) == expected:
  484. break
  485. time.sleep(0.1)
  486. else:
  487. raise BizLogicError("Italy Calendar month did not load")
  488. if (current.year, current.month) != target:
  489. raise BizLogicError("Italy Calendar cannot navigate backwards")
  490. def recheck_calendar_before_final(
  491. page, *, lookahead_months, start_day, end_day, session_is_current,
  492. month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  493. timeout=30, dom_timeout=5, log=None,
  494. ):
  495. service, anchor = read_calendar_context(page)
  496. for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
  497. if session_is_current() is not True:
  498. raise SessionExpiredOrInvalidError("Italy applicant Session changed")
  499. if index and month_click_interval_seconds:
  500. time.sleep(month_click_interval_seconds)
  501. inventory = fetch_calendar_month(page, service, month_start)
  502. days = available_calendar_days(inventory, start_day=start_day, end_day=end_day)
  503. selected_month = month_start.year, month_start.month
  504. if log:
  505. log(f"Italy Book Calendar month={month_start:%Y-%m} candidates={len(days)}")
  506. if days:
  507. _move_to_month(page, service, selected_month, timeout)
  508. for item in days:
  509. slots = fetch_calendar_slots(page, service, item.day)
  510. candidate = select_slot_before_final(
  511. page, target_day=item.day, days=inventory, slots=slots,
  512. runtime_service=service, dom_timeout=dom_timeout,
  513. session_is_current=session_is_current,
  514. )
  515. if candidate:
  516. return candidate
  517. if selected_month >= (end_day.year, end_day.month):
  518. break
  519. return None
  520. FINAL_PATH = "/BookingCalendar/InsertNewBooking"
  521. FINAL_FAILED_LABEL = "italy-final-failed"
  522. FINAL_ACCEPTED_LABEL = "italy-final-accepted"
  523. def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
  524. result = VSBookResult(success=False, label=FINAL_FAILED_LABEL)
  525. try:
  526. page = plugin.page
  527. username = plugin.config.account.username.strip().casefold()
  528. prepared = plugin._require_calendar_context(route, role="book", username=username)
  529. if (not username or not isinstance(slot, SlotCandidate)
  530. or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
  531. raise BizLogicError("Italy final context is not current")
  532. verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
  533. data = _calendar_post(page, FINAL_PATH, {
  534. "idCalendarioGiornaliero": slot.daily_calendar_id,
  535. "selectedDay": slot.day.isoformat(),
  536. "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
  537. }, json.loads, form=True)
  538. if not isinstance(data, dict) or not isinstance(data.get("errorMessage"), str):
  539. raise BizLogicError("Italy final response is missing its result")
  540. if data["errorMessage"].strip():
  541. return result
  542. destination = data.get("url")
  543. if not isinstance(destination, str) or not destination.strip():
  544. raise BizLogicError("Italy final response is missing its receipt URL")
  545. path = same_origin_path(urljoin("https://prenotami.esteri.it", destination.strip()))
  546. if not re.fullmatch(r"/Reservation/?|/ReservationDetail/Index/[^/]+/?", path):
  547. raise BizLogicError("Italy final response did not lead to a receipt")
  548. result = VSBookResult(success=True, account=username, label=FINAL_ACCEPTED_LABEL,
  549. book_date=slot.day.isoformat(), book_time=slot.time_label)
  550. return result
  551. finally:
  552. if not result.success:
  553. # The next Booker signal must prepare again and obtain fresh IDs.
  554. plugin._reset_calendar_state()
  555. _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
  556. _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", Lock())
  557. def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
  558. if not route.booking_type or not route.purpose:
  559. raise BizLogicError("Italy route is missing form controls")
  560. config = {"path": booking_path, "booking": asdict(route.booking_type),
  561. "purpose": asdict(route.purpose)}
  562. return f"""
  563. const cfg = {json.dumps(config, ensure_ascii=False)};
  564. const form = document.querySelector('#bookingForm');
  565. const norm = value => String(value || '').replace(/\\s+/g, ' ').trim().toLowerCase();
  566. function choose(item) {{
  567. const control = document.getElementById(item.control_id);
  568. const option = control && Array.from(control.options).find(value => value.value === item.value);
  569. if (!option || !item.labels.map(norm).includes(norm(option.textContent))) return false;
  570. if (control.value !== item.value) {{
  571. control.value = item.value;
  572. control.dispatchEvent(new Event('change', {{bubbles: true}}));
  573. }}
  574. return control.value === item.value;
  575. }}
  576. const booking = choose(cfg.booking), purpose = choose(cfg.purpose);
  577. const privacy = document.querySelector('#PrivacyCheck');
  578. if (privacy && !privacy.checked) privacy.click();
  579. const otp = document.querySelector('#otp-input'), send = document.querySelector('#otp-send');
  580. const avanti = document.querySelector('#btnAvanti');
  581. const token = document.querySelector('input[name="cf-turnstile-response"]');
  582. return {{
  583. formReady: Boolean(location.pathname === cfg.path && form && booking && purpose && privacy && privacy.checked),
  584. turnstileReady: Boolean(token && token.value),
  585. otpValuePresent: Boolean(otp && otp.value.trim()),
  586. otpSendEnabled: Boolean(send && !send.disabled),
  587. avantiEnabled: Boolean(avanti && !avanti.disabled),
  588. }};
  589. """
  590. def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
  591. if type(after_otp) is not bool or type(allow_pending) is not bool:
  592. raise BizLogicError("Italy booking preflight policy is invalid")
  593. if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
  594. "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
  595. raise BizLogicError("Italy booking form structure changed")
  596. if raw["otpValuePresent"] is not after_otp:
  597. raise BizLogicError("Italy booking OTP stage changed")
  598. ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
  599. raw["turnstileReady"] and raw["avantiEnabled"])
  600. if not allow_pending and not ready:
  601. raise BizLogicError("Italy booking verification is not ready")
  602. def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
  603. check_current=None):
  604. deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
  605. while time.monotonic() < deadline:
  606. if check_current:
  607. check_current()
  608. raw = page.run_js(script)
  609. validate_booking_preflight(raw, after_otp=after_otp, allow_pending=True)
  610. form_ready = raw["formReady"] and (after_otp or raw["otpSendEnabled"])
  611. if form_ready and raw["turnstileReady"] and raw["avantiEnabled"]:
  612. return raw
  613. if form_ready and not raw["turnstileReady"] and attempts < 3:
  614. bypasser = bypasser or CloudflareBypasser(page, log=False)
  615. try:
  616. bypasser.click_verification_button(is_dfs=False)
  617. except Exception:
  618. pass
  619. attempts += 1
  620. time.sleep(1)
  621. reason = ("form_pending" if not raw or not raw["formReady"] else
  622. "otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
  623. "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
  624. raise BizLogicError(f"Italy booking verification timed out: {reason}")
  625. def _element_or_fail(page, selector):
  626. element = page.ele(selector, timeout=5)
  627. if not element:
  628. raise NotFoundError(f"Italy booking element is missing: {selector}")
  629. return element
  630. def _read_manual_otp():
  631. value = input("Italy booking OTP: ").strip()
  632. if not re.fullmatch(r"[0-9]{4,12}", value):
  633. raise BizLogicError("Italy OTP format rejected")
  634. return value
  635. def _enter_otp(plugin, otp):
  636. field = _element_or_fail(plugin.page, "#otp-input")
  637. plugin.mouse.human_click_ele(field)
  638. field.input(otp, clear=True)
  639. if field.run_js("return this.value === arguments[0];", otp) is not True:
  640. raise BizLogicError("Italy OTP write failed")
  641. def validate_cloud_otp_environment(mail_config, recipient):
  642. if not isinstance(mail_config, OtpMailConfig):
  643. raise BizLogicError("Italy OTP mail configuration is missing")
  644. if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
  645. raise BizLogicError("Italy OTP recipient is invalid")
  646. mail_config.mailbox_for(recipient)
  647. return recipient.strip()
  648. def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
  649. validate_cloud_otp_environment(mail_config, recipient)
  650. try:
  651. datetime.strptime(sent_at, _SENT_AT_FORMAT)
  652. except (TypeError, ValueError):
  653. raise BizLogicError("Italy OTP sent time is invalid") from None
  654. try:
  655. body = (api or VSCloudApi.Instance()).fetch_mail_content(
  656. email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
  657. subject_keywords="OTP Code", body_keywords="OTP Code:",
  658. sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
  659. )
  660. return parse_otp_body(body)
  661. except ItaProtocolError as exc:
  662. raise BizLogicError(f"Italy OTP body invalid ({exc.code})") from None
  663. except PermissionDeniedError:
  664. raise PermissionDeniedError("Italy OTP mailbox not permitted") from None
  665. except SessionExpiredOrInvalidError:
  666. raise SessionExpiredOrInvalidError("Italy OTP mailbox session expired") from None
  667. except RateLimiteddError:
  668. raise RateLimiteddError("Italy OTP mailbox rate limited") from None
  669. except NotFoundError:
  670. raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
  671. except BizLogicError as exc:
  672. status = re.search(r"\bHTTP Error (\d{3})\b", str(getattr(exc, "message", "")))
  673. if status and int(status.group(1)) == 404:
  674. raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
  675. if status and int(status.group(1)) in {408, 502, 503, 504}:
  676. raise BizLogicError("Italy OTP mailbox provider timed out") from None
  677. raise BizLogicError("Italy OTP mailbox read failed") from None
  678. except Exception:
  679. raise BizLogicError("Italy OTP mailbox read failed") from None
  680. def _wait_for_calendar(page, timeout=30):
  681. deadline = time.monotonic() + timeout
  682. while time.monotonic() < deadline:
  683. if urlparse(str(page.url or "")).path.rstrip("/") == CALENDAR_PATH:
  684. page.wait.doc_loaded()
  685. return
  686. time.sleep(0.25)
  687. raise BizLogicError("Italy AVANTI did not reach Calendar")
  688. def prepare_calendar(plugin, route, *, role):
  689. if role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM:
  690. raise BizLogicError("Italy Calendar preparation requires a tourism route")
  691. cloud = plugin.free_config.get("otp_mode") == "cloud"
  692. if not cloud and (plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty()):
  693. raise PermissionDeniedError("Italy Calendar requires automatic OTP or an attached terminal")
  694. username, page, booking_path = (
  695. plugin.config.account.username.strip().casefold(), plugin.page, plugin._booking_path(route))
  696. if cloud:
  697. validate_cloud_otp_environment(route.mail, username)
  698. def current(path):
  699. if plugin.page is not page or same_origin_path(page.url) != path:
  700. raise SessionExpiredOrInvalidError("Italy preparation page changed")
  701. def click(selector):
  702. current(booking_path)
  703. plugin.mouse.human_click_ele(_element_or_fail(page, selector))
  704. with _OTP_INPUT_LOCK:
  705. script = guarded_preflight_script(route, booking_path)
  706. wait_for_booking_preflight(page, script=script, check_current=lambda: current(booking_path))
  707. sent_at = datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
  708. click("#otp-send")
  709. plugin._log(f"Italy {role} OTP sent.")
  710. otp = (fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
  711. if cloud else _read_manual_otp())
  712. _enter_otp(plugin, otp)
  713. wait_for_booking_preflight(
  714. page, script=script, after_otp=True, check_current=lambda: current(booking_path))
  715. page.set.auto_handle_alert(accept=True)
  716. try:
  717. click("#btnAvanti")
  718. _wait_for_calendar(page)
  719. finally:
  720. page.set.auto_handle_alert(on_off=False)
  721. wait_for_calendar_service(
  722. page, session_is_current=lambda: plugin.page is page,
  723. expected_service=route.service_id,
  724. )
  725. plugin._record_calendar_prepared_route(route, role=role)
  726. BOOKING_RECHECK_NONE_AVAILABLE_LABEL = "no-availability-after-user-recheck"
  727. BOOKING_CALENDAR_PREFINAL_STOP_LABEL = "calendar-ready-before-final"
  728. RADWARE_VALIDATION_HOSTS = frozenset({"validate.perfdrive.com"})
  729. SERVICE_LINK_WAIT_SECONDS = 15
  730. SERVICES_PROBE_QUERY_MODE = "services_probe"
  731. CALENDAR_QUERY_MODE = "calendar"
  732. @dataclass(frozen=True, repr=False, eq=False)
  733. class _PreparedCalendar:
  734. username: str
  735. routing_key: str
  736. runtime_service: str
  737. tab_id: str
  738. role: str
  739. class ItaLoginFlow(BaseFlow):
  740. """Italy page rules on the host flow engine; never resubmit credentials."""
  741. def __init__(self, plugin):
  742. self.plugin = plugin
  743. self.entered = self.submitted = False
  744. super().__init__(plugin.page, interval=3, logger=plugin._log, max_stuck_cycles=None)
  745. def at(self, host, path):
  746. url = urlparse(self.page.url)
  747. return url.hostname == host and (url.path.rstrip("/") or "/") == path
  748. @guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
  749. def radware(self):
  750. raise PermissionDeniedError(
  751. "Italy authentication requires Radware browser validation; automatic retry is disabled")
  752. @guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
  753. urlparse(f.page.url).netloc.lower() not in {
  754. "prenotami.esteri.it", "iam.esteri.it", "prenotami.esteri.it:443", "iam.esteri.it:443"}, priority=2)
  755. def foreign_origin(self):
  756. raise BizLogicError("Italy authentication left the expected website")
  757. @guard(predicate=lambda f: any(value in f.page.html for value in (
  758. "Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
  759. def blocked(self):
  760. raise PermissionDeniedError("Italy authentication was blocked; automatic retry is disabled")
  761. @guard(predicate=lambda f: any(value in f.page.html for value in (
  762. "502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
  763. def server_error(self):
  764. if self.entered or self.submitted:
  765. raise BizLogicError("Italy authentication failed after login started; no resubmission")
  766. self.page.refresh()
  767. self.plugin._random_sleep(10, 15)
  768. @guard(title="just a moment", priority=5)
  769. @guard(title="cloudflare", priority=5)
  770. def verification_pending(self):
  771. self.log("Waiting for the website's human verification")
  772. time.sleep(5)
  773. @on(ele=".app-menu", predicate=lambda f: f.at("prenotami.esteri.it", "/UserArea") and
  774. bool(f.page.ele("@href=/Services", timeout=0.2)), priority=20)
  775. @done
  776. def authenticated(self):
  777. self.plugin._log("Successfully reached authenticated /UserArea.")
  778. self.plugin.session_create_time = time.time()
  779. self.plugin.is_healthy = True
  780. @on(ele="#pingid-button", predicate=lambda f: f.at("prenotami.esteri.it", "/") and not f.entered, priority=30)
  781. def enter(self):
  782. self.entered = True
  783. self.plugin.mouse.human_click_ele(self.page.ele("#pingid-button"))
  784. self.plugin._log("Redirecting to PingID...")
  785. self.plugin._random_sleep(3, 5)
  786. @on(ele="@name=callback_1", predicate=lambda f: f.at("iam.esteri.it", "/signin") and not f.submitted, priority=40)
  787. def credentials(self):
  788. username, password, submit = [self.page.ele(selector, timeout=0.2) for selector in
  789. ("@name=callback_1", "@name=callback_2", "tag:button@type=submit")]
  790. if not all((username, password, submit)):
  791. return # IAM can render its controls in separate updates.
  792. for label, element, value in (("username", username, self.plugin.config.account.username),
  793. ("password", password, self.plugin.config.account.password)):
  794. self.plugin._log(f"Entering {label}...")
  795. self.plugin.mouse.human_click_ele(element)
  796. element.input(value, clear=True)
  797. time.sleep(1)
  798. self.submitted = True
  799. self.plugin.mouse.human_click_ele(submit)
  800. self.plugin._log("Login form submitted. Waiting for dashboard to load...")
  801. self.plugin._random_sleep(5, 7)
  802. class ItaPlugin(IVSPlg):
  803. name = "ita_plugin"
  804. version = "1.0.3"
  805. description = "意大利 Prenot@Mi 查询与预约插件"
  806. def __init__(self, group_id):
  807. self.group_id = group_id
  808. self.config = None
  809. self.free_config = {}
  810. self.is_healthy = True
  811. self.logger = self.page = self.tunnel = None
  812. self.ita_url = "https://prenotami.esteri.it"
  813. self.instance_id = uuid.uuid4().hex[:8]
  814. self.root_workspace = os.path.abspath(
  815. os.path.join("data/temp_browser_data", f"{group_id}.{self.instance_id}"))
  816. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  817. os.makedirs(self.root_workspace, exist_ok=True)
  818. self.session_create_time = 0
  819. self._prepared_calendar = None
  820. def set_log(self, logger):
  821. self.logger = logger
  822. def _log(self, message):
  823. (self.logger or print)(f"[ItaPlugin] [{self.group_id}] {message}")
  824. def _random_sleep(self, minimum=30, maximum=60):
  825. seconds = random.uniform(minimum, maximum)
  826. self._log(f"Anti-Rate-Limit: Sleeping for {seconds:.2f} seconds...")
  827. time.sleep(seconds)
  828. def set_config(self, config):
  829. self.config, self.free_config = config, config.free_config or {}
  830. query_mode = self.free_config.get("query_mode", SERVICES_PROBE_QUERY_MODE)
  831. otp_mode = self.free_config.get("otp_mode")
  832. final = self.free_config.get("final_submit_enabled", False)
  833. if query_mode not in {SERVICES_PROBE_QUERY_MODE, CALENDAR_QUERY_MODE}:
  834. raise BizLogicError("Italy query_mode is invalid")
  835. if otp_mode not in {None, "manual", "cloud"}:
  836. raise BizLogicError("Italy otp_mode is invalid")
  837. if final is not False and not (
  838. final is True and otp_mode in {"manual", "cloud"}
  839. and query_mode == SERVICES_PROBE_QUERY_MODE):
  840. raise BizLogicError("Italy final submission configuration is invalid")
  841. self._prepared_calendar = None
  842. def _resolve_route(self, apt_type):
  843. try:
  844. return resolve_route_config(
  845. self.free_config.get("apt_configs", {}), apt_type.routing_key)
  846. except (AttributeError, ItaProtocolError) as exc:
  847. detail = getattr(exc, "code", type(exc).__name__)
  848. raise BizLogicError(f"Italy route configuration rejected: {detail}") from exc
  849. @staticmethod
  850. def _booking_path(route):
  851. return f"/Services/Booking/{route.service_id}"
  852. def _authenticated_path(self):
  853. host = urlparse(str(self.page.url or "")).hostname
  854. if host == "iam.esteri.it" or self.page.ele("#pingid-button", timeout=0.2):
  855. raise SessionExpiredOrInvalidError("Italy Session expired")
  856. return same_origin_path(self.page.url)
  857. def _reset_calendar_state(self):
  858. self._prepared_calendar = None
  859. def _calendar_context_matches(self, route, *, role, username=None):
  860. state = self._prepared_calendar
  861. try:
  862. account = self.config.account.username.strip().casefold()
  863. return (
  864. isinstance(state, _PreparedCalendar) and self.is_healthy and
  865. state.tab_id == self.page.tab_id and state.username == account and
  866. state.routing_key == route.routing_key and state.role == role and
  867. (username is None or username == account)
  868. )
  869. except Exception:
  870. return False
  871. def _record_calendar_prepared_route(self, route, *, role):
  872. try:
  873. self._prepared_calendar = _PreparedCalendar(
  874. self.config.account.username.strip().casefold(), route.routing_key,
  875. read_calendar_context(self.page)[0], self.page.tab_id, role)
  876. except Exception:
  877. self._prepared_calendar = None
  878. raise BizLogicError("Italy Calendar identity is unavailable") from None
  879. def _require_calendar_context(self, route, *, role, username=None):
  880. if not self._calendar_context_matches(route, role=role, username=username):
  881. raise BizLogicError("Italy Calendar Session changed")
  882. if read_calendar_context(self.page)[0] != self._prepared_calendar.runtime_service:
  883. raise BizLogicError("Italy Calendar service changed")
  884. return self._prepared_calendar
  885. def _invalidate_query_session(self):
  886. self.is_healthy = False
  887. self._prepared_calendar = None
  888. def keep_alive(self):
  889. pass
  890. def health_check(self):
  891. if not self.is_healthy or not self.page:
  892. return False
  893. try:
  894. alive = self.page.run_js("return 1;") == 1
  895. except Exception:
  896. alive = False
  897. expired = self.config.session_max_life > 0 and (
  898. time.time() - self.session_create_time > self.config.session_max_life)
  899. if not alive or expired:
  900. self._invalidate_query_session()
  901. return False
  902. return True
  903. def create_session(self):
  904. self._log(f"Initializing Session (ID: {self.instance_id})...")
  905. self._invalidate_query_session()
  906. account = getattr(self.config, "account", None)
  907. username, password = getattr(account, "username", None), getattr(account, "password", None)
  908. if (not isinstance(username, str) or not username.strip()
  909. or not isinstance(password, str) or not password):
  910. raise BizLogicError("Italy website username and password are required")
  911. options, self.tunnel = init_chromium_options(
  912. user_data_path=self.user_data_path,
  913. username_seed=self.config.account.username,
  914. proxy=self.config.proxy,
  915. headless=False,
  916. window_size="1920,1080",
  917. logger=self._log,
  918. )
  919. self.page = ChromiumPage(options)
  920. self.page.get(self.ita_url)
  921. self.mouse, self.keyboard = HumanMouse(self.page, debug=True), HumanKeyboard(self.page)
  922. width, height = self.page.rect.viewport_size
  923. self.mouse.move(random.randint(10, width - 10), random.randint(10, height - 10))
  924. flow = ItaLoginFlow(self)
  925. try:
  926. flow.run(max_steps=40, timeout=120)
  927. except BizException:
  928. raise
  929. except Exception as exc:
  930. raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
  931. def query(self, apt_type):
  932. if self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
  933. raise BizLogicError("Italy Query requires query_mode=calendar")
  934. if not self.health_check():
  935. raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
  936. route = self._resolve_route(apt_type)
  937. if same_origin_path(self.page.url) != CALENDAR_PATH:
  938. entry = self._enter_service(apt_type, route=route)
  939. if not entry.success:
  940. return entry
  941. self._reset_calendar_state()
  942. prepare_calendar(self, route, role="query")
  943. self._require_calendar_context(route, role="query")
  944. probes = scan_until_first_available_month(
  945. self.page, lookahead_months=route.lookahead_months, log=self._log,
  946. check_current=lambda: self._require_calendar_context(route, role="query"))
  947. available = available_calendar_days(probes[-1])
  948. if not available:
  949. return VSQueryResult(
  950. success=False, apt_type=apt_type,
  951. availability_status=AvailabilityStatus.NoneAvailable)
  952. earliest = datetime.combine(available[0].day, datetime.min.time())
  953. self._log(f"Italy Calendar earliest_date={earliest.date().isoformat()}")
  954. return VSQueryResult(
  955. success=True, apt_type=apt_type,
  956. availability_status=AvailabilityStatus.Available,
  957. earliest_date=earliest,
  958. availability=[DateAvailability(date=earliest, times=[])])
  959. def _enter_service(self, apt_type, *, route=None):
  960. route, path = route or self._resolve_route(apt_type), None
  961. booking_path = self._booking_path(route)
  962. self.page.get(f"{self.ita_url}/Services")
  963. self.page.wait.doc_loaded()
  964. if self._authenticated_path() != "/Services":
  965. raise BizLogicError("Italy service list is unavailable")
  966. link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
  967. if not link:
  968. raise NotFoundError(f"Italy service link is missing: {booking_path}")
  969. self.mouse.human_click_ele(link)
  970. self.page.wait.load_start()
  971. self.page.wait.doc_loaded()
  972. path = self._authenticated_path()
  973. empty = VSQueryResult(
  974. success=False, apt_type=apt_type,
  975. availability_status=AvailabilityStatus.NoneAvailable)
  976. if path == "/Services":
  977. marker = self.page.ele("#WNotAvailable", timeout=1)
  978. notice = self.page.ele(".jconfirm-content", timeout=1)
  979. text = ((marker.attr("value") if marker else "") or
  980. (notice.text if notice else "") or "").strip().casefold()
  981. if text and ("posti disponibili" in text or marker):
  982. return empty
  983. raise BizLogicError("Italy service returned an unknown response")
  984. if path != booking_path or not self.page.ele("#bookingForm", timeout=2):
  985. raise BizLogicError("Italy booking form is unavailable")
  986. return VSQueryResult(
  987. success=True, apt_type=apt_type,
  988. availability_status=AvailabilityStatus.NoneAvailable)
  989. def book(self, slot_info, user_inputs=None):
  990. if not self.page or not isinstance(slot_info, VSQueryResult):
  991. raise BizLogicError("Italy Book requires a Query signal")
  992. route = self._resolve_route(slot_info.apt_type)
  993. inputs = user_inputs if isinstance(user_inputs, Mapping) else {}
  994. username = str(inputs.get("username", "")).strip().casefold()
  995. if not username or username != self.config.account.username.strip().casefold():
  996. raise BizLogicError("Italy Book requires the applicant account")
  997. if self._prepared_calendar is None:
  998. entry = self._enter_service(slot_info.apt_type, route=route)
  999. if not entry.success:
  1000. return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  1001. prepare_calendar(self, route, role="book")
  1002. start, end = book_date_preferences(inputs)
  1003. slot = recheck_calendar_before_final(
  1004. self.page,
  1005. lookahead_months=route.lookahead_months,
  1006. start_day=start,
  1007. end_day=end,
  1008. session_is_current=lambda: self._calendar_context_matches(
  1009. route, role="book", username=username),
  1010. log=self._log,
  1011. )
  1012. if not slot:
  1013. return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  1014. self._log(f"Italy Book selected {slot.day} {slot.time_label}")
  1015. if self.free_config.get("final_submit_enabled") is True:
  1016. return _submit_final_once(self, route, slot)
  1017. return VSBookResult(success=False, label=BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  1018. def cleanup(self):
  1019. self._invalidate_query_session()
  1020. cleanup_browser_workspace(
  1021. self.page, self.root_workspace, self.tunnel, self._log)
  1022. self.page = self.tunnel = None
  1023. def get_plugin_status(self):
  1024. proxy = self.config.proxy if self.config else None
  1025. current_url = ""
  1026. if self.page:
  1027. try:
  1028. current_url = str(self.page.url)
  1029. except Exception:
  1030. pass # Status reporting must still work after browser disconnection.
  1031. return PluginStatus(
  1032. instance_id=self.instance_id,
  1033. is_healthy=self.is_healthy,
  1034. state="running" if self.is_healthy else "unhealthy",
  1035. current_url=current_url,
  1036. account=self.config.account.username if self.config else "",
  1037. proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
  1038. session_age_sec=max(0, int(time.time() - self.session_create_time))
  1039. if self.session_create_time > 0 else 0,
  1040. last_active_at=utc_now_str(),
  1041. )
  1042. def __del__(self):
  1043. try:
  1044. self.cleanup()
  1045. except Exception:
  1046. pass