ita_plugin.py 53 KB

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