|
@@ -1,559 +1,1178 @@
|
|
|
-import time
|
|
|
|
|
|
|
+"""Prenot@Mi Query/Book adapter; Italy-specific production code stays here."""
|
|
|
|
|
+from __future__ import annotations
|
|
|
|
|
+
|
|
|
|
|
+import html
|
|
|
import json
|
|
import json
|
|
|
|
|
+import os
|
|
|
import random
|
|
import random
|
|
|
import re
|
|
import re
|
|
|
-import os
|
|
|
|
|
|
|
+import sys
|
|
|
|
|
+import time
|
|
|
import uuid
|
|
import uuid
|
|
|
-import base64
|
|
|
|
|
-from datetime import datetime
|
|
|
|
|
-from typing import List, Dict, Optional, Any, Callable
|
|
|
|
|
-from DrissionPage import ChromiumPage
|
|
|
|
|
|
|
+from dataclasses import asdict, dataclass, field
|
|
|
|
|
+from datetime import date, datetime, time as datetime_time, timezone
|
|
|
|
|
+from enum import Enum
|
|
|
|
|
+from threading import Lock
|
|
|
|
|
+from typing import Any, Mapping, Sequence
|
|
|
|
|
+from urllib.parse import urljoin, urlparse
|
|
|
|
|
|
|
|
|
|
+from DrissionPage import ChromiumPage
|
|
|
|
|
+import vs_plg as _ita_host
|
|
|
from vs_plg import IVSPlg
|
|
from vs_plg import IVSPlg
|
|
|
from vs_types import (
|
|
from vs_types import (
|
|
|
- VSPlgConfig,
|
|
|
|
|
- AppointmentType,
|
|
|
|
|
- VSQueryResult,
|
|
|
|
|
- VSBookResult,
|
|
|
|
|
- AvailabilityStatus,
|
|
|
|
|
- TimeSlot,
|
|
|
|
|
- DateAvailability,
|
|
|
|
|
- NotFoundError,
|
|
|
|
|
- PermissionDeniedError,
|
|
|
|
|
- RateLimiteddError,
|
|
|
|
|
- SessionExpiredOrInvalidError,
|
|
|
|
|
- BizLogicError,
|
|
|
|
|
- PluginStatus,
|
|
|
|
|
- utc_now_str
|
|
|
|
|
|
|
+ AvailabilityStatus, BizLogicError,
|
|
|
|
|
+ DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
|
|
|
|
|
+ SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
|
|
|
)
|
|
)
|
|
|
from toolkit.vs_cloud_api import VSCloudApi
|
|
from toolkit.vs_cloud_api import VSCloudApi
|
|
|
from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
|
|
from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
|
|
|
-from utils.mouse import HumanMouse
|
|
|
|
|
|
|
+from utils.flow_engine import BaseFlow, done, guard, on
|
|
|
from utils.keyboard import HumanKeyboard
|
|
from utils.keyboard import HumanKeyboard
|
|
|
-from utils.flow_engine import BaseFlow, on, guard, done, fatal
|
|
|
|
|
|
|
+from utils.mouse import HumanMouse
|
|
|
from utils.plugin_utils import (
|
|
from utils.plugin_utils import (
|
|
|
- BrowserResponse,
|
|
|
|
|
- init_chromium_options,
|
|
|
|
|
|
|
+ cleanup_browser_workspace, filter_dates_in_range, init_chromium_options,
|
|
|
perform_browser_fetch,
|
|
perform_browser_fetch,
|
|
|
- filter_dates_in_range,
|
|
|
|
|
- cleanup_browser_workspace
|
|
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
-class ItaLoginFlow(BaseFlow):
|
|
|
|
|
- """
|
|
|
|
|
- 基于 BaseFlow 注解状态机驱动的意大利 Prenot@Mi 会话创建与自动导航流
|
|
|
|
|
- """
|
|
|
|
|
- def __init__(self, page, plugin: 'ItaPlugin', interval: float = 1.0):
|
|
|
|
|
- super().__init__(
|
|
|
|
|
- page=page,
|
|
|
|
|
- config=plugin.config,
|
|
|
|
|
- context={"plugin": plugin},
|
|
|
|
|
- interval=interval,
|
|
|
|
|
- logger=plugin._log,
|
|
|
|
|
- cf_bypasser=CloudflareBypasser(page, log=plugin.config.debug if plugin.config else False)
|
|
|
|
|
|
|
+MAX_PROTOCOL_ITEMS = 512
|
|
|
|
|
+MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
|
|
|
|
|
+MAX_LOOKAHEAD_MONTHS = 120
|
|
|
|
|
+PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
|
|
|
|
|
+_EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
|
|
|
|
+_OTP_PATTERN = re.compile(r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)", re.I)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class ItaProtocolError(ValueError):
|
|
|
|
|
+ def __init__(self, code: str, message: str = "rejected", *, path: str = ""):
|
|
|
|
|
+ self.code, self.path = code, path
|
|
|
|
|
+ super().__init__(f"Italy protocol error [{code}]" + (f" at {path}" if path else "") + f": {message}")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class ItaCapability(str, Enum):
|
|
|
|
|
+ SERVICES_PROBE_ONLY = "services_probe_only"
|
|
|
|
|
+ SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, slots=True)
|
|
|
|
|
+class FormControlConfig:
|
|
|
|
|
+ control_id: str
|
|
|
|
|
+ value: str
|
|
|
|
|
+ labels: tuple[str, ...]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, slots=True)
|
|
|
|
|
+class OtpMailConfig:
|
|
|
|
|
+ authorization_email: str | None = field(default=None, repr=False)
|
|
|
|
|
+ subject_keywords: str = "OTP Code"
|
|
|
|
|
+ body_keywords: str = "OTP Code:"
|
|
|
|
|
+ expiry_seconds: int = 300
|
|
|
|
|
+ authorization_source: str = "configured"
|
|
|
|
|
+
|
|
|
|
|
+ def __post_init__(self):
|
|
|
|
|
+ if self.authorization_source not in {"account", "configured"}:
|
|
|
|
|
+ raise ItaProtocolError("otp_authorization_source_invalid")
|
|
|
|
|
+ if self.authorization_source == "account" and self.authorization_email is not None:
|
|
|
|
|
+ raise ItaProtocolError("otp_authorization_source_conflict")
|
|
|
|
|
+ if self.authorization_source == "configured":
|
|
|
|
|
+ self.mailbox_for("")
|
|
|
|
|
+ if type(self.expiry_seconds) is not int or not 1 <= self.expiry_seconds <= 300:
|
|
|
|
|
+ raise ItaProtocolError("otp_expiry_invalid")
|
|
|
|
|
+ if (self.subject_keywords, self.body_keywords) != ("OTP Code", "OTP Code:"):
|
|
|
|
|
+ raise ItaProtocolError("otp_filter_invalid")
|
|
|
|
|
+
|
|
|
|
|
+ def mailbox_for(self, account_email: str) -> str:
|
|
|
|
|
+ value = account_email if self.authorization_source == "account" else self.authorization_email
|
|
|
|
|
+ if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
|
|
|
|
|
+ raise ItaProtocolError("otp_authorization_email_invalid", path="mail.authorization_email")
|
|
|
|
|
+ return value.strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, slots=True)
|
|
|
|
|
+class ItaRouteConfig:
|
|
|
|
|
+ routing_key: str
|
|
|
|
|
+ service_id: int
|
|
|
|
|
+ capability: ItaCapability
|
|
|
|
|
+ lookahead_months: int = 0
|
|
|
|
|
+ booking_type: FormControlConfig | None = None
|
|
|
|
|
+ purpose: FormControlConfig | None = None
|
|
|
|
|
+ mail: OtpMailConfig | None = None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, slots=True)
|
|
|
|
|
+class CalendarDay:
|
|
|
|
|
+ day: date
|
|
|
|
|
+ slots_free: int
|
|
|
|
|
+ slots_remaining: int
|
|
|
|
|
+
|
|
|
|
|
+ @property
|
|
|
|
|
+ def is_available(self):
|
|
|
|
|
+ return self.slots_free > 0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, slots=True)
|
|
|
|
|
+class SlotCandidate(CalendarDay):
|
|
|
|
|
+ start_time: datetime_time
|
|
|
|
|
+ end_time: datetime_time
|
|
|
|
|
+ daily_calendar_id: str = field(repr=False)
|
|
|
|
|
+
|
|
|
|
|
+ @property
|
|
|
|
|
+ def time_label(self):
|
|
|
|
|
+ return f"{self.start_time:%H:%M} - {self.end_time:%H:%M}"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _positive_int(value, path, maximum=None):
|
|
|
|
|
+ if type(value) is not int or value <= 0:
|
|
|
|
|
+ raise ItaProtocolError("positive_integer_required", path=path)
|
|
|
|
|
+ if maximum is not None and value > maximum:
|
|
|
|
|
+ raise ItaProtocolError("lookahead_too_large", path=path)
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _mapping(value, path):
|
|
|
|
|
+ if not isinstance(value, Mapping):
|
|
|
|
|
+ raise ItaProtocolError("mapping_required", path=path)
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _text(value, path):
|
|
|
|
|
+ if not isinstance(value, str) or not value.strip():
|
|
|
|
|
+ raise ItaProtocolError("string_required", path=path)
|
|
|
|
|
+ return value.strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _control(form, prefix, path):
|
|
|
|
|
+ labels = form.get(f"{prefix}_labels")
|
|
|
|
|
+ if isinstance(labels, (str, bytes)) or not isinstance(labels, Sequence) or not labels:
|
|
|
|
|
+ raise ItaProtocolError("labels_required", path=path)
|
|
|
|
|
+ labels = tuple(_text(value, path) for value in labels)
|
|
|
|
|
+ if len(set(labels)) != len(labels):
|
|
|
|
|
+ raise ItaProtocolError("labels_duplicate", path=path)
|
|
|
|
|
+ return FormControlConfig(
|
|
|
|
|
+ _text(form.get(f"{prefix}_control_id"), path),
|
|
|
|
|
+ _text(form.get(f"{prefix}_value"), path),
|
|
|
|
|
+ labels,
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def resolve_route_config(configs: Mapping[str, Any], routing_key: str) -> ItaRouteConfig:
|
|
|
|
|
+ configs, key = _mapping(configs, "apt_configs"), _text(routing_key, "routing_key")
|
|
|
|
|
+ if key not in configs:
|
|
|
|
|
+ raise ItaProtocolError("route_missing", path="apt_configs")
|
|
|
|
|
+ raw = _mapping(configs[key], key)
|
|
|
|
|
+ capability_name = _text(raw.get("capability"), f"{key}.capability")
|
|
|
|
|
+ try:
|
|
|
|
|
+ capability = ItaCapability(capability_name)
|
|
|
|
|
+ except ValueError:
|
|
|
|
|
+ raise ItaProtocolError("capability_unsupported", path=f"{key}.capability") from None
|
|
|
|
|
+ service = _positive_int(raw.get("service_id"), f"{key}.service_id")
|
|
|
|
|
+ if capability is ItaCapability.SERVICES_PROBE_ONLY:
|
|
|
|
|
+ return ItaRouteConfig(key, service, capability)
|
|
|
|
|
+ form = _mapping(raw.get("form"), f"{key}.form")
|
|
|
|
|
+ scan = _mapping(raw.get("calendar_scan"), f"{key}.calendar_scan")
|
|
|
|
|
+ mail_raw = raw.get("mail")
|
|
|
|
|
+ mail = None
|
|
|
|
|
+ if mail_raw is not None:
|
|
|
|
|
+ mail_raw = _mapping(mail_raw, f"{key}.mail")
|
|
|
|
|
+ if str(mail_raw.get("sender", PRENOTAMI_OTP_SENDER)).strip().casefold() != PRENOTAMI_OTP_SENDER:
|
|
|
|
|
+ raise ItaProtocolError("otp_sender_not_allowlisted", path=f"{key}.mail.sender")
|
|
|
|
|
+ source = mail_raw.get("authorization_source", "configured")
|
|
|
|
|
+ mail = OtpMailConfig(
|
|
|
|
|
+ mail_raw.get("authorization_email"),
|
|
|
|
|
+ mail_raw.get("subject_keywords", "OTP Code"),
|
|
|
|
|
+ mail_raw.get("body_keywords", "OTP Code:"),
|
|
|
|
|
+ mail_raw.get("expiry_seconds", 300), source,
|
|
|
)
|
|
)
|
|
|
- self.plugin = plugin
|
|
|
|
|
- self.has_submitted_login = False
|
|
|
|
|
-
|
|
|
|
|
- # --- 异常守卫与自愈 (Priority 5~7) ---
|
|
|
|
|
- @guard(text="502 Bad Gateway", priority=5)
|
|
|
|
|
- @guard(text="503 Service Temporarily Unavailable", priority=5)
|
|
|
|
|
- @guard(text="error 1020", priority=5)
|
|
|
|
|
- def on_server_network_error(self):
|
|
|
|
|
- self.log("[WARN] 检测到服务器网络错误 (502/503/1020),等待并刷新自愈...", level="warning")
|
|
|
|
|
- self.plugin._random_sleep(10, 15)
|
|
|
|
|
- self.page.refresh()
|
|
|
|
|
|
|
+ return ItaRouteConfig(
|
|
|
|
|
+ key, service, capability,
|
|
|
|
|
+ _positive_int(scan.get("lookahead_months"), f"{key}.calendar_scan", MAX_LOOKAHEAD_MONTHS),
|
|
|
|
|
+ _control(form, "booking_type", f"{key}.form"),
|
|
|
|
|
+ _control(form, "purpose", f"{key}.form"),
|
|
|
|
|
+ mail,
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def decode_double_json_array(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
|
|
|
|
|
+ if not isinstance(payload, str) or not payload:
|
|
|
|
|
+ raise ItaProtocolError("payload_type")
|
|
|
|
|
+ if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
|
|
|
|
|
+ raise ItaProtocolError("payload_too_large")
|
|
|
|
|
+ if type(max_items) is not int or max_items <= 0:
|
|
|
|
|
+ raise ItaProtocolError("max_items_invalid")
|
|
|
|
|
+ try:
|
|
|
|
|
+ inner = json.loads(payload)
|
|
|
|
|
+ except json.JSONDecodeError as exc:
|
|
|
|
|
+ raise ItaProtocolError("outer_json_invalid") from exc
|
|
|
|
|
+ if not isinstance(inner, str):
|
|
|
|
|
+ raise ItaProtocolError("payload_layer_count")
|
|
|
|
|
+ try:
|
|
|
|
|
+ records = json.loads(inner)
|
|
|
|
|
+ except json.JSONDecodeError as exc:
|
|
|
|
|
+ raise ItaProtocolError("inner_json_invalid") from exc
|
|
|
|
|
+ if not isinstance(records, list):
|
|
|
|
|
+ raise ItaProtocolError("payload_layer_count")
|
|
|
|
|
+ if len(records) > max_items:
|
|
|
|
|
+ raise ItaProtocolError("item_limit_exceeded")
|
|
|
|
|
+ if not all(isinstance(item, Mapping) for item in records):
|
|
|
|
|
+ raise ItaProtocolError("item_type")
|
|
|
|
|
+ return tuple(records)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _site_date(value, path):
|
|
|
|
|
+ if not isinstance(value, str) or not re.fullmatch(r"\d{2}/\d{2}/\d{4} 00:00:00", value):
|
|
|
|
|
+ raise ItaProtocolError("date_format", path=path)
|
|
|
|
|
+ try:
|
|
|
|
|
+ return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
|
|
|
|
|
+ except ValueError as exc:
|
|
|
|
|
+ raise ItaProtocolError("date_invalid", path=path) from exc
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _integer(item, key, path):
|
|
|
|
|
+ if key not in item:
|
|
|
|
|
+ raise ItaProtocolError("field_missing", path=f"{path}.{key}")
|
|
|
|
|
+ if type(item[key]) is not int:
|
|
|
|
|
+ raise ItaProtocolError("integer_required", path=f"{path}.{key}")
|
|
|
|
|
+ return item[key]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _clock(value, path):
|
|
|
|
|
+ value = _mapping(value, path)
|
|
|
|
|
+ parts = [_integer(value, key, path) for key in (
|
|
|
|
|
+ "Hours", "Minutes", "Seconds", "Milliseconds")]
|
|
|
|
|
+ if parts[2] or parts[3]:
|
|
|
|
|
+ raise ItaProtocolError("time_precision", path=path)
|
|
|
|
|
+ try:
|
|
|
|
|
+ return datetime_time(parts[0], parts[1])
|
|
|
|
|
+ except ValueError as exc:
|
|
|
|
|
+ raise ItaProtocolError("time_invalid", path=path) from exc
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _parse_calendar_items(payload, time_slots=False, max_items=MAX_PROTOCOL_ITEMS):
|
|
|
|
|
+ records, identities, daily_ids = [], set(), set()
|
|
|
|
|
+ for index, item in enumerate(decode_double_json_array(payload, max_items=max_items)):
|
|
|
|
|
+ path = f"{'time_slots' if time_slots else 'availability'}[{index}]"
|
|
|
|
|
+ free, remaining = _integer(item, "SlotLiberi", path), _integer(item, "SlotRimanenti", path)
|
|
|
|
|
+ if not ((free > 0 and remaining >= 0) or (free == 0 and remaining < 0)):
|
|
|
|
|
+ raise ItaProtocolError("inventory_conflict", path=path)
|
|
|
|
|
+ day = _site_date(item.get("Data" if time_slots else "DateLibere"), path)
|
|
|
|
|
+ if time_slots:
|
|
|
|
|
+ start = _clock(item.get("OrarioInizioFascia"), f"{path}.OrarioInizioFascia")
|
|
|
|
|
+ end = _clock(item.get("OrarioFineFascia"), f"{path}.OrarioFineFascia")
|
|
|
|
|
+ if start >= end:
|
|
|
|
|
+ raise ItaProtocolError("time_range_invalid", path=path)
|
|
|
|
|
+ daily_id = _integer(item, "IDCalendarioServizioGiornaliero", path)
|
|
|
|
|
+ if daily_id <= 0:
|
|
|
|
|
+ raise ItaProtocolError("positive_integer_required", path=path)
|
|
|
|
|
+ if daily_id in daily_ids:
|
|
|
|
|
+ raise ItaProtocolError("duplicate_daily_id", path=path)
|
|
|
|
|
+ daily_ids.add(daily_id)
|
|
|
|
|
+ record = SlotCandidate(day, free, remaining, start, end, str(daily_id))
|
|
|
|
|
+ identity = day, start, end
|
|
|
|
|
+ else:
|
|
|
|
|
+ record, identity = CalendarDay(day, free, remaining), day
|
|
|
|
|
+ if identity in identities:
|
|
|
|
|
+ raise ItaProtocolError("duplicate_time_range" if time_slots else "duplicate_calendar_day")
|
|
|
|
|
+ identities.add(identity)
|
|
|
|
|
+ records.append(record)
|
|
|
|
|
+ return tuple(sorted(records, key=lambda item: (item.day, getattr(item, "start_time", datetime_time.min))))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def parse_calendar_availability(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
|
|
|
|
|
+ return _parse_calendar_items(payload, max_items=max_items)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def parse_time_slots(payload: str, *, max_items: int = MAX_PROTOCOL_ITEMS):
|
|
|
|
|
+ return _parse_calendar_items(payload, time_slots=True, max_items=max_items)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _available_inventory(items, *, start_day=None, end_day=None):
|
|
|
|
|
+ if start_day and end_day and start_day > end_day:
|
|
|
|
|
+ raise ItaProtocolError("date_range_invalid")
|
|
|
|
|
+ allowed = set(filter_dates_in_range(
|
|
|
|
|
+ [item.day.isoformat() for item in items],
|
|
|
|
|
+ (start_day or date.min).isoformat(), (end_day or date.max).isoformat(),
|
|
|
|
|
+ shuffle=False,
|
|
|
|
|
+ ))
|
|
|
|
|
+ return tuple(item for item in sorted(
|
|
|
|
|
+ (item for item in items if item.is_available and item.day.isoformat() in allowed),
|
|
|
|
|
+ key=lambda item: (item.day, getattr(item, "start_time", datetime_time.min)),
|
|
|
|
|
+ ))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+available_calendar_days = available_slot_candidates = _available_inventory
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def parse_otp_body(body: str, *, max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS):
|
|
|
|
|
+ if not isinstance(body, str) or not body.strip():
|
|
|
|
|
+ raise ItaProtocolError("otp_body_invalid")
|
|
|
|
|
+ if len(body) > max_chars:
|
|
|
|
|
+ raise ItaProtocolError("otp_body_too_large")
|
|
|
|
|
+ values = set(_OTP_PATTERN.findall(html.unescape(re.sub(r"<[^>]*>", " ", body))))
|
|
|
|
|
+ if len(values) != 1:
|
|
|
|
|
+ raise ItaProtocolError("otp_not_found" if not values else "otp_ambiguous")
|
|
|
|
|
+ return values.pop()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def month_starts(anchor_day: date, lookahead_months: int):
|
|
|
|
|
+ months = _positive_int(lookahead_months, "lookahead_months", MAX_LOOKAHEAD_MONTHS)
|
|
|
|
|
+ return tuple(date(anchor_day.year + (anchor_day.month - 1 + i) // 12,
|
|
|
|
|
+ (anchor_day.month - 1 + i) % 12 + 1, 1) for i in range(months))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+CALENDAR_PATH = "/BookingCalendar"
|
|
|
|
|
+AVAILABILITY_PATH = "/BookingCalendar/RetrieveCalendarAvailability"
|
|
|
|
|
+TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
|
|
|
|
|
+DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class CalendarGateError(RuntimeError): pass
|
|
|
|
|
+class CalendarAuthenticationExpiredError(CalendarGateError): pass
|
|
|
|
|
+class CalendarRateLimitedError(CalendarGateError): pass
|
|
|
|
|
+class CalendarAccessDeniedError(CalendarGateError): pass
|
|
|
|
|
+class CalendarTransientError(CalendarGateError): pass
|
|
|
|
|
+class CalendarBookError(CalendarGateError): pass
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def same_origin_path(raw_url):
|
|
|
|
|
+ parsed = urlparse(str(raw_url or ""))
|
|
|
|
|
+ if parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it":
|
|
|
|
|
+ raise CalendarGateError("Italy request left the expected origin")
|
|
|
|
|
+ return parsed.path
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+CALENDAR_DOM_SCRIPT = r"""
|
|
|
|
|
+const [mode, serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
|
|
|
|
|
+const all = (selector, root = document) => Array.from(root.querySelectorAll(selector));
|
|
|
|
|
+const services = all('#idServizio'), timeline = all('.events a.selected[data-date]');
|
|
|
|
|
+const service = services.length === 1 ? services[0].value : '';
|
|
|
|
|
+const selectedDay = timeline.length === 1 ? timeline[0].dataset.date : '';
|
|
|
|
|
+if (mode === 'context') return {path: location.pathname, service, day: selectedDay};
|
|
|
|
|
+const contextReady = location.pathname === '/BookingCalendar' && service === serviceId;
|
|
|
|
|
+const links = all('.events a[data-date]').filter(item => item.dataset.date === day);
|
|
|
|
|
+const link = links.length === 1 ? links[0] : null;
|
|
|
|
|
+if (mode === 'date') {
|
|
|
|
|
+ const candidateReady = Boolean(contextReady && link &&
|
|
|
|
|
+ !link.classList.contains('notAvailableDay') && !link.classList.contains('disabled'));
|
|
|
|
|
+ let selected = Boolean(candidateReady && link.classList.contains('selected')), clicked = false;
|
|
|
|
|
+ if (shouldClick && candidateReady && !selected) { link.click(); clicked = true; }
|
|
|
|
|
+ selected = Boolean(candidateReady && link.classList.contains('selected'));
|
|
|
|
|
+ return {contextReady, candidateCount: links.length, candidateReady, selected, clicked};
|
|
|
|
|
+}
|
|
|
|
|
+const content = all('.events-content li.selected').find(item => item.dataset.date === day);
|
|
|
|
|
+const matches = content ? all('.fascia', content).filter(slot => {
|
|
|
|
|
+ const input = slot.querySelector('#idHiddenFasciaServizio');
|
|
|
|
|
+ return input && input.value === dailyId;
|
|
|
|
|
+}) : [];
|
|
|
|
|
+const slot = matches.length === 1 ? matches[0] : null, spans = slot ? slot.querySelectorAll('span') : [];
|
|
|
|
|
+const clean = value => String(value || '').replace(/\s+/g, ' ').trim();
|
|
|
|
|
+const candidateReady = Boolean(contextReady && slot && !slot.classList.contains('notAvailableFascia') &&
|
|
|
|
|
+ spans.length === 2 && clean(spans[0].textContent) === timeLabel &&
|
|
|
|
|
+ clean(spans[1].textContent) === `(${capacity})`);
|
|
|
|
|
+let selected = Boolean(candidateReady && slot.classList.contains('act')), clicked = false;
|
|
|
|
|
+if (shouldClick && candidateReady && !selected) { slot.click(); clicked = true; }
|
|
|
|
|
+selected = Boolean(candidateReady && slot.classList.contains('act'));
|
|
|
|
|
+return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
|
|
|
|
|
+"""
|
|
|
|
|
+def _runtime_id(value):
|
|
|
|
|
+ value = str(value).strip()
|
|
|
|
|
+ if not value or len(value) > 128:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar service id is invalid")
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _request_day(value):
|
|
|
|
|
+ try:
|
|
|
|
|
+ return date.fromisoformat(str(value))
|
|
|
|
|
+ except ValueError:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar date format changed") from None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def read_calendar_context(page):
|
|
|
|
|
+ if same_origin_path(page.url) != CALENDAR_PATH:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar page is not current")
|
|
|
|
|
+ raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
|
|
|
|
|
+ if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar context is not ready")
|
|
|
|
|
+ return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def read_calendar_service(page):
|
|
|
|
|
+ return read_calendar_context(page)[0]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
|
|
|
|
|
+ deadline = time.monotonic() + timeout
|
|
|
|
|
+ while time.monotonic() < deadline:
|
|
|
|
|
+ if session_is_current() is not True:
|
|
|
|
|
+ raise CalendarBookError("Italy applicant Session changed")
|
|
|
try:
|
|
try:
|
|
|
- self.page.wait.doc_loaded()
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
|
|
+ service = read_calendar_service(page)
|
|
|
|
|
+ except CalendarBookError:
|
|
|
|
|
+ time.sleep(0.1)
|
|
|
|
|
+ continue
|
|
|
|
|
+ if expected_service and service != _runtime_id(expected_service):
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar service changed")
|
|
|
|
|
+ return service
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar service did not initialize")
|
|
|
|
|
|
|
|
- @guard(text="Sorry, you have been blocked", priority=6)
|
|
|
|
|
- @guard(text="You are being rate limited", priority=6)
|
|
|
|
|
- @guard(text="Cloudflare Ray ID", priority=6)
|
|
|
|
|
- @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
|
|
|
|
|
- def on_cloudflare_blocked(self):
|
|
|
|
|
- pass
|
|
|
|
|
|
|
|
|
|
- @guard(title="just a moment", priority=7)
|
|
|
|
|
- def on_cloudflare_turnstile_challenge(self):
|
|
|
|
|
- self.log("🛡️ 检测到 Cloudflare 5秒盾挑战,正在尝试穿透...")
|
|
|
|
|
- if self.cf_bypasser.bypass(max_retry=3):
|
|
|
|
|
- self.plugin._random_sleep(3, 5)
|
|
|
|
|
- self.cf_bypasser.handle_waiting_room()
|
|
|
|
|
-
|
|
|
|
|
- @guard(title="waitting room", priority=7)
|
|
|
|
|
- def on_cloudflare_waiting_room(self):
|
|
|
|
|
- self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...")
|
|
|
|
|
- self.cf_bypasser.handle_waiting_room()
|
|
|
|
|
- time.sleep(2)
|
|
|
|
|
-
|
|
|
|
|
- # --- 状态流转与表单处理 (Priority 35~45) ---
|
|
|
|
|
- @on(ele="#pingid-button", priority=45)
|
|
|
|
|
- def handle_initial_landing_page(self):
|
|
|
|
|
- self.log("[State] Initial Landing Page detected. Clicking login button...")
|
|
|
|
|
- login_btn = self.page.ele('#pingid-button')
|
|
|
|
|
- if login_btn:
|
|
|
|
|
- self.plugin.mouse.human_click_ele(login_btn)
|
|
|
|
|
- self.log("Redirecting to PingID...")
|
|
|
|
|
- self.plugin._random_sleep(3, 5)
|
|
|
|
|
|
|
+def _calendar_post(page, path, payload, parser):
|
|
|
|
|
+ response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
|
|
|
|
|
+ status, host = response.status_code, urlparse(str(response.url or "")).hostname
|
|
|
|
|
+ if host == "iam.esteri.it" or status == 401:
|
|
|
|
|
+ raise CalendarAuthenticationExpiredError("Italy Calendar authentication expired")
|
|
|
|
|
+ if status == 403:
|
|
|
|
|
+ raise CalendarAccessDeniedError("Italy Calendar access denied")
|
|
|
|
|
+ if status == 429:
|
|
|
|
|
+ raise CalendarRateLimitedError("Italy Calendar rate limited")
|
|
|
|
|
+ if status in {0, 408, 502, 503, 504}:
|
|
|
|
|
+ raise CalendarTransientError("Italy Calendar temporarily unavailable")
|
|
|
|
|
+ if status != 200 or same_origin_path(response.url) != path:
|
|
|
|
|
+ raise CalendarGateError("Italy Calendar returned an unexpected response")
|
|
|
|
|
+ try:
|
|
|
|
|
+ return parser(response.text)
|
|
|
|
|
+ except ItaProtocolError as exc:
|
|
|
|
|
+ raise CalendarGateError(f"Italy Calendar response rejected ({exc.code})") from exc
|
|
|
|
|
|
|
|
- @on(ele="@name=callback_1", priority=40)
|
|
|
|
|
- def handle_pingid_login_form(self):
|
|
|
|
|
- if self.has_submitted_login:
|
|
|
|
|
- return
|
|
|
|
|
- self.log("[State] PingID Login Form detected. Submitting credentials...")
|
|
|
|
|
- username = self.plugin.config.account.username
|
|
|
|
|
- password = self.plugin.config.account.password
|
|
|
|
|
-
|
|
|
|
|
- self.log("Entering username...")
|
|
|
|
|
- user_input = self.page.ele('@name=callback_1')
|
|
|
|
|
- self.plugin.mouse.human_click_ele(user_input)
|
|
|
|
|
- user_input.input(username, clear=True)
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
|
|
|
|
|
- self.log("Entering password...")
|
|
|
|
|
- pwd_input = self.page.ele('@type=password')
|
|
|
|
|
- self.plugin.mouse.human_click_ele(pwd_input)
|
|
|
|
|
- pwd_input.input(password, clear=True)
|
|
|
|
|
|
|
+def fetch_calendar_month(page, service, selected_day):
|
|
|
|
|
+ selected = selected_day.strftime("%d/%m/%Y")
|
|
|
|
|
+ return _calendar_post(
|
|
|
|
|
+ page, AVAILABILITY_PATH,
|
|
|
|
|
+ {"_Servizio": _runtime_id(service), "selectedDay": selected},
|
|
|
|
|
+ parse_calendar_availability,
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def fetch_calendar_slots(page, service, selected_day):
|
|
|
|
|
+ slots = _calendar_post(
|
|
|
|
|
+ page, TIME_SLOTS_PATH,
|
|
|
|
|
+ {"selectedDay": selected_day.isoformat(), "idService": _runtime_id(service)},
|
|
|
|
|
+ parse_time_slots,
|
|
|
|
|
+ )
|
|
|
|
|
+ if any(slot.day != selected_day for slot in slots):
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar returned slots for another day")
|
|
|
|
|
+ return slots
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def scan_until_first_available_month(
|
|
|
|
|
+ page, *, lookahead_months, log=None,
|
|
|
|
|
+ month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
|
|
|
|
|
+):
|
|
|
|
|
+ service, anchor = read_calendar_context(page)
|
|
|
|
|
+ scans = []
|
|
|
|
|
+ for index, month in enumerate(month_starts(anchor, lookahead_months)):
|
|
|
|
|
+ if index and month_click_interval_seconds:
|
|
|
|
|
+ time.sleep(month_click_interval_seconds)
|
|
|
|
|
+ days = fetch_calendar_month(page, service, month)
|
|
|
|
|
+ scans.append(days)
|
|
|
|
|
+ available = available_calendar_days(days)
|
|
|
|
|
+ if log:
|
|
|
|
|
+ log(f"Italy Calendar probe index={index} available={len(available)}")
|
|
|
|
|
+ if available:
|
|
|
|
|
+ break
|
|
|
|
|
+ return tuple(scans)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def click_next_month(page, *, timeout=10, diagnostic=None):
|
|
|
|
|
+ control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
|
|
|
|
|
+ if not control:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar next-month control is unavailable")
|
|
|
|
|
+ control.click(by_js=True)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _snapshot(page, mode, service, day, candidate=None, click=False):
|
|
|
|
|
+ candidate = candidate or SlotCandidate(day, 0, -1, datetime_time.min, datetime_time.min, "")
|
|
|
|
|
+ raw = page.run_js(
|
|
|
|
|
+ CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
|
|
|
|
|
+ candidate.time_label, candidate.slots_free, click,
|
|
|
|
|
+ )
|
|
|
|
|
+ if not isinstance(raw, dict) or not raw.get("contextReady") or raw.get("candidateCount") != 1:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar selection context changed")
|
|
|
|
|
+ return raw
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def verify_precommit_selection(page, *, runtime_service, candidate):
|
|
|
|
|
+ raw = _snapshot(
|
|
|
|
|
+ page, "slot", runtime_service, candidate.day, candidate, False)
|
|
|
|
|
+ if not raw.get("candidateReady") or not raw.get("selected"):
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar selected slot changed")
|
|
|
|
|
+ return candidate
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def select_slot_before_final(
|
|
|
|
|
+ page, *, target_day, days, slots, runtime_service,
|
|
|
|
|
+ dom_timeout=5, session_is_current=None,
|
|
|
|
|
+):
|
|
|
|
|
+ inventory = [item for item in days if item.day == target_day and item.is_available]
|
|
|
|
|
+ candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
|
|
|
|
|
+ if not inventory or not candidates:
|
|
|
|
|
+ return None
|
|
|
|
|
+ candidate, deadline = candidates[0], time.monotonic() + dom_timeout
|
|
|
|
|
+ _snapshot(page, "date", runtime_service, target_day, click=True)
|
|
|
|
|
+ while time.monotonic() < deadline:
|
|
|
|
|
+ if session_is_current and session_is_current() is not True:
|
|
|
|
|
+ raise CalendarBookError("Italy applicant Session changed")
|
|
|
|
|
+ date_state = _snapshot(page, "date", runtime_service, target_day)
|
|
|
|
|
+ slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
|
|
|
|
|
+ if date_state.get("selected") and slot_state.get("candidateReady"):
|
|
|
|
|
+ if not slot_state.get("selected"):
|
|
|
|
|
+ _snapshot(page, "slot", runtime_service, target_day, candidate, True)
|
|
|
|
|
+ return verify_precommit_selection(
|
|
|
|
|
+ page, runtime_service=runtime_service, candidate=candidate)
|
|
|
|
|
+ time.sleep(0.1)
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar slot did not finish loading")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def book_date_preferences(user_inputs):
|
|
|
|
|
+ values = []
|
|
|
|
|
+ for key, default in (("expected_start_date", "2000-01-01"),
|
|
|
|
|
+ ("expected_end_date", "2100-01-01")):
|
|
|
|
|
+ try:
|
|
|
|
|
+ values.append(date.fromisoformat(user_inputs.get(key, default)))
|
|
|
|
|
+ except (AttributeError, TypeError, ValueError):
|
|
|
|
|
+ raise CalendarBookError(f"Italy {key} must use YYYY-MM-DD") from None
|
|
|
|
|
+ if values[0] > values[1]:
|
|
|
|
|
+ raise CalendarBookError("Italy date preference is inverted")
|
|
|
|
|
+ return tuple(values)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _move_to_month(page, service, target, timeout):
|
|
|
|
|
+ current = read_calendar_context(page)[1]
|
|
|
|
|
+ while (current.year, current.month) < target:
|
|
|
|
|
+ expected = (current.year + 1, 1) if current.month == 12 else (current.year, current.month + 1)
|
|
|
|
|
+ click_next_month(page, timeout=timeout)
|
|
|
|
|
+ deadline = time.monotonic() + timeout
|
|
|
|
|
+ while time.monotonic() < deadline:
|
|
|
|
|
+ actual_service, current = read_calendar_context(page)
|
|
|
|
|
+ if actual_service != service:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar service changed")
|
|
|
|
|
+ if (current.year, current.month) == expected:
|
|
|
|
|
+ break
|
|
|
|
|
+ time.sleep(0.1)
|
|
|
|
|
+ else:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar month did not load")
|
|
|
|
|
+ if (current.year, current.month) != target:
|
|
|
|
|
+ raise CalendarBookError("Italy Calendar cannot navigate backwards")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def recheck_calendar_before_final(
|
|
|
|
|
+ page, *, lookahead_months, start_day, end_day, session_is_current,
|
|
|
|
|
+ month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
|
|
|
|
|
+ timeout=30, dom_timeout=5, log=None,
|
|
|
|
|
+):
|
|
|
|
|
+ service, anchor = read_calendar_context(page)
|
|
|
|
|
+ for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
|
|
|
|
|
+ if session_is_current() is not True:
|
|
|
|
|
+ raise CalendarBookError("Italy applicant Session changed")
|
|
|
|
|
+ if index and month_click_interval_seconds:
|
|
|
|
|
+ time.sleep(month_click_interval_seconds)
|
|
|
|
|
+ inventory = fetch_calendar_month(page, service, month_start)
|
|
|
|
|
+ days = available_calendar_days(inventory, start_day=start_day, end_day=end_day)
|
|
|
|
|
+ selected_month = month_start.year, month_start.month
|
|
|
|
|
+ if log:
|
|
|
|
|
+ log(f"Italy Book Calendar month={month_start:%Y-%m} candidates={len(days)}")
|
|
|
|
|
+ if days:
|
|
|
|
|
+ _move_to_month(page, service, selected_month, timeout)
|
|
|
|
|
+ for item in days:
|
|
|
|
|
+ slots = fetch_calendar_slots(page, service, item.day)
|
|
|
|
|
+ candidate = select_slot_before_final(
|
|
|
|
|
+ page, target_day=item.day, days=inventory, slots=slots,
|
|
|
|
|
+ runtime_service=service, dom_timeout=dom_timeout,
|
|
|
|
|
+ session_is_current=session_is_current,
|
|
|
|
|
+ )
|
|
|
|
|
+ if candidate:
|
|
|
|
|
+ return candidate
|
|
|
|
|
+ if selected_month >= (end_day.year, end_day.month):
|
|
|
|
|
+ break
|
|
|
|
|
+ return None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+FINAL_PATH = "/BookingCalendar/InsertNewBooking"
|
|
|
|
|
+FINAL_FAILED_LABEL = "italy-final-failed"
|
|
|
|
|
+FINAL_ACCEPTED_LABEL = "italy-final-accepted"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
|
|
|
|
|
+ try:
|
|
|
|
|
+ page = plugin.page
|
|
|
|
|
+ username = plugin.config.account.username.strip().casefold()
|
|
|
|
|
+ prepared = plugin._require_calendar_context(route, role="book", username=username)
|
|
|
|
|
+ if (not username or not isinstance(slot, SlotCandidate)
|
|
|
|
|
+ or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
|
|
|
|
|
+ raise CalendarBookError("Italy final context is not current")
|
|
|
|
|
+ verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
|
|
|
|
|
+ response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
|
|
|
|
|
+ "idCalendarioGiornaliero": slot.daily_calendar_id,
|
|
|
|
|
+ "selectedDay": slot.day.isoformat(),
|
|
|
|
|
+ "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
|
|
|
|
|
+ })
|
|
|
|
|
+ data = response.json()
|
|
|
|
|
+ if (response.status_code == 200 and same_origin_path(response.url) == FINAL_PATH
|
|
|
|
|
+ and isinstance(data, dict) and not str(data.get("errorMessage", "")).strip()
|
|
|
|
|
+ and isinstance(data.get("url"), str) and data["url"].strip()):
|
|
|
|
|
+ same_origin_path(urljoin("https://prenotami.esteri.it", data["url"]))
|
|
|
|
|
+ return VSBookResult(
|
|
|
|
|
+ success=True,
|
|
|
|
|
+ account=username,
|
|
|
|
|
+ label=FINAL_ACCEPTED_LABEL,
|
|
|
|
|
+ book_date=slot.day.isoformat(),
|
|
|
|
|
+ book_time=slot.time_label,
|
|
|
|
|
+ )
|
|
|
|
|
+ except Exception as exc:
|
|
|
|
|
+ plugin._log(f"Italy final submission failed: {type(exc).__name__}")
|
|
|
|
|
+ # The next Booker signal must re-enter the form and obtain fresh IDs.
|
|
|
|
|
+ plugin._reset_calendar_state()
|
|
|
|
|
+ return VSBookResult(success=False, label=FINAL_FAILED_LABEL)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+_SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
|
|
|
+_OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", Lock())
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
|
|
|
|
|
+ if not route.booking_type or not route.purpose:
|
|
|
|
|
+ raise CalendarGateError("Italy route is missing form controls")
|
|
|
|
|
+ config = {"path": booking_path, "booking": asdict(route.booking_type),
|
|
|
|
|
+ "purpose": asdict(route.purpose)}
|
|
|
|
|
+ return f"""
|
|
|
|
|
+const cfg = {json.dumps(config, ensure_ascii=False)};
|
|
|
|
|
+const form = document.querySelector('#bookingForm');
|
|
|
|
|
+const norm = value => String(value || '').replace(/\\s+/g, ' ').trim().toLowerCase();
|
|
|
|
|
+function choose(item) {{
|
|
|
|
|
+ const control = document.getElementById(item.control_id);
|
|
|
|
|
+ const option = control && Array.from(control.options).find(value => value.value === item.value);
|
|
|
|
|
+ if (!option || !item.labels.map(norm).includes(norm(option.textContent))) return false;
|
|
|
|
|
+ if (control.value !== item.value) {{
|
|
|
|
|
+ control.value = item.value;
|
|
|
|
|
+ control.dispatchEvent(new Event('change', {{bubbles: true}}));
|
|
|
|
|
+ }}
|
|
|
|
|
+ return control.value === item.value;
|
|
|
|
|
+}}
|
|
|
|
|
+const booking = choose(cfg.booking), purpose = choose(cfg.purpose);
|
|
|
|
|
+const privacy = document.querySelector('#PrivacyCheck');
|
|
|
|
|
+if (privacy && !privacy.checked) privacy.click();
|
|
|
|
|
+const otp = document.querySelector('#otp-input'), send = document.querySelector('#otp-send');
|
|
|
|
|
+const avanti = document.querySelector('#btnAvanti');
|
|
|
|
|
+const token = document.querySelector('input[name="cf-turnstile-response"]');
|
|
|
|
|
+return {{
|
|
|
|
|
+ formReady: Boolean(location.pathname === cfg.path && form && booking && purpose && privacy && privacy.checked),
|
|
|
|
|
+ turnstileReady: Boolean(token && token.value),
|
|
|
|
|
+ otpValuePresent: Boolean(otp && otp.value.trim()),
|
|
|
|
|
+ otpSendEnabled: Boolean(send && !send.disabled),
|
|
|
|
|
+ avantiEnabled: Boolean(avanti && !avanti.disabled),
|
|
|
|
|
+}};
|
|
|
|
|
+"""
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
|
|
|
|
|
+ if type(after_otp) is not bool or type(allow_pending) is not bool:
|
|
|
|
|
+ raise CalendarGateError("Italy booking preflight policy is invalid")
|
|
|
|
|
+ if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
|
|
|
|
|
+ "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
|
|
|
|
|
+ raise CalendarGateError("Italy booking form structure changed")
|
|
|
|
|
+ if raw["otpValuePresent"] is not after_otp:
|
|
|
|
|
+ raise CalendarGateError("Italy booking OTP stage changed")
|
|
|
|
|
+ ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
|
|
|
|
|
+ raw["turnstileReady"] and raw["avantiEnabled"])
|
|
|
|
|
+ if not allow_pending and not ready:
|
|
|
|
|
+ raise CalendarGateError("Italy booking verification is not ready")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
|
|
|
|
|
+ diagnostic=None, wait_action=None, check_current=None):
|
|
|
|
|
+ deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
|
|
|
|
|
+ while time.monotonic() < deadline:
|
|
|
|
|
+ if check_current:
|
|
|
|
|
+ check_current()
|
|
|
|
|
+ raw = page.run_js(script)
|
|
|
|
|
+ validate_booking_preflight(raw, after_otp=after_otp, allow_pending=True)
|
|
|
|
|
+ form_ready = raw["formReady"] and (after_otp or raw["otpSendEnabled"])
|
|
|
|
|
+ if form_ready and raw["turnstileReady"] and raw["avantiEnabled"]:
|
|
|
|
|
+ return raw
|
|
|
|
|
+ if form_ready and not raw["turnstileReady"] and attempts < 3:
|
|
|
|
|
+ bypasser = bypasser or CloudflareBypasser(page, log=False)
|
|
|
|
|
+ try:
|
|
|
|
|
+ bypasser.click_verification_button(is_dfs=False)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+ attempts += 1
|
|
|
time.sleep(1)
|
|
time.sleep(1)
|
|
|
|
|
+ reason = ("form_pending" if not raw or not raw["formReady"] else
|
|
|
|
|
+ "otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
|
|
|
|
|
+ "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
|
|
|
|
|
+ raise CalendarGateError(f"Italy booking verification timed out: {reason}")
|
|
|
|
|
|
|
|
- self.log("Clicking submit login button...")
|
|
|
|
|
- submit_btn = self.page.ele('tag:button@type=submit')
|
|
|
|
|
- if submit_btn:
|
|
|
|
|
- self.plugin.mouse.human_click_ele(submit_btn)
|
|
|
|
|
-
|
|
|
|
|
- self.has_submitted_login = True
|
|
|
|
|
- self.log("Login form submitted. Waiting for dashboard to load...")
|
|
|
|
|
- self.plugin._random_sleep(5, 7)
|
|
|
|
|
|
|
|
|
|
- @on(ele=".app-menu", priority=35)
|
|
|
|
|
- def handle_dashboard_menu(self):
|
|
|
|
|
- self.log("[State] Dashboard Menu detected.")
|
|
|
|
|
- switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2', timeout=0.5)
|
|
|
|
|
- if switch_en_btn:
|
|
|
|
|
- self.log("Found 'English' language switch button. Clicking to change language...")
|
|
|
|
|
- self.plugin.mouse.human_click_ele(switch_en_btn)
|
|
|
|
|
- self.plugin._random_sleep(4, 6)
|
|
|
|
|
- return
|
|
|
|
|
|
|
+def _element_or_fail(page, selector):
|
|
|
|
|
+ element = page.ele(selector, timeout=5)
|
|
|
|
|
+ if not element:
|
|
|
|
|
+ raise CalendarGateError(f"Italy booking element is missing: {selector}")
|
|
|
|
|
+ return element
|
|
|
|
|
|
|
|
- book_btn = self.page.ele('@href=/Services', timeout=0.5)
|
|
|
|
|
- if book_btn:
|
|
|
|
|
- self.log("Found 'Book' menu element. Clicking to proceed to reservation...")
|
|
|
|
|
- self.plugin.mouse.human_click_ele(book_btn)
|
|
|
|
|
- self.plugin._random_sleep(4, 6)
|
|
|
|
|
|
|
+
|
|
|
|
|
+def _read_manual_otp():
|
|
|
|
|
+ value = input("Italy booking OTP: ").strip()
|
|
|
|
|
+ if not re.fullmatch(r"[0-9]{4,12}", value):
|
|
|
|
|
+ raise CalendarGateError("Italy OTP format rejected")
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _enter_otp(plugin, otp):
|
|
|
|
|
+ field = _element_or_fail(plugin.page, "#otp-input")
|
|
|
|
|
+ plugin.mouse.human_click_ele(field)
|
|
|
|
|
+ field.input(otp, clear=True)
|
|
|
|
|
+ if field.run_js("return this.value === arguments[0];", otp) is not True:
|
|
|
|
|
+ raise CalendarGateError("Italy OTP write failed")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def validate_cloud_otp_environment(mail_config, recipient):
|
|
|
|
|
+ if not isinstance(mail_config, OtpMailConfig):
|
|
|
|
|
+ raise CalendarGateError("Italy OTP mail configuration is missing")
|
|
|
|
|
+ if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
|
|
|
|
|
+ raise CalendarGateError("Italy OTP recipient is invalid")
|
|
|
|
|
+ mail_config.mailbox_for(recipient)
|
|
|
|
|
+ return recipient.strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
|
|
|
|
|
+ validate_cloud_otp_environment(mail_config, recipient)
|
|
|
|
|
+ try:
|
|
|
|
|
+ datetime.strptime(sent_at, _SENT_AT_FORMAT)
|
|
|
|
|
+ except (TypeError, ValueError):
|
|
|
|
|
+ raise CalendarGateError("Italy OTP sent time is invalid") from None
|
|
|
|
|
+ try:
|
|
|
|
|
+ body = (api or VSCloudApi.Instance()).fetch_mail_content(
|
|
|
|
|
+ email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
|
|
|
|
|
+ subject_keywords="OTP Code", body_keywords="OTP Code:",
|
|
|
|
|
+ sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
|
|
|
|
|
+ )
|
|
|
|
|
+ return parse_otp_body(body)
|
|
|
|
|
+ except Exception as exc:
|
|
|
|
|
+ message = "not permitted" if isinstance(exc, PermissionDeniedError) else "read failed"
|
|
|
|
|
+ raise CalendarGateError(f"Italy OTP mailbox {message}") from None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _wait_for_calendar(page, timeout=30):
|
|
|
|
|
+ deadline = time.monotonic() + timeout
|
|
|
|
|
+ while time.monotonic() < deadline:
|
|
|
|
|
+ if urlparse(str(page.url or "")).path.rstrip("/") == CALENDAR_PATH:
|
|
|
|
|
+ page.wait.doc_loaded()
|
|
|
return
|
|
return
|
|
|
|
|
+ time.sleep(0.25)
|
|
|
|
|
+ raise CalendarGateError("Italy AVANTI did not reach Calendar")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def prepare_calendar(plugin, route, *, role):
|
|
|
|
|
+ if role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM:
|
|
|
|
|
+ raise BizLogicError("Italy Calendar preparation requires a tourism route")
|
|
|
|
|
+ cloud = plugin.free_config.get("otp_mode") == "cloud"
|
|
|
|
|
+ if not cloud and (plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty()):
|
|
|
|
|
+ raise PermissionDeniedError("Italy Calendar requires automatic OTP or an attached terminal")
|
|
|
|
|
+ username, page, booking_path = (
|
|
|
|
|
+ plugin.config.account.username.strip().casefold(), plugin.page, plugin._booking_path(route))
|
|
|
|
|
+ if cloud:
|
|
|
|
|
+ validate_cloud_otp_environment(route.mail, username)
|
|
|
|
|
+
|
|
|
|
|
+ def current(path):
|
|
|
|
|
+ if plugin.page is not page or same_origin_path(page.url) != path:
|
|
|
|
|
+ raise CalendarGateError("Italy preparation page changed")
|
|
|
|
|
|
|
|
- self.log("[WARN] On Dashboard, but neither 'English' nor 'Book' button was found. Waiting...")
|
|
|
|
|
- time.sleep(2)
|
|
|
|
|
|
|
+ def click(selector):
|
|
|
|
|
+ current(booking_path)
|
|
|
|
|
+ plugin.mouse.human_click_ele(_element_or_fail(page, selector))
|
|
|
|
|
|
|
|
- # --- 成功终态到达 (Priority 10) ---
|
|
|
|
|
- @on(url="/Services", ele=".app-menu", priority=10)
|
|
|
|
|
|
|
+ with _OTP_INPUT_LOCK:
|
|
|
|
|
+ script = guarded_preflight_script(route, booking_path)
|
|
|
|
|
+ wait_for_booking_preflight(page, script=script, check_current=lambda: current(booking_path))
|
|
|
|
|
+ sent_at = datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
|
|
|
|
|
+ click("#otp-send")
|
|
|
|
|
+ plugin._log(f"Italy {role} OTP sent.")
|
|
|
|
|
+ otp = (fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
|
|
|
|
|
+ if cloud else _read_manual_otp())
|
|
|
|
|
+ _enter_otp(plugin, otp)
|
|
|
|
|
+ wait_for_booking_preflight(
|
|
|
|
|
+ page, script=script, after_otp=True, check_current=lambda: current(booking_path))
|
|
|
|
|
+ page.set.auto_handle_alert(accept=True)
|
|
|
|
|
+ try:
|
|
|
|
|
+ click("#btnAvanti")
|
|
|
|
|
+ _wait_for_calendar(page)
|
|
|
|
|
+ finally:
|
|
|
|
|
+ page.set.auto_handle_alert(on_off=False)
|
|
|
|
|
+ wait_for_calendar_service(
|
|
|
|
|
+ page, session_is_current=lambda: plugin.page is page,
|
|
|
|
|
+ expected_service=route.service_id,
|
|
|
|
|
+ )
|
|
|
|
|
+ plugin._record_calendar_prepared_route(route, role=role)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+BOOKING_RECHECK_NONE_AVAILABLE_LABEL = "no-availability-after-user-recheck"
|
|
|
|
|
+BOOKING_CALENDAR_PREFINAL_STOP_LABEL = "calendar-ready-before-final"
|
|
|
|
|
+RADWARE_VALIDATION_HOSTS = frozenset({"validate.perfdrive.com"})
|
|
|
|
|
+SERVICE_LINK_WAIT_SECONDS = 15
|
|
|
|
|
+SERVICES_PROBE_QUERY_MODE = "services_probe"
|
|
|
|
|
+CALENDAR_QUERY_MODE = "calendar"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class ItaAuthenticationChallengeError(BizLogicError): pass
|
|
|
|
|
+class ItaTargetServiceLinkMissingError(BizLogicError): pass
|
|
|
|
|
+class ItaCalendarTransientError(BizLogicError): pass
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@dataclass(frozen=True, repr=False, eq=False)
|
|
|
|
|
+class _PreparedCalendar:
|
|
|
|
|
+ username: str
|
|
|
|
|
+ routing_key: str
|
|
|
|
|
+ runtime_service: str
|
|
|
|
|
+ tab_id: str
|
|
|
|
|
+ role: str
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class ItaLoginFlow(BaseFlow):
|
|
|
|
|
+ """Italy page rules on the host flow engine; never resubmit credentials."""
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self, plugin):
|
|
|
|
|
+ self.plugin = plugin
|
|
|
|
|
+ self.entered = self.submitted = False
|
|
|
|
|
+ super().__init__(plugin.page, interval=3, logger=plugin._log, max_stuck_cycles=None)
|
|
|
|
|
+
|
|
|
|
|
+ def at(self, host, path):
|
|
|
|
|
+ url = urlparse(self.page.url)
|
|
|
|
|
+ return url.hostname == host and (url.path.rstrip("/") or "/") == path
|
|
|
|
|
+
|
|
|
|
|
+ @guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
|
|
|
|
|
+ def radware(self):
|
|
|
|
|
+ raise ItaAuthenticationChallengeError(
|
|
|
|
|
+ "Italy authentication requires Radware browser validation; automatic retry is disabled")
|
|
|
|
|
+
|
|
|
|
|
+ @guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
|
|
|
|
|
+ urlparse(f.page.url).netloc.lower() not in {
|
|
|
|
|
+ "prenotami.esteri.it", "iam.esteri.it", "prenotami.esteri.it:443", "iam.esteri.it:443"}, priority=2)
|
|
|
|
|
+ def foreign_origin(self):
|
|
|
|
|
+ raise BizLogicError("Italy authentication left the expected website")
|
|
|
|
|
+
|
|
|
|
|
+ @guard(predicate=lambda f: any(value in f.page.html for value in (
|
|
|
|
|
+ "Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
|
|
|
|
|
+ def blocked(self):
|
|
|
|
|
+ raise ItaAuthenticationChallengeError("Italy authentication was blocked; automatic retry is disabled")
|
|
|
|
|
+
|
|
|
|
|
+ @guard(predicate=lambda f: any(value in f.page.html for value in (
|
|
|
|
|
+ "502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
|
|
|
|
|
+ def server_error(self):
|
|
|
|
|
+ if self.entered or self.submitted:
|
|
|
|
|
+ raise BizLogicError("Italy authentication failed after login started; no resubmission")
|
|
|
|
|
+ self.page.refresh()
|
|
|
|
|
+ self.plugin._random_sleep(10, 15)
|
|
|
|
|
+
|
|
|
|
|
+ @guard(title="just a moment", priority=5)
|
|
|
|
|
+ @guard(title="cloudflare", priority=5)
|
|
|
|
|
+ def verification_pending(self):
|
|
|
|
|
+ self.log("Waiting for the website's human verification")
|
|
|
|
|
+ time.sleep(5)
|
|
|
|
|
+
|
|
|
|
|
+ @on(ele=".app-menu", predicate=lambda f: f.at("prenotami.esteri.it", "/UserArea") and
|
|
|
|
|
+ bool(f.page.ele("@href=/Services", timeout=0.2)), priority=20)
|
|
|
@done
|
|
@done
|
|
|
- def on_reached_services_page(self):
|
|
|
|
|
|
|
+ def authenticated(self):
|
|
|
|
|
+ self.plugin._log("Successfully reached authenticated /UserArea.")
|
|
|
self.plugin.session_create_time = time.time()
|
|
self.plugin.session_create_time = time.time()
|
|
|
- self.log("🎉 Successfully reached the Booking Services page! Session created successfully!")
|
|
|
|
|
|
|
+ self.plugin.is_healthy = True
|
|
|
|
|
+
|
|
|
|
|
+ @on(ele="#pingid-button", predicate=lambda f: f.at("prenotami.esteri.it", "/") and not f.entered, priority=30)
|
|
|
|
|
+ def enter(self):
|
|
|
|
|
+ self.entered = True
|
|
|
|
|
+ self.plugin.mouse.human_click_ele(self.page.ele("#pingid-button"))
|
|
|
|
|
+ self.plugin._log("Redirecting to PingID...")
|
|
|
|
|
+ self.plugin._random_sleep(3, 5)
|
|
|
|
|
+
|
|
|
|
|
+ @on(ele="@name=callback_1", predicate=lambda f: f.at("iam.esteri.it", "/signin") and not f.submitted, priority=40)
|
|
|
|
|
+ def credentials(self):
|
|
|
|
|
+ username, password, submit = [self.page.ele(selector, timeout=0.2) for selector in
|
|
|
|
|
+ ("@name=callback_1", "@name=callback_2", "tag:button@type=submit")]
|
|
|
|
|
+ if not all((username, password, submit)):
|
|
|
|
|
+ return # IAM can render its controls in separate updates.
|
|
|
|
|
+ for label, element, value in (("username", username, self.plugin.config.account.username),
|
|
|
|
|
+ ("password", password, self.plugin.config.account.password)):
|
|
|
|
|
+ self.plugin._log(f"Entering {label}...")
|
|
|
|
|
+ self.plugin.mouse.human_click_ele(element)
|
|
|
|
|
+ element.input(value, clear=True)
|
|
|
|
|
+ time.sleep(1)
|
|
|
|
|
+ self.submitted = True
|
|
|
|
|
+ self.plugin.mouse.human_click_ele(submit)
|
|
|
|
|
+ self.plugin._log("Login form submitted. Waiting for dashboard to load...")
|
|
|
|
|
+ self.plugin._random_sleep(5, 7)
|
|
|
|
|
|
|
|
|
|
|
|
|
class ItaPlugin(IVSPlg):
|
|
class ItaPlugin(IVSPlg):
|
|
|
name = "ita_plugin"
|
|
name = "ita_plugin"
|
|
|
- version = "1.0.0"
|
|
|
|
|
- description = "意大利Prenot@Mi领事预约插件 (支持拟人化交互与多领区调度)"
|
|
|
|
|
|
|
+ version = "1.0.2"
|
|
|
|
|
+ description = "意大利 Prenot@Mi 查询与预约插件"
|
|
|
|
|
|
|
|
- def __init__(self, group_id: str):
|
|
|
|
|
|
|
+ def __init__(self, group_id):
|
|
|
self.group_id = group_id
|
|
self.group_id = group_id
|
|
|
- self.config: Optional[VSPlgConfig] = None
|
|
|
|
|
- self.free_config: Dict[str, Any] = {}
|
|
|
|
|
|
|
+ self.config = None
|
|
|
|
|
+ self.free_config = {}
|
|
|
self.is_healthy = True
|
|
self.is_healthy = True
|
|
|
- self.logger = None
|
|
|
|
|
- self.page: Optional[ChromiumPage] = None
|
|
|
|
|
-
|
|
|
|
|
- # Prenotami 特有配置
|
|
|
|
|
- self._service_id = 0
|
|
|
|
|
- self.ita_url = 'https://prenotami.esteri.it'
|
|
|
|
|
- self._host = self.ita_url
|
|
|
|
|
-
|
|
|
|
|
|
|
+ self.logger = self.page = self.tunnel = None
|
|
|
|
|
+ self.ita_url = "https://prenotami.esteri.it"
|
|
|
self.instance_id = uuid.uuid4().hex[:8]
|
|
self.instance_id = uuid.uuid4().hex[:8]
|
|
|
- self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
|
|
|
|
|
|
|
+ self.root_workspace = os.path.abspath(
|
|
|
|
|
+ os.path.join("data/temp_browser_data", f"{group_id}.{self.instance_id}"))
|
|
|
self.user_data_path = os.path.join(self.root_workspace, "user_data")
|
|
self.user_data_path = os.path.join(self.root_workspace, "user_data")
|
|
|
-
|
|
|
|
|
- if not os.path.exists(self.root_workspace):
|
|
|
|
|
- os.makedirs(self.root_workspace)
|
|
|
|
|
- self.tunnel = None
|
|
|
|
|
- self.session_create_time: float = 0
|
|
|
|
|
-
|
|
|
|
|
- def set_log(self, logger: Callable[[str], None]) -> None:
|
|
|
|
|
|
|
+ os.makedirs(self.root_workspace, exist_ok=True)
|
|
|
|
|
+ self.session_create_time = 0
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+
|
|
|
|
|
+ def set_log(self, logger):
|
|
|
self.logger = logger
|
|
self.logger = logger
|
|
|
-
|
|
|
|
|
- def _log(self, message):
|
|
|
|
|
- if self.logger:
|
|
|
|
|
- self.logger(f'[ItaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
|
|
|
|
|
- else:
|
|
|
|
|
- print(f'[ItaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
|
|
|
|
|
-
|
|
|
|
|
- def _random_sleep(self, min_sec=3, max_sec=5):
|
|
|
|
|
- sleep_time = random.uniform(min_sec, max_sec)
|
|
|
|
|
- time.sleep(sleep_time)
|
|
|
|
|
-
|
|
|
|
|
- def set_config(self, config: VSPlgConfig):
|
|
|
|
|
- self.config = config
|
|
|
|
|
- self.free_config = config.free_config or {}
|
|
|
|
|
- # Service ID (e.g., 1321 for Ireland, 5059 for Guangzhou)
|
|
|
|
|
- self._service_id = self.free_config.get('service_id', 0)
|
|
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
|
|
+ def _log(self, message):
|
|
|
|
|
+ (self.logger or print)(f"[ItaPlugin] [{self.group_id}] {message}")
|
|
|
|
|
+
|
|
|
|
|
+ def _random_sleep(self, minimum=30, maximum=60):
|
|
|
|
|
+ seconds = random.uniform(minimum, maximum)
|
|
|
|
|
+ self._log(f"Anti-Rate-Limit: Sleeping for {seconds:.2f} seconds...")
|
|
|
|
|
+ time.sleep(seconds)
|
|
|
|
|
+
|
|
|
|
|
+ def set_config(self, config):
|
|
|
|
|
+ self.config, self.free_config = config, config.free_config or {}
|
|
|
|
|
+ query_mode = self.free_config.get("query_mode", SERVICES_PROBE_QUERY_MODE)
|
|
|
|
|
+ otp_mode = self.free_config.get("otp_mode")
|
|
|
|
|
+ final = self.free_config.get("final_submit_enabled", False)
|
|
|
|
|
+ if query_mode not in {SERVICES_PROBE_QUERY_MODE, CALENDAR_QUERY_MODE}:
|
|
|
|
|
+ raise BizLogicError("Italy query_mode is invalid")
|
|
|
|
|
+ if otp_mode not in {None, "manual", "cloud"}:
|
|
|
|
|
+ raise BizLogicError("Italy otp_mode is invalid")
|
|
|
|
|
+ if final is not False and not (
|
|
|
|
|
+ final is True and otp_mode in {"manual", "cloud"}
|
|
|
|
|
+ and query_mode == SERVICES_PROBE_QUERY_MODE):
|
|
|
|
|
+ raise BizLogicError("Italy final submission configuration is invalid")
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+
|
|
|
|
|
+ def _resolve_route(self, apt_type):
|
|
|
|
|
+ try:
|
|
|
|
|
+ return resolve_route_config(
|
|
|
|
|
+ self.free_config.get("apt_configs", {}), apt_type.routing_key)
|
|
|
|
|
+ except (AttributeError, ItaProtocolError) as exc:
|
|
|
|
|
+ detail = getattr(exc, "code", type(exc).__name__)
|
|
|
|
|
+ raise BizLogicError(f"Italy route configuration rejected: {detail}") from exc
|
|
|
|
|
+
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ def _booking_path(route):
|
|
|
|
|
+ return f"/Services/Booking/{route.service_id}"
|
|
|
|
|
+
|
|
|
|
|
+ def _authenticated_path(self):
|
|
|
|
|
+ host = urlparse(str(self.page.url or "")).hostname
|
|
|
|
|
+ if host == "iam.esteri.it" or self.page.ele("#pingid-button", timeout=0.2):
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy Session expired")
|
|
|
|
|
+ return same_origin_path(self.page.url)
|
|
|
|
|
+
|
|
|
|
|
+ def _reset_calendar_state(self):
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+
|
|
|
|
|
+ def _calendar_context_matches(self, route, *, role, username=None):
|
|
|
|
|
+ state = self._prepared_calendar
|
|
|
|
|
+ try:
|
|
|
|
|
+ account = self.config.account.username.strip().casefold()
|
|
|
|
|
+ return (
|
|
|
|
|
+ isinstance(state, _PreparedCalendar) and self.is_healthy and
|
|
|
|
|
+ state.tab_id == self.page.tab_id and state.username == account and
|
|
|
|
|
+ state.routing_key == route.routing_key and state.role == role and
|
|
|
|
|
+ (username is None or username == account)
|
|
|
|
|
+ )
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+ def _record_calendar_prepared_route(self, route, *, role):
|
|
|
|
|
+ try:
|
|
|
|
|
+ self._prepared_calendar = _PreparedCalendar(
|
|
|
|
|
+ self.config.account.username.strip().casefold(), route.routing_key,
|
|
|
|
|
+ read_calendar_service(self.page), self.page.tab_id, role)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+ raise BizLogicError("Italy Calendar identity is unavailable") from None
|
|
|
|
|
+
|
|
|
|
|
+ def _require_calendar_context(self, route, *, role, username=None):
|
|
|
|
|
+ if not self._calendar_context_matches(route, role=role, username=username):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar Session changed")
|
|
|
|
|
+ if read_calendar_service(self.page) != self._prepared_calendar.runtime_service:
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service changed")
|
|
|
|
|
+ return self._prepared_calendar
|
|
|
|
|
+
|
|
|
|
|
+ def _invalidate_query_session(self):
|
|
|
|
|
+ self.is_healthy = False
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+
|
|
|
|
|
+ def _calendar_failure(self, exc, role):
|
|
|
|
|
+ self._prepared_calendar = None
|
|
|
|
|
+ kinds = (
|
|
|
|
|
+ (CalendarAuthenticationExpiredError, SessionExpiredOrInvalidError, "Session expired"),
|
|
|
|
|
+ (CalendarRateLimitedError, RateLimiteddError, "rate limited"),
|
|
|
|
|
+ (CalendarAccessDeniedError, PermissionDeniedError, "access denied"),
|
|
|
|
|
+ (CalendarTransientError, ItaCalendarTransientError, "temporarily unavailable"),
|
|
|
|
|
+ )
|
|
|
|
|
+ for source, target, message in kinds:
|
|
|
|
|
+ if isinstance(exc, source):
|
|
|
|
|
+ if role == "Query" or source is CalendarAuthenticationExpiredError:
|
|
|
|
|
+ self.is_healthy = False
|
|
|
|
|
+ return target(f"Italy {role} {message}")
|
|
|
|
|
+ return BizLogicError(f"Italy {role} failed: {exc}")
|
|
|
|
|
+
|
|
|
def keep_alive(self):
|
|
def keep_alive(self):
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
- def health_check(self) -> bool:
|
|
|
|
|
|
|
+ def health_check(self):
|
|
|
if not self.is_healthy or not self.page:
|
|
if not self.is_healthy or not self.page:
|
|
|
return False
|
|
return False
|
|
|
try:
|
|
try:
|
|
|
- if not self.page.run_js("return 1;"):
|
|
|
|
|
- return False
|
|
|
|
|
|
|
+ alive = self.page.run_js("return 1;") == 1
|
|
|
except Exception:
|
|
except Exception:
|
|
|
|
|
+ alive = False
|
|
|
|
|
+ expired = self.config.session_max_life > 0 and (
|
|
|
|
|
+ time.time() - self.session_create_time > self.config.session_max_life)
|
|
|
|
|
+ if not alive or expired:
|
|
|
|
|
+ self._invalidate_query_session()
|
|
|
return False
|
|
return False
|
|
|
- if self.config.session_max_life > 0:
|
|
|
|
|
- if time.time() - self.session_create_time > self.config.session_max_life:
|
|
|
|
|
- self._log("Session expired.")
|
|
|
|
|
- return False
|
|
|
|
|
return True
|
|
return True
|
|
|
|
|
|
|
|
def create_session(self):
|
|
def create_session(self):
|
|
|
- """
|
|
|
|
|
- 全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
|
|
|
|
|
- """
|
|
|
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
|
- self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}")
|
|
|
|
|
-
|
|
|
|
|
- co, self.tunnel = init_chromium_options(
|
|
|
|
|
|
|
+ self._invalidate_query_session()
|
|
|
|
|
+ options, self.tunnel = init_chromium_options(
|
|
|
user_data_path=self.user_data_path,
|
|
user_data_path=self.user_data_path,
|
|
|
- username_seed=self.config.account.username if self.config and self.config.account else None,
|
|
|
|
|
- proxy=self.config.proxy if self.config else None,
|
|
|
|
|
|
|
+ username_seed=self.config.account.username,
|
|
|
|
|
+ proxy=self.config.proxy,
|
|
|
headless=False,
|
|
headless=False,
|
|
|
window_size="1920,1080",
|
|
window_size="1920,1080",
|
|
|
- logger=self._log
|
|
|
|
|
- )
|
|
|
|
|
-
|
|
|
|
|
- self.page = ChromiumPage(co)
|
|
|
|
|
- ita_url = self.ita_url
|
|
|
|
|
- self._log(f"Navigating to {ita_url}")
|
|
|
|
|
- self.page.get(ita_url)
|
|
|
|
|
-
|
|
|
|
|
- self._log("Init humanize tools...")
|
|
|
|
|
- self.mouse = HumanMouse(self.page, debug=False)
|
|
|
|
|
- self.keyboard = HumanKeyboard(self.page)
|
|
|
|
|
-
|
|
|
|
|
- viewport_width = self.page.rect.viewport_size[0]
|
|
|
|
|
- viewport_height = self.page.rect.viewport_size[1]
|
|
|
|
|
- init_x = random.randint(10, viewport_width - 10)
|
|
|
|
|
- init_y = random.randint(10, viewport_height - 10)
|
|
|
|
|
- self.mouse.move(init_x, init_y)
|
|
|
|
|
-
|
|
|
|
|
- # 启动 ItaLoginFlow 注解流状态机
|
|
|
|
|
- login_flow = ItaLoginFlow(
|
|
|
|
|
- self.page,
|
|
|
|
|
- plugin=self,
|
|
|
|
|
- interval=1.0
|
|
|
|
|
|
|
+ logger=self._log,
|
|
|
)
|
|
)
|
|
|
- login_flow.run(max_steps=20)
|
|
|
|
|
- self.session_create_time = time.time()
|
|
|
|
|
- self._log("🎉 ItaLoginFlow completed successfully. Session created.")
|
|
|
|
|
-
|
|
|
|
|
- def query(self, apt_type: AppointmentType) -> VSQueryResult:
|
|
|
|
|
- res = VSQueryResult()
|
|
|
|
|
- res.success = False
|
|
|
|
|
- res.availability_status = AvailabilityStatus.NoneAvailable
|
|
|
|
|
-
|
|
|
|
|
- TARGET_SERVICE = self.free_config.get('target_service', "National and Schengen Visas")
|
|
|
|
|
- REASON_FOR_VISIT = self.free_config.get('reason_for_visit', "Tourism")
|
|
|
|
|
-
|
|
|
|
|
- # 步骤 1:在服务列表中寻找并点击目标服务的 Book
|
|
|
|
|
- self._log("Waiting for service list to load...")
|
|
|
|
|
- self.page.wait.eles_loaded('@aria-controls=dataTableServices', timeout=10)
|
|
|
|
|
-
|
|
|
|
|
- self._log(f"Searching for [{TARGET_SERVICE}] Book button...")
|
|
|
|
|
- target_book_btn_xpath = f'xpath://tr[contains(., "{TARGET_SERVICE}")]//a[contains(text(), "Book")]'
|
|
|
|
|
- book_btn = self.page.ele(target_book_btn_xpath)
|
|
|
|
|
-
|
|
|
|
|
- if not book_btn:
|
|
|
|
|
- self._log(f"Target [{TARGET_SERVICE}] Book button not found, currently no slots available.")
|
|
|
|
|
- return res
|
|
|
|
|
-
|
|
|
|
|
- self.mouse.human_click_ele(book_btn)
|
|
|
|
|
- self.page.wait.load_start()
|
|
|
|
|
- time.sleep(3)
|
|
|
|
|
-
|
|
|
|
|
- # 步骤 2:填写预约表单
|
|
|
|
|
- self._log("Waiting for booking form to load...")
|
|
|
|
|
- self.page.wait.eles_loaded('#bookingForm', timeout=10)
|
|
|
|
|
-
|
|
|
|
|
- self._log("Selecting booking type & reason...")
|
|
|
|
|
- typeofbooking_ddl = self.page.ele('#typeofbookingddl')
|
|
|
|
|
- if typeofbooking_ddl:
|
|
|
|
|
- typeofbooking_ddl.select('Individual booking')
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
-
|
|
|
|
|
- reason_ddl = self.page.ele('#ddls_0')
|
|
|
|
|
- if reason_ddl:
|
|
|
|
|
- reason_ddl.select(REASON_FOR_VISIT)
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
-
|
|
|
|
|
- notes_input = self.page.ele('#BookingNotes')
|
|
|
|
|
- if notes_input:
|
|
|
|
|
- notes_input.clear()
|
|
|
|
|
- notes_input.input('N/A')
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
-
|
|
|
|
|
- # 步骤 3:处理 OTP 验证码
|
|
|
|
|
- self._log("Sending OTP code...")
|
|
|
|
|
- otp_send_btn = self.page.ele('#otp-send')
|
|
|
|
|
- if otp_send_btn:
|
|
|
|
|
- self.mouse.human_click_ele(otp_send_btn)
|
|
|
|
|
- self.page.wait.ele_displayed('#IdOtpSent', timeout=15)
|
|
|
|
|
- self._log("OTP code sent successfully.")
|
|
|
|
|
-
|
|
|
|
|
- otp_input = self.page.ele('#otp-input')
|
|
|
|
|
- if otp_input:
|
|
|
|
|
- self.mouse.human_click_ele(otp_input)
|
|
|
|
|
- otp_input.input('123456')
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
-
|
|
|
|
|
- # 步骤 4:勾选隐私政策并提交
|
|
|
|
|
- privacy_checkbox = self.page.ele('#PrivacyCheck')
|
|
|
|
|
- if privacy_checkbox and not privacy_checkbox.states.is_checked:
|
|
|
|
|
- self.mouse.human_click_ele(privacy_checkbox)
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
|
|
+ self.page = ChromiumPage(options)
|
|
|
|
|
+ self.page.get(self.ita_url)
|
|
|
|
|
+ self.mouse, self.keyboard = HumanMouse(self.page, debug=True), HumanKeyboard(self.page)
|
|
|
|
|
+ width, height = self.page.rect.viewport_size
|
|
|
|
|
+ self.mouse.move(random.randint(10, width - 10), random.randint(10, height - 10))
|
|
|
|
|
+ flow = ItaLoginFlow(self)
|
|
|
|
|
+ try:
|
|
|
|
|
+ flow.run(max_steps=40, timeout=120)
|
|
|
|
|
+ except BizLogicError:
|
|
|
|
|
+ raise
|
|
|
|
|
+ except Exception as exc:
|
|
|
|
|
+ raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
|
|
|
|
|
|
|
|
- self._log("Submitting forward form...")
|
|
|
|
|
- forward_btn = self.page.ele('#btnAvanti')
|
|
|
|
|
- if forward_btn:
|
|
|
|
|
- self.mouse.human_click_ele(forward_btn)
|
|
|
|
|
|
|
+ def query(self, apt_type):
|
|
|
|
|
+ if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
|
|
|
|
|
+ route = self._resolve_route(apt_type)
|
|
|
|
|
+ try:
|
|
|
|
|
+ if same_origin_path(self.page.url) != CALENDAR_PATH:
|
|
|
|
|
+ entry = self._enter_service(apt_type, route=route)
|
|
|
|
|
+ if not entry.success:
|
|
|
|
|
+ return entry
|
|
|
|
|
+ self._reset_calendar_state()
|
|
|
|
|
+ prepare_calendar(self, route, role="query")
|
|
|
|
|
+ self._require_calendar_context(route, role="query")
|
|
|
|
|
+ probes = scan_until_first_available_month(
|
|
|
|
|
+ self.page, lookahead_months=route.lookahead_months, log=self._log)
|
|
|
|
|
+ except CalendarGateError as exc:
|
|
|
|
|
+ raise self._calendar_failure(exc, "Query") from None
|
|
|
|
|
+ available = available_calendar_days(probes[-1])
|
|
|
|
|
+ if not available:
|
|
|
|
|
+ return VSQueryResult(
|
|
|
|
|
+ success=False, apt_type=apt_type,
|
|
|
|
|
+ availability_status=AvailabilityStatus.NoneAvailable)
|
|
|
|
|
+ earliest = datetime.combine(available[0].day, datetime.min.time())
|
|
|
|
|
+ self._log(f"Italy Calendar earliest_date={earliest.date().isoformat()}")
|
|
|
|
|
+ return VSQueryResult(
|
|
|
|
|
+ success=True, apt_type=apt_type,
|
|
|
|
|
+ availability_status=AvailabilityStatus.Available,
|
|
|
|
|
+ earliest_date=earliest,
|
|
|
|
|
+ availability=[DateAvailability(date=earliest, times=[])])
|
|
|
|
|
|
|
|
|
|
+ def _enter_service(self, apt_type, *, route=None):
|
|
|
|
|
+ route, path = route or self._resolve_route(apt_type), None
|
|
|
|
|
+ booking_path = self._booking_path(route)
|
|
|
|
|
+ self.page.get(f"{self.ita_url}/Services")
|
|
|
|
|
+ self.page.wait.doc_loaded()
|
|
|
|
|
+ if self._authenticated_path() != "/Services":
|
|
|
|
|
+ raise BizLogicError("Italy service list is unavailable")
|
|
|
|
|
+ link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
|
|
|
|
|
+ if not link:
|
|
|
|
|
+ raise ItaTargetServiceLinkMissingError(f"Italy service link is missing: {booking_path}")
|
|
|
|
|
+ self.mouse.human_click_ele(link)
|
|
|
self.page.wait.load_start()
|
|
self.page.wait.load_start()
|
|
|
- self._log(f"Form submitted. Current page: {self.page.url}")
|
|
|
|
|
- time.sleep(3)
|
|
|
|
|
-
|
|
|
|
|
- return res
|
|
|
|
|
-
|
|
|
|
|
- def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
|
|
|
|
|
- res = VSBookResult()
|
|
|
|
|
- res.success = False
|
|
|
|
|
- user_inputs = user_inputs or {}
|
|
|
|
|
-
|
|
|
|
|
- if not slot_info.availability:
|
|
|
|
|
- raise NotFoundError("No slots to book")
|
|
|
|
|
-
|
|
|
|
|
- target_dt = slot_info.availability[0].date
|
|
|
|
|
- target_date = target_dt.strftime("%Y-%m-%d") if target_dt else ""
|
|
|
|
|
- target_slot = slot_info.availability[0].times[0] if slot_info.availability[0].times else None
|
|
|
|
|
- slot_id = target_slot.label if target_slot else ""
|
|
|
|
|
- slot_text = target_slot.time if target_slot else ""
|
|
|
|
|
-
|
|
|
|
|
- # 1. 获取 OTP (GenerateOTP)
|
|
|
|
|
- self._log("Requesting OTP...")
|
|
|
|
|
- otp_url = f"{self._host}/BookingCalendar/GenerateOTP?ServiceID={self._service_id}"
|
|
|
|
|
- self._perform_request("POST", otp_url)
|
|
|
|
|
-
|
|
|
|
|
- # 2. 等待并读取邮件
|
|
|
|
|
- self._log("Waiting for email code...")
|
|
|
|
|
- time.sleep(10)
|
|
|
|
|
- email_account = self.config.account.username if self.config and self.config.account else ""
|
|
|
|
|
- otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
|
|
|
|
|
-
|
|
|
|
|
- if not otp_code:
|
|
|
|
|
- raise BizLogicError("Failed to retrieve OTP code")
|
|
|
|
|
- self._log(f"Got OTP: {otp_code}")
|
|
|
|
|
-
|
|
|
|
|
- # 3. 提交详细信息 (Fill User Info)
|
|
|
|
|
- self._log("Submitting User Details & Files...")
|
|
|
|
|
- passport_pdf_path = user_inputs.get('passport_pdf_path')
|
|
|
|
|
- irp_pdf_path = user_inputs.get('irp_pdf_path')
|
|
|
|
|
-
|
|
|
|
|
- def file_to_b64(path):
|
|
|
|
|
- if not path or not os.path.exists(path):
|
|
|
|
|
- return ""
|
|
|
|
|
- with open(path, "rb") as f:
|
|
|
|
|
- return base64.b64encode(f.read()).decode('utf-8')
|
|
|
|
|
-
|
|
|
|
|
- ppt_b64 = file_to_b64(passport_pdf_path)
|
|
|
|
|
- irp_b64 = file_to_b64(irp_pdf_path)
|
|
|
|
|
-
|
|
|
|
|
- submit_url = f"{self._host}/Services/Booking/{self._service_id}"
|
|
|
|
|
-
|
|
|
|
|
- js_submit = f"""
|
|
|
|
|
- const url = "{submit_url}";
|
|
|
|
|
- const fd = new FormData();
|
|
|
|
|
-
|
|
|
|
|
- fd.append('ServizioDescrizione', 'D Visa Application');
|
|
|
|
|
- fd.append('MessaggioRassicuranteWaitingList', 'True');
|
|
|
|
|
- fd.append('isWaitingListEnabled', 'False');
|
|
|
|
|
- fd.append('IDServizioConsolare', '35');
|
|
|
|
|
- fd.append('IDServizioErogato', '{self._service_id}');
|
|
|
|
|
- fd.append('IdTipoPrenotazione', '1');
|
|
|
|
|
- fd.append('NumMaxAccompagnatori', '3');
|
|
|
|
|
- fd.append('NumAccompagnatoriSelected', '0');
|
|
|
|
|
-
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._Id', '61738');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
|
|
|
|
|
-
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._Id', '61739');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
|
|
|
|
|
-
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._Id', '61740');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
|
|
|
|
|
-
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
|
|
|
|
|
- fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42');
|
|
|
|
|
-
|
|
|
|
|
- fd.append('otp-input', '{otp_code}');
|
|
|
|
|
- fd.append('PrivacyCheck', 'true');
|
|
|
|
|
-
|
|
|
|
|
- async function addFile(b64, name, filename) {{
|
|
|
|
|
- if(!b64) return;
|
|
|
|
|
- const res = await fetch(`data:application/pdf;base64,${{b64}}`);
|
|
|
|
|
- const blob = await res.blob();
|
|
|
|
|
- fd.append(name, blob, filename);
|
|
|
|
|
- }}
|
|
|
|
|
-
|
|
|
|
|
- await Promise.all([
|
|
|
|
|
- addFile('{ppt_b64}', 'File_0', 'passport.pdf'),
|
|
|
|
|
- addFile('{irp_b64}', 'File_1', 'irp.pdf')
|
|
|
|
|
- ]);
|
|
|
|
|
-
|
|
|
|
|
- return fetch(url, {{
|
|
|
|
|
- method: 'POST',
|
|
|
|
|
- body: fd
|
|
|
|
|
- }}).then(async r => {{
|
|
|
|
|
- return {{ status: r.status, url: r.url, text: await r.text() }};
|
|
|
|
|
- }}).catch(e => {{ return {{ status: 0, text: e.toString() }}; }});
|
|
|
|
|
- """
|
|
|
|
|
-
|
|
|
|
|
- result_dict = self.page.run_js(js_submit)
|
|
|
|
|
- resp = BrowserResponse(result_dict)
|
|
|
|
|
-
|
|
|
|
|
- if resp.status_code == 302 or "BookingCalendar" in resp.url:
|
|
|
|
|
- self._log("User Info Submitted Successfully.")
|
|
|
|
|
- else:
|
|
|
|
|
- self._log(f"User Info Submit Failed: {resp.text[:100]}")
|
|
|
|
|
- if "Codice errato" in resp.text:
|
|
|
|
|
- raise BizLogicError("Invalid OTP Code")
|
|
|
|
|
- return res
|
|
|
|
|
-
|
|
|
|
|
- # 4. 最终确认预约 (InsertNewBooking)
|
|
|
|
|
- self._log("Finalizing Booking...")
|
|
|
|
|
- final_url = f"{self._host}/BookingCalendar/InsertNewBooking"
|
|
|
|
|
- final_payload = {
|
|
|
|
|
- "idCalendarioGiornaliero": slot_id,
|
|
|
|
|
- "selectedDay": target_date,
|
|
|
|
|
- "selectedHour": slot_text
|
|
|
|
|
- }
|
|
|
|
|
- resp_final = self._perform_request("POST", final_url, data=final_payload)
|
|
|
|
|
-
|
|
|
|
|
- if resp_final.status_code == 200:
|
|
|
|
|
- self._log("Booking Confirmed!")
|
|
|
|
|
- res.success = True
|
|
|
|
|
- res.book_date = target_date
|
|
|
|
|
- res.book_time = slot_text
|
|
|
|
|
- else:
|
|
|
|
|
- self._log(f"Final Booking Failed: {resp_final.status_code}")
|
|
|
|
|
-
|
|
|
|
|
- return res
|
|
|
|
|
-
|
|
|
|
|
- def _perform_request(self, method, url, headers=None, data=None, json_data=None):
|
|
|
|
|
- """在浏览器上下文中注入执行 Fetch"""
|
|
|
|
|
- if not self.page:
|
|
|
|
|
- raise BizLogicError("Browser not initialized")
|
|
|
|
|
- return perform_browser_fetch(
|
|
|
|
|
- self.page,
|
|
|
|
|
- method=method,
|
|
|
|
|
- url=url,
|
|
|
|
|
- headers=headers,
|
|
|
|
|
- data=data,
|
|
|
|
|
- json_data=json_data
|
|
|
|
|
- )
|
|
|
|
|
|
|
+ self.page.wait.doc_loaded()
|
|
|
|
|
+ path = self._authenticated_path()
|
|
|
|
|
+ empty = VSQueryResult(
|
|
|
|
|
+ success=False, apt_type=apt_type,
|
|
|
|
|
+ availability_status=AvailabilityStatus.NoneAvailable)
|
|
|
|
|
+ if path == "/Services":
|
|
|
|
|
+ marker = self.page.ele("#WNotAvailable", timeout=1)
|
|
|
|
|
+ notice = self.page.ele(".jconfirm-content", timeout=1)
|
|
|
|
|
+ text = ((marker.attr("value") if marker else "") or
|
|
|
|
|
+ (notice.text if notice else "") or "").strip().casefold()
|
|
|
|
|
+ if text and ("posti disponibili" in text or marker):
|
|
|
|
|
+ return empty
|
|
|
|
|
+ raise BizLogicError("Italy service returned an unknown response")
|
|
|
|
|
+ if path != booking_path or not self.page.ele("#bookingForm", timeout=2):
|
|
|
|
|
+ raise BizLogicError("Italy booking form is unavailable")
|
|
|
|
|
+ return VSQueryResult(
|
|
|
|
|
+ success=True, apt_type=apt_type,
|
|
|
|
|
+ availability_status=AvailabilityStatus.NoneAvailable)
|
|
|
|
|
|
|
|
- def _parse_valid_days(self, text: str) -> List[str]:
|
|
|
|
|
- days = []
|
|
|
|
|
|
|
+ def book(self, slot_info, user_inputs=None):
|
|
|
|
|
+ if not self.page or not isinstance(slot_info, VSQueryResult):
|
|
|
|
|
+ raise BizLogicError("Italy Book requires a Query signal")
|
|
|
|
|
+ route = self._resolve_route(slot_info.apt_type)
|
|
|
|
|
+ inputs = user_inputs if isinstance(user_inputs, Mapping) else {}
|
|
|
|
|
+ username = str(inputs.get("username", "")).strip().casefold()
|
|
|
|
|
+ if not username or username != self.config.account.username.strip().casefold():
|
|
|
|
|
+ raise BizLogicError("Italy Book requires the applicant account")
|
|
|
|
|
+ if self._prepared_calendar is None:
|
|
|
|
|
+ entry = self._enter_service(slot_info.apt_type, route=route)
|
|
|
|
|
+ if not entry.success:
|
|
|
|
|
+ return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
|
|
|
+ prepare_calendar(self, route, role="book")
|
|
|
try:
|
|
try:
|
|
|
- matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
|
|
|
|
|
- for d_str, rem in matches:
|
|
|
|
|
- if int(rem) != -1:
|
|
|
|
|
- dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
|
|
|
|
|
- days.append(dt.strftime("%Y-%m-%d"))
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
- return days
|
|
|
|
|
-
|
|
|
|
|
- def _parse_time_slots(self, text: str) -> List[Dict[str, Any]]:
|
|
|
|
|
- slots = []
|
|
|
|
|
- try:
|
|
|
|
|
- raw_list = json.loads(text)
|
|
|
|
|
- for item in raw_list:
|
|
|
|
|
- remain = item.get('SlotRimanenti', -1)
|
|
|
|
|
- if remain > 0:
|
|
|
|
|
- start = item['OrarioInizioFascia']
|
|
|
|
|
- end = item['OrarioFineFascia']
|
|
|
|
|
- s_time = f"{start['Hours']:02d}:{start['Minutes']:02d}"
|
|
|
|
|
- e_time = f"{end['Hours']:02d}:{end['Minutes']:02d}"
|
|
|
|
|
- slots.append({
|
|
|
|
|
- 'id': item['IDCalendarioServizioGiornaliero'],
|
|
|
|
|
- 'start': s_time,
|
|
|
|
|
- 'end': e_time,
|
|
|
|
|
- 'remain': remain
|
|
|
|
|
- })
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
- return slots
|
|
|
|
|
|
|
+ start, end = book_date_preferences(inputs)
|
|
|
|
|
+ slot = recheck_calendar_before_final(
|
|
|
|
|
+ self.page,
|
|
|
|
|
+ lookahead_months=route.lookahead_months,
|
|
|
|
|
+ start_day=start,
|
|
|
|
|
+ end_day=end,
|
|
|
|
|
+ session_is_current=lambda: self._calendar_context_matches(
|
|
|
|
|
+ route, role="book", username=username),
|
|
|
|
|
+ log=self._log,
|
|
|
|
|
+ )
|
|
|
|
|
+ except CalendarGateError as exc:
|
|
|
|
|
+ raise self._calendar_failure(exc, "Book") from None
|
|
|
|
|
+ if not slot:
|
|
|
|
|
+ return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
|
|
|
+ self._log(f"Italy Book selected {slot.day} {slot.time_label}")
|
|
|
|
|
+ if self.free_config.get("final_submit_enabled") is True:
|
|
|
|
|
+ return _submit_final_once(self, route, slot)
|
|
|
|
|
+ return VSBookResult(success=False, label=BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
|
|
|
|
|
|
|
|
def cleanup(self):
|
|
def cleanup(self):
|
|
|
- """销毁浏览器并彻底删除临时文件"""
|
|
|
|
|
- cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
|
|
|
|
|
- self.page = None
|
|
|
|
|
- self.tunnel = None
|
|
|
|
|
-
|
|
|
|
|
- def get_plugin_status(self) -> PluginStatus:
|
|
|
|
|
- account_name = self.config.account.username if self.config and self.config.account else ""
|
|
|
|
|
- proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
|
|
|
|
|
- current_url = ""
|
|
|
|
|
- if self.page:
|
|
|
|
|
- try:
|
|
|
|
|
- current_url = self.page.url
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
-
|
|
|
|
|
- session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
|
|
|
|
|
- state = "running" if self.is_healthy else "unhealthy"
|
|
|
|
|
|
|
+ self._invalidate_query_session()
|
|
|
|
|
+ cleanup_browser_workspace(
|
|
|
|
|
+ self.page, self.root_workspace, self.tunnel, self._log)
|
|
|
|
|
+ self.page = self.tunnel = None
|
|
|
|
|
|
|
|
|
|
+ def get_plugin_status(self):
|
|
|
|
|
+ proxy = self.config.proxy if self.config else None
|
|
|
return PluginStatus(
|
|
return PluginStatus(
|
|
|
instance_id=self.instance_id,
|
|
instance_id=self.instance_id,
|
|
|
is_healthy=self.is_healthy,
|
|
is_healthy=self.is_healthy,
|
|
|
- state=state,
|
|
|
|
|
- current_url=current_url,
|
|
|
|
|
- account=account_name,
|
|
|
|
|
- proxy=proxy_info,
|
|
|
|
|
- session_age_sec=session_age,
|
|
|
|
|
|
|
+ state="running" if self.is_healthy else "unhealthy",
|
|
|
|
|
+ current_url=str(self.page.url if self.page else ""),
|
|
|
|
|
+ account=self.config.account.username if self.config else "",
|
|
|
|
|
+ proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
|
|
|
|
|
+ session_age_sec=0,
|
|
|
last_active_at=utc_now_str(),
|
|
last_active_at=utc_now_str(),
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
def __del__(self):
|
|
def __del__(self):
|
|
|
- """
|
|
|
|
|
- 析构函数:当对象被垃圾回收时自动调用
|
|
|
|
|
- """
|
|
|
|
|
- self.cleanup()
|
|
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.cleanup()
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|