Prechádzať zdrojové kódy

fix(ita): stabilize booking preflight

zhangweijp 2 mesiacov pred
rodič
commit
c6e6cb47c0
2 zmenil súbory, kde vykonal 58 pridanie a 24 odobranie
  1. 26 15
      config/test_conf.json
  2. 32 9
      plugins/ita_plugin.py

+ 26 - 15
config/test_conf.json

@@ -281,32 +281,32 @@
       }
     },
     "ita_plugin": {
-      "group_id": "ita.hong_kong",
+      "group_id": "pernotami.ie.it",
       "debug": false,
       "account": {
-        "username": "johnnyzhang.luck@gmail.com",
-        "password": "Zhangwei123"
+        "username": "waynezhang.luck@gmail.com",
+        "password": "!Wei19960506"
       },
       "appointment_types": [
         {
-          "city": "Hong Kong",
+          "city": "Dublin",
           "country": "Italy",
           "visa_type": "Tourist",
-          "routing_key": "slot.hkg.it.tourist",
+          "routing_key": "slot.dub.it.tourist",
           "weight": 10
         }
       ],
       "free_config": {
         "website": "https://prenotami.esteri.it/",
-                "query_mode": "calendar",
-                "otp_mode": "cloud",
+        "query_mode": "calendar",
+        "otp_mode": "cloud",
         "final_submit_enabled": false,
         "apt_configs": {
-                    "slot.hkg.it.tourist": {
-                        "service_id": 4937,
-                        "mail": {
-                            "authorization_source": "account"
-                        },
+          "slot.dub.it.tourist": {
+            "service_id": 1321,
+            "mail": {
+              "authorization_source": "account"
+            },
             "capability": "single_schengen_tourism",
             "calendar_scan": {
               "lookahead_months": 12
@@ -314,10 +314,16 @@
             "form": {
               "booking_type_control_id": "typeofbookingddl",
               "booking_type_value": "1",
-              "booking_type_labels": ["Prenotazione Singola", "Single booking"],
+              "booking_type_labels": [
+                "Prenotazione Singola",
+                "Single booking"
+              ],
               "purpose_control_id": "ddls_0",
               "purpose_value": "42",
-              "purpose_labels": ["Turismo", "Tourism"]
+              "purpose_labels": [
+                "Turismo",
+                "Tourism"
+              ]
             }
           }
         }
@@ -325,11 +331,16 @@
       "user_inputs": {
         "first_name": "SAN",
         "last_name": "ZHANG",
-        "email": "johnnyzhang.luck@gmail.com",
+        "email": "waynezhang.luck@gmail.com",
         "citizen": "China",
         "address": "Dublin",
         "expected_start_date": "2026-09-01",
         "expected_end_date": "2026-11-30"
+      },
+      "proxy": {
+        "proto": "http",
+        "ip": "127.0.0.1",
+        "port": 7897
       }
     },
     "bel_plugin": {

+ 32 - 9
plugins/ita_plugin.py

@@ -37,6 +37,7 @@ from utils.plugin_utils import (
 MAX_PROTOCOL_ITEMS = 512
 MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
 MAX_LOOKAHEAD_MONTHS = 120
+TURNSTILE_PASSIVE_SECONDS = 5
 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)
@@ -617,6 +618,7 @@ 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),
+  turnstilePresent: Boolean(token),
   turnstileReady: Boolean(token && token.value),
   otpValuePresent: Boolean(otp && otp.value.trim()),
   otpSendEnabled: Boolean(send && !send.disabled),
@@ -626,33 +628,51 @@ return {{
 
 
 def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
-                               check_current=None):
-    deadline, clicked, raw = time.monotonic() + timeout, False, None
+                               check_current=None, log=None):
+    deadline = time.monotonic() + timeout
+    click_after, click_attempted, pending_logged, raw = None, False, False, None
     while time.monotonic() < deadline:
         if check_current:
             check_current()
         raw = page.run_js(script)
         if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
-                "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
+                "formReady", "turnstilePresent", "turnstileReady", "otpValuePresent",
+                "otpSendEnabled", "avantiEnabled")):
             raise BizLogicError("Italy booking form structure changed")
         if raw["otpValuePresent"] is not after_otp:
             raise BizLogicError("Italy booking OTP stage changed")
         form_ready = raw["formReady"] and (after_otp or raw["otpSendEnabled"])
+        turnstile_present = raw["turnstilePresent"]
+        if turnstile_present and click_after is None:
+            click_after = time.monotonic() + TURNSTILE_PASSIVE_SECONDS
+        elif not turnstile_present:
+            click_after = None
         if form_ready and raw["turnstileReady"] and raw["avantiEnabled"]:
             return raw
-        if form_ready and not raw["turnstileReady"] and not clicked:
+        if form_ready and not raw["turnstileReady"] and log and not pending_logged:
+            log("Italy booking verification state: "
+                f"stage={'after_otp' if after_otp else 'before_otp'} "
+                f"turnstile_present={turnstile_present} "
+                f"otp_send_enabled={raw['otpSendEnabled']} "
+                f"avanti_enabled={raw['avantiEnabled']}")
+            pending_logged = True
+        if (form_ready and turnstile_present and not raw["turnstileReady"]
+                and not click_attempted and time.monotonic() >= click_after):
+            click_attempted = True
             try:
-                clicked = CloudflareBypasser(page, log=False).click_verification_button(is_dfs=False)
+                clicked = CloudflareBypasser(
+                    page, log=log is not None, logger=log).click_verification_button(is_dfs=False)
             except (PageDisconnectedError, ElementNotFoundError,
                     SessionExpiredOrInvalidError, RateLimiteddError, NotFoundError, BizLogicError):
                 raise
             except Exception as exc:
                 raise BizLogicError("Italy booking verification click failed") from exc
-            if not clicked:
-                raise BizLogicError("Italy booking verification control could not be clicked")
+            if log:
+                log(f"Italy booking verification fallback click result={clicked}.")
         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_widget_pending" if not raw["turnstilePresent"] else
               "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
     raise BizLogicError(f"Italy booking verification timed out: {reason}")
 
@@ -739,7 +759,7 @@ def prepare_calendar(plugin, route, *, role):
         plugin.mouse.human_click_ele(_element_or_fail(page, selector))
 
     script = guarded_preflight_script(route, booking_path)
-    wait_for_booking_preflight(page, script=script, check_current=current)
+    wait_for_booking_preflight(page, script=script, check_current=current, log=plugin._log)
     sent_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
     click("#otp-send")
     plugin._log(f"Italy {role} OTP sent.")
@@ -752,7 +772,7 @@ def prepare_calendar(plugin, route, *, role):
     current()
     _enter_otp(plugin, otp)
     wait_for_booking_preflight(
-        page, script=script, after_otp=True, check_current=current)
+        page, script=script, after_otp=True, check_current=current, log=plugin._log)
     page.set.auto_handle_alert(accept=True)
     try:
         click("#btnAvanti")
@@ -1097,6 +1117,9 @@ class ItaPlugin(IVSPlg):
             raise BizLogicError(f"Italy Book failed: {type(exc).__name__}") from exc
 
     def cleanup(self):
+        if getattr(self, "keep_browser_on_error", False):
+            self._log("Italy debug browser retained after test failure.")
+            return
         self._invalidate_query_session()
         cleanup_browser_workspace(
             self.page, self.root_workspace, self.tunnel, self._log)