|
@@ -20,7 +20,7 @@ from DrissionPage import ChromiumPage
|
|
|
import vs_plg as _ita_host
|
|
import vs_plg as _ita_host
|
|
|
from vs_plg import IVSPlg
|
|
from vs_plg import IVSPlg
|
|
|
from vs_types import (
|
|
from vs_types import (
|
|
|
- AvailabilityStatus, BizLogicError,
|
|
|
|
|
|
|
+ AvailabilityStatus, BizException, BizLogicError, NotFoundError,
|
|
|
DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
|
|
DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
|
|
|
SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
|
|
SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
|
|
|
)
|
|
)
|
|
@@ -325,18 +325,15 @@ TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
|
|
|
DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
|
|
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):
|
|
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")
|
|
|
|
|
|
|
+ try:
|
|
|
|
|
+ parsed = urlparse(str(raw_url or ""))
|
|
|
|
|
+ port = parsed.port
|
|
|
|
|
+ except ValueError:
|
|
|
|
|
+ raise BizLogicError("Italy request left the expected origin") from None
|
|
|
|
|
+ if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
|
|
|
|
|
+ or port not in (None, 443) or parsed.username is not None):
|
|
|
|
|
+ raise BizLogicError("Italy request left the expected origin")
|
|
|
return parsed.path
|
|
return parsed.path
|
|
|
|
|
|
|
|
|
|
|
|
@@ -374,9 +371,11 @@ selected = Boolean(candidateReady && slot.classList.contains('act'));
|
|
|
return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
|
|
return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
|
|
|
"""
|
|
"""
|
|
|
def _runtime_id(value):
|
|
def _runtime_id(value):
|
|
|
|
|
+ if value is None or isinstance(value, bool):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service id is invalid")
|
|
|
value = str(value).strip()
|
|
value = str(value).strip()
|
|
|
- if not value or len(value) > 128:
|
|
|
|
|
- raise CalendarBookError("Italy Calendar service id is invalid")
|
|
|
|
|
|
|
+ if not re.fullmatch(r"[1-9]\d{0,127}", value):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service id is invalid")
|
|
|
return value
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
@@ -384,64 +383,71 @@ def _request_day(value):
|
|
|
try:
|
|
try:
|
|
|
return date.fromisoformat(str(value))
|
|
return date.fromisoformat(str(value))
|
|
|
except ValueError:
|
|
except ValueError:
|
|
|
- raise CalendarBookError("Italy Calendar date format changed") from None
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar date format changed") from None
|
|
|
|
|
|
|
|
|
|
|
|
|
def read_calendar_context(page):
|
|
def read_calendar_context(page):
|
|
|
if same_origin_path(page.url) != CALENDAR_PATH:
|
|
if same_origin_path(page.url) != CALENDAR_PATH:
|
|
|
- raise CalendarBookError("Italy Calendar page is not current")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar page is not current")
|
|
|
raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
|
|
raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
|
|
|
if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
|
|
if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
|
|
|
- raise CalendarBookError("Italy Calendar context is not ready")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar context is not ready")
|
|
|
return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
|
|
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):
|
|
def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
|
|
|
deadline = time.monotonic() + timeout
|
|
deadline = time.monotonic() + timeout
|
|
|
while time.monotonic() < deadline:
|
|
while time.monotonic() < deadline:
|
|
|
if session_is_current() is not True:
|
|
if session_is_current() is not True:
|
|
|
- raise CalendarBookError("Italy applicant Session changed")
|
|
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy applicant Session changed")
|
|
|
try:
|
|
try:
|
|
|
- service = read_calendar_service(page)
|
|
|
|
|
- except CalendarBookError:
|
|
|
|
|
|
|
+ service = read_calendar_context(page)[0]
|
|
|
|
|
+ except BizLogicError:
|
|
|
time.sleep(0.1)
|
|
time.sleep(0.1)
|
|
|
continue
|
|
continue
|
|
|
if expected_service and service != _runtime_id(expected_service):
|
|
if expected_service and service != _runtime_id(expected_service):
|
|
|
- raise CalendarBookError("Italy Calendar service changed")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service changed")
|
|
|
return service
|
|
return service
|
|
|
- raise CalendarBookError("Italy Calendar service did not initialize")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service did not initialize")
|
|
|
|
|
|
|
|
|
|
|
|
|
-def _calendar_post(page, path, payload, parser):
|
|
|
|
|
- response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
|
|
|
|
|
|
|
+def _calendar_post(page, path, payload, parser, *, form=False):
|
|
|
|
|
+ try:
|
|
|
|
|
+ response = perform_browser_fetch(
|
|
|
|
|
+ page, "POST", path, **{"data" if form else "json_data": payload}, timeout=30)
|
|
|
|
|
+ except BizException:
|
|
|
|
|
+ raise
|
|
|
|
|
+ except Exception as exc:
|
|
|
|
|
+ raise BizLogicError(f"Italy Calendar request failed: {type(exc).__name__}") from exc
|
|
|
status, host = response.status_code, urlparse(str(response.url or "")).hostname
|
|
status, host = response.status_code, urlparse(str(response.url or "")).hostname
|
|
|
if host == "iam.esteri.it" or status == 401:
|
|
if host == "iam.esteri.it" or status == 401:
|
|
|
- raise CalendarAuthenticationExpiredError("Italy Calendar authentication expired")
|
|
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
|
|
|
if status == 403:
|
|
if status == 403:
|
|
|
- raise CalendarAccessDeniedError("Italy Calendar access denied")
|
|
|
|
|
|
|
+ raise PermissionDeniedError("Italy Calendar access denied")
|
|
|
if status == 429:
|
|
if status == 429:
|
|
|
- raise CalendarRateLimitedError("Italy Calendar rate limited")
|
|
|
|
|
|
|
+ raise RateLimiteddError("Italy Calendar rate limited")
|
|
|
|
|
+ if status == 404:
|
|
|
|
|
+ raise NotFoundError("Italy Calendar endpoint is unavailable")
|
|
|
if status in {0, 408, 502, 503, 504}:
|
|
if status in {0, 408, 502, 503, 504}:
|
|
|
- raise CalendarTransientError("Italy Calendar temporarily unavailable")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar temporarily unavailable")
|
|
|
if status != 200 or same_origin_path(response.url) != path:
|
|
if status != 200 or same_origin_path(response.url) != path:
|
|
|
- raise CalendarGateError("Italy Calendar returned an unexpected response")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar returned an unexpected response")
|
|
|
try:
|
|
try:
|
|
|
return parser(response.text)
|
|
return parser(response.text)
|
|
|
- except ItaProtocolError as exc:
|
|
|
|
|
- raise CalendarGateError(f"Italy Calendar response rejected ({exc.code})") from exc
|
|
|
|
|
|
|
+ except (ValueError, TypeError) as exc:
|
|
|
|
|
+ raise BizLogicError(
|
|
|
|
|
+ f"Italy Calendar response rejected ({getattr(exc, 'code', type(exc).__name__)})") from exc
|
|
|
|
|
|
|
|
|
|
|
|
|
def fetch_calendar_month(page, service, selected_day):
|
|
def fetch_calendar_month(page, service, selected_day):
|
|
|
selected = selected_day.strftime("%d/%m/%Y")
|
|
selected = selected_day.strftime("%d/%m/%Y")
|
|
|
- return _calendar_post(
|
|
|
|
|
|
|
+ days = _calendar_post(
|
|
|
page, AVAILABILITY_PATH,
|
|
page, AVAILABILITY_PATH,
|
|
|
{"_Servizio": _runtime_id(service), "selectedDay": selected},
|
|
{"_Servizio": _runtime_id(service), "selectedDay": selected},
|
|
|
parse_calendar_availability,
|
|
parse_calendar_availability,
|
|
|
)
|
|
)
|
|
|
|
|
+ if any(item.day.replace(day=1) != selected_day.replace(day=1) for item in days):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar returned dates for another month")
|
|
|
|
|
+ return days
|
|
|
|
|
|
|
|
|
|
|
|
|
def fetch_calendar_slots(page, service, selected_day):
|
|
def fetch_calendar_slots(page, service, selected_day):
|
|
@@ -451,12 +457,12 @@ def fetch_calendar_slots(page, service, selected_day):
|
|
|
parse_time_slots,
|
|
parse_time_slots,
|
|
|
)
|
|
)
|
|
|
if any(slot.day != selected_day for slot in slots):
|
|
if any(slot.day != selected_day for slot in slots):
|
|
|
- raise CalendarBookError("Italy Calendar returned slots for another day")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar returned slots for another day")
|
|
|
return slots
|
|
return slots
|
|
|
|
|
|
|
|
|
|
|
|
|
def scan_until_first_available_month(
|
|
def scan_until_first_available_month(
|
|
|
- page, *, lookahead_months, log=None,
|
|
|
|
|
|
|
+ page, *, lookahead_months, log=None, check_current=None,
|
|
|
month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
|
|
month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
|
|
|
):
|
|
):
|
|
|
service, anchor = read_calendar_context(page)
|
|
service, anchor = read_calendar_context(page)
|
|
@@ -464,7 +470,11 @@ def scan_until_first_available_month(
|
|
|
for index, month in enumerate(month_starts(anchor, lookahead_months)):
|
|
for index, month in enumerate(month_starts(anchor, lookahead_months)):
|
|
|
if index and month_click_interval_seconds:
|
|
if index and month_click_interval_seconds:
|
|
|
time.sleep(month_click_interval_seconds)
|
|
time.sleep(month_click_interval_seconds)
|
|
|
|
|
+ if check_current:
|
|
|
|
|
+ check_current()
|
|
|
days = fetch_calendar_month(page, service, month)
|
|
days = fetch_calendar_month(page, service, month)
|
|
|
|
|
+ if check_current:
|
|
|
|
|
+ check_current()
|
|
|
scans.append(days)
|
|
scans.append(days)
|
|
|
available = available_calendar_days(days)
|
|
available = available_calendar_days(days)
|
|
|
if log:
|
|
if log:
|
|
@@ -474,10 +484,10 @@ def scan_until_first_available_month(
|
|
|
return tuple(scans)
|
|
return tuple(scans)
|
|
|
|
|
|
|
|
|
|
|
|
|
-def click_next_month(page, *, timeout=10, diagnostic=None):
|
|
|
|
|
|
|
+def click_next_month(page, *, timeout=10):
|
|
|
control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
|
|
control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
|
|
|
if not control:
|
|
if not control:
|
|
|
- raise CalendarBookError("Italy Calendar next-month control is unavailable")
|
|
|
|
|
|
|
+ raise NotFoundError("Italy Calendar next-month control is unavailable")
|
|
|
control.click(by_js=True)
|
|
control.click(by_js=True)
|
|
|
|
|
|
|
|
|
|
|
|
@@ -487,16 +497,22 @@ def _snapshot(page, mode, service, day, candidate=None, click=False):
|
|
|
CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
|
|
CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
|
|
|
candidate.time_label, candidate.slots_free, click,
|
|
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")
|
|
|
|
|
|
|
+ if (not isinstance(raw, dict) or type(raw.get("candidateCount")) is not int
|
|
|
|
|
+ or any(type(raw.get(key)) is not bool for key in (
|
|
|
|
|
+ "contextReady", "candidateReady", "selected", "clicked"))
|
|
|
|
|
+ or not raw["contextReady"] or raw["candidateCount"] not in (0, 1)
|
|
|
|
|
+ or (raw["candidateCount"] == 0 and (mode != "slot" or click
|
|
|
|
|
+ or raw["candidateReady"] or raw["selected"] or raw["clicked"]))):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar selection context changed")
|
|
|
return raw
|
|
return raw
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_precommit_selection(page, *, runtime_service, candidate):
|
|
def verify_precommit_selection(page, *, runtime_service, candidate):
|
|
|
raw = _snapshot(
|
|
raw = _snapshot(
|
|
|
page, "slot", runtime_service, candidate.day, candidate, False)
|
|
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")
|
|
|
|
|
|
|
+ if (not candidate.is_available or raw["candidateCount"] != 1
|
|
|
|
|
+ or not raw["candidateReady"] or not raw["selected"]):
|
|
|
|
|
+ raise BizLogicError("Italy Calendar selected slot changed")
|
|
|
return candidate
|
|
return candidate
|
|
|
|
|
|
|
|
|
|
|
|
@@ -509,10 +525,12 @@ def select_slot_before_final(
|
|
|
if not inventory or not candidates:
|
|
if not inventory or not candidates:
|
|
|
return None
|
|
return None
|
|
|
candidate, deadline = candidates[0], time.monotonic() + dom_timeout
|
|
candidate, deadline = candidates[0], time.monotonic() + dom_timeout
|
|
|
|
|
+ if session_is_current and session_is_current() is not True:
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy applicant Session changed")
|
|
|
_snapshot(page, "date", runtime_service, target_day, click=True)
|
|
_snapshot(page, "date", runtime_service, target_day, click=True)
|
|
|
while time.monotonic() < deadline:
|
|
while time.monotonic() < deadline:
|
|
|
if session_is_current and session_is_current() is not True:
|
|
if session_is_current and session_is_current() is not True:
|
|
|
- raise CalendarBookError("Italy applicant Session changed")
|
|
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy applicant Session changed")
|
|
|
date_state = _snapshot(page, "date", runtime_service, target_day)
|
|
date_state = _snapshot(page, "date", runtime_service, target_day)
|
|
|
slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
|
|
slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
|
|
|
if date_state.get("selected") and slot_state.get("candidateReady"):
|
|
if date_state.get("selected") and slot_state.get("candidateReady"):
|
|
@@ -521,7 +539,7 @@ def select_slot_before_final(
|
|
|
return verify_precommit_selection(
|
|
return verify_precommit_selection(
|
|
|
page, runtime_service=runtime_service, candidate=candidate)
|
|
page, runtime_service=runtime_service, candidate=candidate)
|
|
|
time.sleep(0.1)
|
|
time.sleep(0.1)
|
|
|
- raise CalendarBookError("Italy Calendar slot did not finish loading")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar slot did not finish loading")
|
|
|
|
|
|
|
|
|
|
|
|
|
def book_date_preferences(user_inputs):
|
|
def book_date_preferences(user_inputs):
|
|
@@ -531,9 +549,9 @@ def book_date_preferences(user_inputs):
|
|
|
try:
|
|
try:
|
|
|
values.append(date.fromisoformat(user_inputs.get(key, default)))
|
|
values.append(date.fromisoformat(user_inputs.get(key, default)))
|
|
|
except (AttributeError, TypeError, ValueError):
|
|
except (AttributeError, TypeError, ValueError):
|
|
|
- raise CalendarBookError(f"Italy {key} must use YYYY-MM-DD") from None
|
|
|
|
|
|
|
+ raise BizLogicError(f"Italy {key} must use YYYY-MM-DD") from None
|
|
|
if values[0] > values[1]:
|
|
if values[0] > values[1]:
|
|
|
- raise CalendarBookError("Italy date preference is inverted")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy date preference is inverted")
|
|
|
return tuple(values)
|
|
return tuple(values)
|
|
|
|
|
|
|
|
|
|
|
|
@@ -546,14 +564,14 @@ def _move_to_month(page, service, target, timeout):
|
|
|
while time.monotonic() < deadline:
|
|
while time.monotonic() < deadline:
|
|
|
actual_service, current = read_calendar_context(page)
|
|
actual_service, current = read_calendar_context(page)
|
|
|
if actual_service != service:
|
|
if actual_service != service:
|
|
|
- raise CalendarBookError("Italy Calendar service changed")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar service changed")
|
|
|
if (current.year, current.month) == expected:
|
|
if (current.year, current.month) == expected:
|
|
|
break
|
|
break
|
|
|
time.sleep(0.1)
|
|
time.sleep(0.1)
|
|
|
else:
|
|
else:
|
|
|
- raise CalendarBookError("Italy Calendar month did not load")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar month did not load")
|
|
|
if (current.year, current.month) != target:
|
|
if (current.year, current.month) != target:
|
|
|
- raise CalendarBookError("Italy Calendar cannot navigate backwards")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy Calendar cannot navigate backwards")
|
|
|
|
|
|
|
|
|
|
|
|
|
def recheck_calendar_before_final(
|
|
def recheck_calendar_before_final(
|
|
@@ -564,7 +582,7 @@ def recheck_calendar_before_final(
|
|
|
service, anchor = read_calendar_context(page)
|
|
service, anchor = read_calendar_context(page)
|
|
|
for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
|
|
for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
|
|
|
if session_is_current() is not True:
|
|
if session_is_current() is not True:
|
|
|
- raise CalendarBookError("Italy applicant Session changed")
|
|
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy applicant Session changed")
|
|
|
if index and month_click_interval_seconds:
|
|
if index and month_click_interval_seconds:
|
|
|
time.sleep(month_click_interval_seconds)
|
|
time.sleep(month_click_interval_seconds)
|
|
|
inventory = fetch_calendar_month(page, service, month_start)
|
|
inventory = fetch_calendar_month(page, service, month_start)
|
|
@@ -594,36 +612,37 @@ FINAL_ACCEPTED_LABEL = "italy-final-accepted"
|
|
|
|
|
|
|
|
|
|
|
|
|
def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
|
|
def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
|
|
|
|
|
+ result = VSBookResult(success=False, label=FINAL_FAILED_LABEL)
|
|
|
try:
|
|
try:
|
|
|
page = plugin.page
|
|
page = plugin.page
|
|
|
username = plugin.config.account.username.strip().casefold()
|
|
username = plugin.config.account.username.strip().casefold()
|
|
|
prepared = plugin._require_calendar_context(route, role="book", username=username)
|
|
prepared = plugin._require_calendar_context(route, role="book", username=username)
|
|
|
if (not username or not isinstance(slot, SlotCandidate)
|
|
if (not username or not isinstance(slot, SlotCandidate)
|
|
|
or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
|
|
or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
|
|
|
- raise CalendarBookError("Italy final context is not current")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy final context is not current")
|
|
|
verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
|
|
verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
|
|
|
- response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
|
|
|
|
|
|
|
+ data = _calendar_post(page, FINAL_PATH, {
|
|
|
"idCalendarioGiornaliero": slot.daily_calendar_id,
|
|
"idCalendarioGiornaliero": slot.daily_calendar_id,
|
|
|
"selectedDay": slot.day.isoformat(),
|
|
"selectedDay": slot.day.isoformat(),
|
|
|
"selectedHour": f"{slot.time_label}\n({slot.slots_free})",
|
|
"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)
|
|
|
|
|
|
|
+ }, json.loads, form=True)
|
|
|
|
|
+ if not isinstance(data, dict) or not isinstance(data.get("errorMessage"), str):
|
|
|
|
|
+ raise BizLogicError("Italy final response is missing its result")
|
|
|
|
|
+ if data["errorMessage"].strip():
|
|
|
|
|
+ return result
|
|
|
|
|
+ destination = data.get("url")
|
|
|
|
|
+ if not isinstance(destination, str) or not destination.strip():
|
|
|
|
|
+ raise BizLogicError("Italy final response is missing its receipt URL")
|
|
|
|
|
+ path = same_origin_path(urljoin("https://prenotami.esteri.it", destination.strip()))
|
|
|
|
|
+ if not re.fullmatch(r"/Reservation/?|/ReservationDetail/Index/[^/]+/?", path):
|
|
|
|
|
+ raise BizLogicError("Italy final response did not lead to a receipt")
|
|
|
|
|
+ result = VSBookResult(success=True, account=username, label=FINAL_ACCEPTED_LABEL,
|
|
|
|
|
+ book_date=slot.day.isoformat(), book_time=slot.time_label)
|
|
|
|
|
+ return result
|
|
|
|
|
+ finally:
|
|
|
|
|
+ if not result.success:
|
|
|
|
|
+ # The next Booker signal must prepare again and obtain fresh IDs.
|
|
|
|
|
+ plugin._reset_calendar_state()
|
|
|
|
|
|
|
|
|
|
|
|
|
_SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
_SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
@@ -632,7 +651,7 @@ _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", L
|
|
|
|
|
|
|
|
def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
|
|
def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
|
|
|
if not route.booking_type or not route.purpose:
|
|
if not route.booking_type or not route.purpose:
|
|
|
- raise CalendarGateError("Italy route is missing form controls")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy route is missing form controls")
|
|
|
config = {"path": booking_path, "booking": asdict(route.booking_type),
|
|
config = {"path": booking_path, "booking": asdict(route.booking_type),
|
|
|
"purpose": asdict(route.purpose)}
|
|
"purpose": asdict(route.purpose)}
|
|
|
return f"""
|
|
return f"""
|
|
@@ -667,20 +686,20 @@ return {{
|
|
|
|
|
|
|
|
def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
|
|
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:
|
|
if type(after_otp) is not bool or type(allow_pending) is not bool:
|
|
|
- raise CalendarGateError("Italy booking preflight policy is invalid")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy booking preflight policy is invalid")
|
|
|
if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
|
|
if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
|
|
|
"formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
|
|
"formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
|
|
|
- raise CalendarGateError("Italy booking form structure changed")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy booking form structure changed")
|
|
|
if raw["otpValuePresent"] is not after_otp:
|
|
if raw["otpValuePresent"] is not after_otp:
|
|
|
- raise CalendarGateError("Italy booking OTP stage changed")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy booking OTP stage changed")
|
|
|
ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
|
|
ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
|
|
|
raw["turnstileReady"] and raw["avantiEnabled"])
|
|
raw["turnstileReady"] and raw["avantiEnabled"])
|
|
|
if not allow_pending and not ready:
|
|
if not allow_pending and not ready:
|
|
|
- raise CalendarGateError("Italy booking verification is not ready")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy booking verification is not ready")
|
|
|
|
|
|
|
|
|
|
|
|
|
def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
|
|
def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
|
|
|
- diagnostic=None, wait_action=None, check_current=None):
|
|
|
|
|
|
|
+ check_current=None):
|
|
|
deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
|
|
deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
|
|
|
while time.monotonic() < deadline:
|
|
while time.monotonic() < deadline:
|
|
|
if check_current:
|
|
if check_current:
|
|
@@ -701,20 +720,20 @@ def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
|
|
|
reason = ("form_pending" if not raw or not raw["formReady"] else
|
|
reason = ("form_pending" if not raw or not raw["formReady"] else
|
|
|
"otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
|
|
"otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
|
|
|
"turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
|
|
"turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
|
|
|
- raise CalendarGateError(f"Italy booking verification timed out: {reason}")
|
|
|
|
|
|
|
+ raise BizLogicError(f"Italy booking verification timed out: {reason}")
|
|
|
|
|
|
|
|
|
|
|
|
|
def _element_or_fail(page, selector):
|
|
def _element_or_fail(page, selector):
|
|
|
element = page.ele(selector, timeout=5)
|
|
element = page.ele(selector, timeout=5)
|
|
|
if not element:
|
|
if not element:
|
|
|
- raise CalendarGateError(f"Italy booking element is missing: {selector}")
|
|
|
|
|
|
|
+ raise NotFoundError(f"Italy booking element is missing: {selector}")
|
|
|
return element
|
|
return element
|
|
|
|
|
|
|
|
|
|
|
|
|
def _read_manual_otp():
|
|
def _read_manual_otp():
|
|
|
value = input("Italy booking OTP: ").strip()
|
|
value = input("Italy booking OTP: ").strip()
|
|
|
if not re.fullmatch(r"[0-9]{4,12}", value):
|
|
if not re.fullmatch(r"[0-9]{4,12}", value):
|
|
|
- raise CalendarGateError("Italy OTP format rejected")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy OTP format rejected")
|
|
|
return value
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
@@ -723,14 +742,14 @@ def _enter_otp(plugin, otp):
|
|
|
plugin.mouse.human_click_ele(field)
|
|
plugin.mouse.human_click_ele(field)
|
|
|
field.input(otp, clear=True)
|
|
field.input(otp, clear=True)
|
|
|
if field.run_js("return this.value === arguments[0];", otp) is not True:
|
|
if field.run_js("return this.value === arguments[0];", otp) is not True:
|
|
|
- raise CalendarGateError("Italy OTP write failed")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy OTP write failed")
|
|
|
|
|
|
|
|
|
|
|
|
|
def validate_cloud_otp_environment(mail_config, recipient):
|
|
def validate_cloud_otp_environment(mail_config, recipient):
|
|
|
if not isinstance(mail_config, OtpMailConfig):
|
|
if not isinstance(mail_config, OtpMailConfig):
|
|
|
- raise CalendarGateError("Italy OTP mail configuration is missing")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy OTP mail configuration is missing")
|
|
|
if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
|
|
if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
|
|
|
- raise CalendarGateError("Italy OTP recipient is invalid")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy OTP recipient is invalid")
|
|
|
mail_config.mailbox_for(recipient)
|
|
mail_config.mailbox_for(recipient)
|
|
|
return recipient.strip()
|
|
return recipient.strip()
|
|
|
|
|
|
|
@@ -740,7 +759,7 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
|
|
|
try:
|
|
try:
|
|
|
datetime.strptime(sent_at, _SENT_AT_FORMAT)
|
|
datetime.strptime(sent_at, _SENT_AT_FORMAT)
|
|
|
except (TypeError, ValueError):
|
|
except (TypeError, ValueError):
|
|
|
- raise CalendarGateError("Italy OTP sent time is invalid") from None
|
|
|
|
|
|
|
+ raise BizLogicError("Italy OTP sent time is invalid") from None
|
|
|
try:
|
|
try:
|
|
|
body = (api or VSCloudApi.Instance()).fetch_mail_content(
|
|
body = (api or VSCloudApi.Instance()).fetch_mail_content(
|
|
|
email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
|
|
email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
|
|
@@ -748,9 +767,25 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
|
|
|
sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
|
|
sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
|
|
|
)
|
|
)
|
|
|
return parse_otp_body(body)
|
|
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
|
|
|
|
|
|
|
+ except ItaProtocolError as exc:
|
|
|
|
|
+ raise BizLogicError(f"Italy OTP body invalid ({exc.code})") from None
|
|
|
|
|
+ except PermissionDeniedError:
|
|
|
|
|
+ raise PermissionDeniedError("Italy OTP mailbox not permitted") from None
|
|
|
|
|
+ except SessionExpiredOrInvalidError:
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy OTP mailbox session expired") from None
|
|
|
|
|
+ except RateLimiteddError:
|
|
|
|
|
+ raise RateLimiteddError("Italy OTP mailbox rate limited") from None
|
|
|
|
|
+ except NotFoundError:
|
|
|
|
|
+ raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
|
|
|
|
|
+ except BizLogicError as exc:
|
|
|
|
|
+ status = re.search(r"\bHTTP Error (\d{3})\b", str(getattr(exc, "message", "")))
|
|
|
|
|
+ if status and int(status.group(1)) == 404:
|
|
|
|
|
+ raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
|
|
|
|
|
+ if status and int(status.group(1)) in {408, 502, 503, 504}:
|
|
|
|
|
+ raise BizLogicError("Italy OTP mailbox provider timed out") from None
|
|
|
|
|
+ raise BizLogicError("Italy OTP mailbox read failed") from None
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ raise BizLogicError("Italy OTP mailbox read failed") from None
|
|
|
|
|
|
|
|
|
|
|
|
|
def _wait_for_calendar(page, timeout=30):
|
|
def _wait_for_calendar(page, timeout=30):
|
|
@@ -760,7 +795,7 @@ def _wait_for_calendar(page, timeout=30):
|
|
|
page.wait.doc_loaded()
|
|
page.wait.doc_loaded()
|
|
|
return
|
|
return
|
|
|
time.sleep(0.25)
|
|
time.sleep(0.25)
|
|
|
- raise CalendarGateError("Italy AVANTI did not reach Calendar")
|
|
|
|
|
|
|
+ raise BizLogicError("Italy AVANTI did not reach Calendar")
|
|
|
|
|
|
|
|
|
|
|
|
|
def prepare_calendar(plugin, route, *, role):
|
|
def prepare_calendar(plugin, route, *, role):
|
|
@@ -776,7 +811,7 @@ def prepare_calendar(plugin, route, *, role):
|
|
|
|
|
|
|
|
def current(path):
|
|
def current(path):
|
|
|
if plugin.page is not page or same_origin_path(page.url) != path:
|
|
if plugin.page is not page or same_origin_path(page.url) != path:
|
|
|
- raise CalendarGateError("Italy preparation page changed")
|
|
|
|
|
|
|
+ raise SessionExpiredOrInvalidError("Italy preparation page changed")
|
|
|
|
|
|
|
|
def click(selector):
|
|
def click(selector):
|
|
|
current(booking_path)
|
|
current(booking_path)
|
|
@@ -814,11 +849,6 @@ SERVICES_PROBE_QUERY_MODE = "services_probe"
|
|
|
CALENDAR_QUERY_MODE = "calendar"
|
|
CALENDAR_QUERY_MODE = "calendar"
|
|
|
|
|
|
|
|
|
|
|
|
|
-class ItaAuthenticationChallengeError(BizLogicError): pass
|
|
|
|
|
-class ItaTargetServiceLinkMissingError(BizLogicError): pass
|
|
|
|
|
-class ItaCalendarTransientError(BizLogicError): pass
|
|
|
|
|
-
|
|
|
|
|
-
|
|
|
|
|
@dataclass(frozen=True, repr=False, eq=False)
|
|
@dataclass(frozen=True, repr=False, eq=False)
|
|
|
class _PreparedCalendar:
|
|
class _PreparedCalendar:
|
|
|
username: str
|
|
username: str
|
|
@@ -842,7 +872,7 @@ class ItaLoginFlow(BaseFlow):
|
|
|
|
|
|
|
|
@guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
|
|
@guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
|
|
|
def radware(self):
|
|
def radware(self):
|
|
|
- raise ItaAuthenticationChallengeError(
|
|
|
|
|
|
|
+ raise PermissionDeniedError(
|
|
|
"Italy authentication requires Radware browser validation; automatic retry is disabled")
|
|
"Italy authentication requires Radware browser validation; automatic retry is disabled")
|
|
|
|
|
|
|
|
@guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
|
|
@guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
|
|
@@ -854,7 +884,7 @@ class ItaLoginFlow(BaseFlow):
|
|
|
@guard(predicate=lambda f: any(value in f.page.html for value in (
|
|
@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)
|
|
"Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
|
|
|
def blocked(self):
|
|
def blocked(self):
|
|
|
- raise ItaAuthenticationChallengeError("Italy authentication was blocked; automatic retry is disabled")
|
|
|
|
|
|
|
+ raise PermissionDeniedError("Italy authentication was blocked; automatic retry is disabled")
|
|
|
|
|
|
|
|
@guard(predicate=lambda f: any(value in f.page.html for value in (
|
|
@guard(predicate=lambda f: any(value in f.page.html for value in (
|
|
|
"502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
|
|
"502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
|
|
@@ -905,7 +935,7 @@ class ItaLoginFlow(BaseFlow):
|
|
|
|
|
|
|
|
class ItaPlugin(IVSPlg):
|
|
class ItaPlugin(IVSPlg):
|
|
|
name = "ita_plugin"
|
|
name = "ita_plugin"
|
|
|
- version = "1.0.2"
|
|
|
|
|
|
|
+ version = "1.0.3"
|
|
|
description = "意大利 Prenot@Mi 查询与预约插件"
|
|
description = "意大利 Prenot@Mi 查询与预约插件"
|
|
|
|
|
|
|
|
def __init__(self, group_id):
|
|
def __init__(self, group_id):
|
|
@@ -987,7 +1017,7 @@ class ItaPlugin(IVSPlg):
|
|
|
try:
|
|
try:
|
|
|
self._prepared_calendar = _PreparedCalendar(
|
|
self._prepared_calendar = _PreparedCalendar(
|
|
|
self.config.account.username.strip().casefold(), route.routing_key,
|
|
self.config.account.username.strip().casefold(), route.routing_key,
|
|
|
- read_calendar_service(self.page), self.page.tab_id, role)
|
|
|
|
|
|
|
+ read_calendar_context(self.page)[0], self.page.tab_id, role)
|
|
|
except Exception:
|
|
except Exception:
|
|
|
self._prepared_calendar = None
|
|
self._prepared_calendar = None
|
|
|
raise BizLogicError("Italy Calendar identity is unavailable") from None
|
|
raise BizLogicError("Italy Calendar identity is unavailable") from None
|
|
@@ -995,7 +1025,7 @@ class ItaPlugin(IVSPlg):
|
|
|
def _require_calendar_context(self, route, *, role, username=None):
|
|
def _require_calendar_context(self, route, *, role, username=None):
|
|
|
if not self._calendar_context_matches(route, role=role, username=username):
|
|
if not self._calendar_context_matches(route, role=role, username=username):
|
|
|
raise BizLogicError("Italy Calendar Session changed")
|
|
raise BizLogicError("Italy Calendar Session changed")
|
|
|
- if read_calendar_service(self.page) != self._prepared_calendar.runtime_service:
|
|
|
|
|
|
|
+ if read_calendar_context(self.page)[0] != self._prepared_calendar.runtime_service:
|
|
|
raise BizLogicError("Italy Calendar service changed")
|
|
raise BizLogicError("Italy Calendar service changed")
|
|
|
return self._prepared_calendar
|
|
return self._prepared_calendar
|
|
|
|
|
|
|
@@ -1003,21 +1033,6 @@ class ItaPlugin(IVSPlg):
|
|
|
self.is_healthy = False
|
|
self.is_healthy = False
|
|
|
self._prepared_calendar = None
|
|
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
|
|
|
|
|
|
|
@@ -1038,6 +1053,11 @@ class ItaPlugin(IVSPlg):
|
|
|
def create_session(self):
|
|
def create_session(self):
|
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
|
self._invalidate_query_session()
|
|
self._invalidate_query_session()
|
|
|
|
|
+ account = getattr(self.config, "account", None)
|
|
|
|
|
+ username, password = getattr(account, "username", None), getattr(account, "password", None)
|
|
|
|
|
+ if (not isinstance(username, str) or not username.strip()
|
|
|
|
|
+ or not isinstance(password, str) or not password):
|
|
|
|
|
+ raise BizLogicError("Italy website username and password are required")
|
|
|
options, self.tunnel = init_chromium_options(
|
|
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,
|
|
username_seed=self.config.account.username,
|
|
@@ -1054,27 +1074,27 @@ class ItaPlugin(IVSPlg):
|
|
|
flow = ItaLoginFlow(self)
|
|
flow = ItaLoginFlow(self)
|
|
|
try:
|
|
try:
|
|
|
flow.run(max_steps=40, timeout=120)
|
|
flow.run(max_steps=40, timeout=120)
|
|
|
- except BizLogicError:
|
|
|
|
|
|
|
+ except BizException:
|
|
|
raise
|
|
raise
|
|
|
except Exception as exc:
|
|
except Exception as exc:
|
|
|
raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
|
|
raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
|
|
|
|
|
|
|
|
def query(self, apt_type):
|
|
def query(self, apt_type):
|
|
|
- if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
|
|
|
|
|
|
|
+ if self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
|
|
|
|
|
+ raise BizLogicError("Italy Query requires query_mode=calendar")
|
|
|
|
|
+ if not self.health_check():
|
|
|
raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
|
|
raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
|
|
|
route = self._resolve_route(apt_type)
|
|
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
|
|
|
|
|
|
|
+ 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,
|
|
|
|
|
+ check_current=lambda: self._require_calendar_context(route, role="query"))
|
|
|
available = available_calendar_days(probes[-1])
|
|
available = available_calendar_days(probes[-1])
|
|
|
if not available:
|
|
if not available:
|
|
|
return VSQueryResult(
|
|
return VSQueryResult(
|
|
@@ -1097,7 +1117,7 @@ class ItaPlugin(IVSPlg):
|
|
|
raise BizLogicError("Italy service list is unavailable")
|
|
raise BizLogicError("Italy service list is unavailable")
|
|
|
link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
|
|
link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
|
|
|
if not link:
|
|
if not link:
|
|
|
- raise ItaTargetServiceLinkMissingError(f"Italy service link is missing: {booking_path}")
|
|
|
|
|
|
|
+ raise NotFoundError(f"Italy service link is missing: {booking_path}")
|
|
|
self.mouse.human_click_ele(link)
|
|
self.mouse.human_click_ele(link)
|
|
|
self.page.wait.load_start()
|
|
self.page.wait.load_start()
|
|
|
self.page.wait.doc_loaded()
|
|
self.page.wait.doc_loaded()
|
|
@@ -1132,19 +1152,16 @@ class ItaPlugin(IVSPlg):
|
|
|
if not entry.success:
|
|
if not entry.success:
|
|
|
return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
|
prepare_calendar(self, route, role="book")
|
|
prepare_calendar(self, route, role="book")
|
|
|
- try:
|
|
|
|
|
- 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
|
|
|
|
|
|
|
+ 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,
|
|
|
|
|
+ )
|
|
|
if not slot:
|
|
if not slot:
|
|
|
return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
|
|
|
self._log(f"Italy Book selected {slot.day} {slot.time_label}")
|
|
self._log(f"Italy Book selected {slot.day} {slot.time_label}")
|
|
@@ -1160,14 +1177,21 @@ class ItaPlugin(IVSPlg):
|
|
|
|
|
|
|
|
def get_plugin_status(self):
|
|
def get_plugin_status(self):
|
|
|
proxy = self.config.proxy if self.config else None
|
|
proxy = self.config.proxy if self.config else None
|
|
|
|
|
+ current_url = ""
|
|
|
|
|
+ if self.page:
|
|
|
|
|
+ try:
|
|
|
|
|
+ current_url = str(self.page.url)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass # Status reporting must still work after browser disconnection.
|
|
|
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="running" if self.is_healthy else "unhealthy",
|
|
state="running" if self.is_healthy else "unhealthy",
|
|
|
- current_url=str(self.page.url if self.page else ""),
|
|
|
|
|
|
|
+ current_url=current_url,
|
|
|
account=self.config.account.username if self.config else "",
|
|
account=self.config.account.username if self.config else "",
|
|
|
proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
|
|
proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
|
|
|
- session_age_sec=0,
|
|
|
|
|
|
|
+ session_age_sec=max(0, int(time.time() - self.session_create_time))
|
|
|
|
|
+ if self.session_create_time > 0 else 0,
|
|
|
last_active_at=utc_now_str(),
|
|
last_active_at=utc_now_str(),
|
|
|
)
|
|
)
|
|
|
|
|
|