ita_plugin.py 51 KB

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