ita_plugin.py 52 KB

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