Selaa lähdekoodia

feat: refactor pol_plugin to REST API, update de_plugin dual calendar mode, fix keygen load_proxies and enhance clash multi-port generator

hujiarui 1 kuukausi sitten
vanhempi
sitoutus
d23754a5ba
8 muutettua tiedostoa jossa 874 lisäystä ja 403 poistoa
  1. 1 0
      .gitignore
  2. 361 66
      plugins/de_plugin.py
  3. 289 273
      plugins/pol_plugin.py
  4. 1 0
      standalone.py
  5. 37 19
      supersaas_keygen.py
  6. 23 5
      tls_keygen.py
  7. 135 32
      tools/generate_clash_multi_port.py
  8. 27 8
      vfs_keygen.py

+ 1 - 0
.gitignore

@@ -90,3 +90,4 @@ AGENTS.md
 powershell.cmd
 *.yaml
 !config/local_multi_port.yaml
+data/supersaas_accounts.*

+ 361 - 66
plugins/de_plugin.py

@@ -5,7 +5,7 @@ import re
 import os
 import uuid
 import base64
-from datetime import datetime
+from datetime import datetime, timezone
 from typing import List, Dict, Optional, Any, Callable
 from DrissionPage import ChromiumPage
 
@@ -48,10 +48,11 @@ def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
 class DePlugin(IVSPlg):
     """
     Germany (Visametric) 签证预约插件 (Browser + Tunnel Mode)
+    兼容有日历选时模式 (calendarType != 0) 与无日历排队等候模式 (calendarType == 0)
     """
     name = "de_plugin"
-    version = "1.0.0"
-    description = "德国Visametric签证预约插件 (支持Cloudflare穿透与OCR验证)"
+    version = "1.1.0"
+    description = "德国Visametric签证预约插件 (支持Cloudflare穿透、OCR验证、双日历模式及完整前置校验)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -77,11 +78,28 @@ class DePlugin(IVSPlg):
         # 字符识别引擎
         self.ocr_engine: Optional[DddOcrEngine] = None
         
-        # 业务状态
+        # 业务与配置状态
         self.base_url = "https://ie-appointment.visametric.com"
         self.csrf_token = ""
         self.personal_info_val = ""
         self.email_val_control = ""
+        
+        # 动态业务参数 (默认以都柏林为例,可通过 free_config 动态覆盖)
+        self.consular_id = "1"
+        self.city_id = "6"
+        self.office_id = "1"
+        self.office_type = "1"
+        self.service_type_id = "1"
+        self.language_id = "2"
+        self.app_country_view = "Schengen - Tourism/Family&Friend Visit/Transit Visa/Other Purposes"
+        self.app_office_view = "Dublin"
+        self.app_service_type_view = "NORMAL"
+        self.nationality = "2"
+        
+        # 邮箱与 OTP 策略
+        self.use_alias_email = False
+        self.alias_domain = "text.skin"
+        self.master_email = "hujiarui8@gmail.com"
     
     def set_log(self, logger: Callable[[str], None]) -> None:
         self.logger = logger
@@ -97,6 +115,26 @@ class DePlugin(IVSPlg):
         self.free_config = config.free_config or {}
         if self.free_config.get("base_url"):
             self.base_url = self.free_config["base_url"].rstrip('/')
+        
+        self.consular_id = str(self.free_config.get("consularid", "1"))
+        self.city_id = str(self.free_config.get("city", "6"))
+        self.office_id = str(self.free_config.get("office", "1"))
+        self.office_type = str(self.free_config.get("officetype", "1"))
+        self.service_type_id = str(self.free_config.get("service_type_id", "1"))
+        self.language_id = str(self.free_config.get("language_id", "2"))
+        
+        self.app_country_view = self.free_config.get(
+            "view_set_app_country", 
+            "Schengen - Tourism/Family&Friend Visit/Transit Visa/Other Purposes"
+        )
+        self.app_office_view = self.free_config.get("view_set_app_office", "Dublin")
+        self.app_service_type_view = self.free_config.get("view_set_app_service_type", "NORMAL")
+        self.nationality = str(self.free_config.get("nationality", "2"))
+        
+        # 邮箱与验证码配置
+        self.use_alias_email = bool(self.free_config.get("use_alias_email", False))
+        self.alias_domain = self.free_config.get("alias_domain", "text.skin")
+        self.master_email = self.free_config.get("master_email", "hujiarui8@gmail.com")
             
     def keep_alive(self):
         pass
@@ -109,7 +147,7 @@ class DePlugin(IVSPlg):
                 return False
         except Exception:
             return False
-        if self.config.session_max_life > 0:
+        if self.config and self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
                 self._log("Session expired.")
                 return False
@@ -175,7 +213,7 @@ class DePlugin(IVSPlg):
             # 4. 识别验证码 (本地 OCR 服务)
             captcha_code = self.ocr_engine.inference_captcha(image_bytes)
 
-            # 5. 提交验证码 (获取 PersonalInfo)
+            # 5. 提交验证码 (获取 PersonalInfo 与 emailValControl)
             self._submit_captcha(captcha_code)
             
             self.session_create_time = time.time()
@@ -218,17 +256,137 @@ class DePlugin(IVSPlg):
         if m:
             self.csrf_token = m.group(1)
 
+    def _get_calendar_status(self) -> str:
+        """
+        向服务端发起自动探测,获取办事处日历状态:
+        "0": 无日历配额 / 等候名单 (without calendar quota)
+        "2": 正常选日历模式
+        """
+        url = f"{self.base_url}/en/getcalendarstatus"
+        payload = {
+            "getvisaofficeid": self.office_id,
+            "getservicetypeid": self.service_type_id,
+            "getvisacountryid": self.consular_id
+        }
+        headers = {
+            'X-CSRF-TOKEN': self.csrf_token,
+            'X-Requested-With': 'XMLHttpRequest'
+        }
+        resp = self._perform_request('POST', url, data=payload, headers=headers)
+        status = resp.text.strip().strip('"')
+        self._log(f"Calendar Status for Office {self.office_id}: {status}")
+        return status if status else "0"
+
+    def _confirm_without_calendar_mode(self):
+        """无日历模式下的服务确认与无配额状态校验"""
+        headers = {
+            'X-CSRF-TOKEN': self.csrf_token,
+            'X-Requested-With': 'XMLHttpRequest'
+        }
+        # 1. getservices
+        self._perform_request('POST', f"{self.base_url}/en/getservices", data={
+            "country_id": self.consular_id,
+            "service_type_id": self.service_type_id,
+            "office_id": self.office_id,
+            "languageID": self.language_id,
+            "calendarType": "0"
+        }, headers=headers)
+        
+        # 2. withoutcalendarquota
+        self._perform_request('POST', f"{self.base_url}/en/withoutcalendarquota", data={
+            "dateall": "0",
+            "personCountTotal": "1"
+        }, headers=headers)
+
+    def _pre_validate_controls(self, passport_no: str, email: str, phone_no: str, cal_status: str):
+        """
+        执行完整的个人信息校验与前置服务检查
+        对应 HAR 录制中的 entries #11 - #16 时序
+        """
+        headers = {
+            'X-CSRF-TOKEN': self.csrf_token,
+            'X-Requested-With': 'XMLHttpRequest',
+            'Referer': f"{self.base_url}/en/appointment-form"
+        }
+        
+        self._log(f"Running pre-validation controls: passport={passport_no}, email={email}, phone={phone_no}...")
+        
+        # 1. passport-control
+        self._log("[1/6] Validating passport...")
+        resp = self._perform_request('POST', f"{self.base_url}/en/personal/passport-control", data={
+            'passport[]': passport_no,
+            'country_id': self.consular_id
+        }, headers=headers)
+        self._log(f"[1/6] Passport validated (status {resp.status_code})")
+
+        # 2. email-control
+        self._log("[2/6] Validating email...")
+        resp = self._perform_request('POST', f"{self.base_url}/en/personal/email-control", data={
+            'email[]': email,
+            'country_id': self.consular_id
+        }, headers=headers)
+        self._log(f"[2/6] Email validated (status {resp.status_code})")
+
+        # 3. phone-control
+        self._log("[3/6] Validating phone...")
+        resp = self._perform_request('POST', f"{self.base_url}/en/personal/phone-control", data={
+            'phone[]': phone_no,
+            'country_id': self.consular_id
+        }, headers=headers)
+        self._log(f"[3/6] Phone validated (status {resp.status_code})")
+
+        # 4. getservices
+        self._log("[4/6] Querying services...")
+        resp = self._perform_request('POST', f"{self.base_url}/en/getservices", data={
+            "country_id": self.consular_id,
+            "service_type_id": self.service_type_id,
+            "office_id": self.office_id,
+            "languageID": self.language_id,
+            "calendarType": cal_status
+        }, headers=headers)
+        self._log(f"[4/6] Services queried (status {resp.status_code})")
+
+        # 5. withoutcalendarquota (若为无日历模式)
+        if cal_status == "0":
+            self._log("[5/6] Confirming without-calendar quota...")
+            resp = self._perform_request('POST', f"{self.base_url}/en/withoutcalendarquota", data={
+                "dateall": "0",
+                "personCountTotal": "1"
+            }, headers=headers)
+            self._log(f"[5/6] Without-calendar quota confirmed (status {resp.status_code})")
+
+        # 6. check-service-packages
+        self._log("[6/6] Checking service packages...")
+        resp = self._perform_request('POST', f"{self.base_url}/en/check-service-packages", data={}, headers=headers)
+        self._log(f"[6/6] Service packages checked (status {resp.status_code})")
+        self._log("Pre-validation controls completed successfully.")
+
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
         res = VSQueryResult()
         res.success = False
         
-        consular_id = self.free_config.get("consularid", "1")
+        cal_status = self._get_calendar_status()
+        
+        # 模式一:无日历排队模式 (如爱尔兰都柏林等候名单)
+        if cal_status == "0":
+            self._confirm_without_calendar_mode()
+            res.success = True
+            res.availability_status = AvailabilityStatus.Available
+            today = datetime.now()
+            res.earliest_date = today
+            res.availability = [
+                DateAvailability(date=today, times=[TimeSlot(time="WAITLIST")])
+            ]
+            self._log("Without-calendar mode detected: Waitlist available.")
+            return res
+        
+        # 模式二:普通有日历模式
         url = f"{self.base_url}/en/getdate"
         payload = {
-            "consularid": consular_id,
+            "consularid": self.consular_id,
             "exitid": "1",
-            "servicetypeid": "1",
-            "calendarType": "2",
+            "servicetypeid": self.service_type_id,
+            "calendarType": cal_status,
             "totalperson": "1"
         }
         
@@ -264,34 +422,70 @@ class DePlugin(IVSPlg):
     def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
         user_inputs = user_inputs or {}
-        exp_start = user_inputs.get('expected_start_date', '')
-        exp_end = user_inputs.get('expected_end_date', '')
         
-        available_dates_str = [
-            da.date.strftime("%Y-%m-%d")
-            for da in slot_info.availability
-        ]
+        # 1. 动态检测日历模式
+        cal_status = self._get_calendar_status()
         
-        valid_dates = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True)
-        if not valid_dates:
-            raise NotFoundError("No dates match constraints")
+        target_date = ""
+        time_slot = {'data_id': '', 'data_all': '', 'time': 'WAITLIST'}
         
-        target_date = random.choice(valid_dates)
-        self._log(f"Selected date: {target_date}")
+        if cal_status != "0":
+            # 有日历模式:筛选有效日期并提取 slot
+            exp_start = user_inputs.get('expected_start_date', '')
+            exp_end = user_inputs.get('expected_end_date', '')
+            
+            available_dates_str = [
+                da.date.strftime("%Y-%m-%d")
+                for da in slot_info.availability
+                if da.times and da.times[0].time != "WAITLIST"
+            ]
+            
+            valid_dates = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True)
+            if not valid_dates:
+                raise NotFoundError("No dates match constraints")
+            
+            target_date = random.choice(valid_dates)
+            self._log(f"Selected date: {target_date}")
+            time_slot = self._get_slot_time(target_date)
+        else:
+            # 无日历模式:不需要选 slot,直接以出行日期或当前日期为目标
+            target_date = user_inputs.get('travel_date', datetime.now().strftime("%Y-%m-%d"))[:10]
+            self._log(f"Booking in without-calendar mode, target date: {target_date}")
+
+        # 2. 准备邮箱和手机号
+        raw_email = user_inputs.get("email", "")
+        if self.use_alias_email:
+            booking_email = get_alias_email(raw_email, new_domain=self.alias_domain)
+        else:
+            booking_email = raw_email
+            
+        phone_no = user_inputs.get("phone_no") or user_inputs.get("phone", "")
+        passport_no = user_inputs.get("passport_no") or user_inputs.get("passport", "")
+
+        # 3. 按照 HAR 时序执行前置校验与服务检查
+        self._pre_validate_controls(passport_no, booking_email, phone_no, cal_status)
         
-        # 1. 获取时间 Slot
-        time_slot = self._get_slot_time(target_date)
+        # 4. 记录发邮件前的旧验证码与精准 UTC 时间戳,杜绝读取到历史旧邮件
+        old_otp = self._peek_latest_otp(booking_email)
+        send_time_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+        self._log(f"Pre-send snapshot: current latest OTP='{old_otp}', send_time_utc='{send_time_utc}'")
         
-        # 2. 发送邮件流程
-        alias_email = get_alias_email(user_inputs.get("email", ""), new_domain='text.skin')
-        self._send_email_step1(alias_email)
+        # 5. 发送邮箱验证码流程 (jky45fgd -> confirmCodeSendMail)
+        self._send_email_step1(booking_email)
         self._send_email_step2("0")
         
-        # 3. 读取 OTP
-        otp_code = self._read_otp_email(alias_email)
-        
-        # 4. 提交确认
-        book_res_html = self._confirm_appointment(target_date, time_slot, user_inputs, otp_code, alias_email)
+        # 6. 读取新到达的 OTP 验证码 (排除 old_otp)
+        otp_code = self._read_otp_email(booking_email, send_time_utc=send_time_utc, old_otp=old_otp)
+        
+        # 7. 提交预约确认
+        book_res_html = self._confirm_appointment(
+            target_date=target_date, 
+            slot_data=time_slot, 
+            user_inputs=user_inputs, 
+            otp=otp_code, 
+            alias_email=booking_email,
+            cal_status=cal_status
+        )
         
         if "complete all required fields" in book_res_html.lower():
             raise BizLogicError("Incomplete fields response")
@@ -355,10 +549,10 @@ class DePlugin(IVSPlg):
         payload = {
             "fulldate": converted_date,
             "totalperson": "1",
-            "set_new_consular_id": self.free_config.get("consularid", "1"),
-            "set_new_exit_office_id": "1",
+            "set_new_consular_id": self.consular_id,
+            "set_new_exit_office_id": self.office_id,
             "calendarType": "2",
-            "set_new_service_type_id": "1",
+            "set_new_service_type_id": self.service_type_id,
             "personalinfo": self.personal_info_val
         }
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
@@ -373,31 +567,114 @@ class DePlugin(IVSPlg):
         return random.choice(times)
 
     def _send_email_step1(self, email: str):
+        self._log(f"Sending OTP verification email step 1 (jky45fgd) to: {email}...")
         url = f"{self.base_url}/en/jky45fgd"
         payload = {"emailCheck": email, "personalinfo": self.personal_info_val}
-        headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
-        self._perform_request('POST', url, data=payload, headers=headers)
+        headers = {
+            'X-CSRF-TOKEN': self.csrf_token,
+            'X-Requested-With': 'XMLHttpRequest',
+            'Referer': f"{self.base_url}/en/appointment-form"
+        }
+        resp = self._perform_request('POST', url, data=payload, headers=headers)
+        self._log(f"OTP step 1 finished (status {resp.status_code})")
 
     def _send_email_step2(self, code_val: str):
+        self._log(f"Sending OTP verification email step 2 (confirmCodeSendMail) code_val={code_val}...")
         url = f"{self.base_url}/en/confirmCodeSendMail"
         payload = {"confirmCode": code_val, "emailValControl": self.email_val_control}
-        headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
-        self._perform_request('POST', url, data=payload, headers=headers)
-
-    def _read_otp_email(self, recipient: str) -> str:
-        master_email = "hujiarui8@gmail.com"
-        sender = 'Visametric - verify at visametric.com'
-        now_utc = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
-        for _ in range(12):
-            c = VSCloudApi.Instance().fetch_mail_content(master_email, sender, recipient, 'Verification Code', 'Verification code', now_utc, 300)
+        headers = {
+            'X-CSRF-TOKEN': self.csrf_token,
+            'X-Requested-With': 'XMLHttpRequest',
+            'Referer': f"{self.base_url}/en/appointment-form"
+        }
+        resp = self._perform_request('POST', url, data=payload, headers=headers)
+        self._log(f"OTP step 2 finished (status {resp.status_code})")
+
+    def _peek_latest_otp(self, recipient: str) -> str:
+        """快速查看当前邮箱里已有的旧验证码,用于发码后比对排除旧邮件"""
+        try:
+            master_email = self.master_email if self.use_alias_email else recipient
+            c = VSCloudApi.Instance().fetch_mail_content_from_top(
+                email=master_email,
+                sender="Visametric",
+                recipient=recipient,
+                subject_keywords="",
+                body_keywords="",
+                top=1
+            )
             if c:
-                m = re.search(r'\b\d{6}\b', c)
+                m = re.search(r'Verification code.*?<h2[^>]*>\s*(\d{4,6})\s*</h2>', c, re.DOTALL | re.IGNORECASE)
                 if m:
-                    return m.group(0)
+                    return m.group(1).strip()
+                m2 = re.search(r'\b\d{4,6}\b', c)
+                if m2:
+                    return m2.group(0)
+        except Exception:
+            pass
+        return ""
+
+    def _read_otp_email(self, recipient: str, send_time_utc: str = "", old_otp: str = "") -> str:
+        master_email = self.master_email if self.use_alias_email else recipient
+        sender = 'Visametric'
+        if not send_time_utc:
+            send_time_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+        self._log(f"Waiting for NEW OTP email... (recipient: '{recipient}', master: '{master_email}', sent after: {send_time_utc}, ignore old_otp='{old_otp}')")
+        for attempt in range(1, 13):
+            self._log(f"Polling OTP email (Attempt {attempt}/12)...")
+            try:
+                # 策略 1: 优先尝试带精准 sentDate(UTC) 时间戳过滤的 fetch 接口
+                c = None
+                try:
+                    c = VSCloudApi.Instance().fetch_mail_content(
+                        email=master_email,
+                        sender=sender,
+                        recipient=recipient,
+                        subject_keywords="",
+                        body_keywords="",
+                        sent_date=send_time_utc,
+                        expiry=300
+                    )
+                except Exception as e_fetch:
+                    self._log(f"Standard fetch check: {e_fetch}")
+
+                # 策略 2: 若 fetch 未立即返回,尝试 fetch-top
+                if not c:
+                    c = VSCloudApi.Instance().fetch_mail_content_from_top(
+                        email=master_email,
+                        sender=sender,
+                        recipient=recipient,
+                        subject_keywords="",
+                        body_keywords="",
+                        top=1
+                    )
+                
+                if c:
+                    cand_otp = ""
+                    # 1. 精确提取 HTML 中的 Verification code (例如 <h2> 7029 </h2>)
+                    m = re.search(r'Verification code.*?<h2[^>]*>\s*(\d{4,6})\s*</h2>', c, re.DOTALL | re.IGNORECASE)
+                    if m:
+                        cand_otp = m.group(1).strip()
+                    else:
+                        m2 = re.search(r'\b\d{4,6}\b', c)
+                        if m2:
+                            cand_otp = m2.group(0)
+
+                    if cand_otp:
+                        # 核心防抖:如果拿到的验证码与发信前捕获的历史旧验证码完全一致,说明新邮件尚未到达,继续等待!
+                        if old_otp and cand_otp == old_otp:
+                            self._log(f"Captured OTP '{cand_otp}' equals pre-send old_otp, still waiting for newly arrived email...")
+                        else:
+                            self._log(f"🎉 Successfully retrieved NEW OTP: {cand_otp}")
+                            return cand_otp
+                    else:
+                        self._log(f"Email content received but no 4-6 digit OTP found. Snippet: {c[:100]}...")
+            except Exception as e:
+                self._log(f"Warning: Exception while polling mail: {e}")
             time.sleep(5)
+        self._log("❌ OTP retrieval timed out after 12 attempts (60s).")
         raise NotFoundError("OTP timeout")
 
-    def _confirm_appointment(self, date, slot_data, user_inputs, otp, alias_email):
+    def _confirm_appointment(self, target_date: str, slot_data: Dict, user_inputs: Dict, otp: str, alias_email: str, cal_status: str = "0"):
         url = f"{self.base_url}/en/personal/appointment/create"
         def _get_dob(d):
             try:
@@ -406,44 +683,62 @@ class DePlugin(IVSPlg):
                 return datetime.now()
         dob = _get_dob(user_inputs.get('birthday', ''))
         
+        travel_dt_str = user_inputs.get('travel_date', '')[:10]
+        if travel_dt_str:
+            try:
+                travel_start = datetime.strptime(travel_dt_str, "%Y-%m-%d").strftime("%d-%m-%Y")
+            except Exception:
+                travel_start = datetime.now().strftime("%d-%m-%Y")
+        else:
+            travel_start = datetime.now().strftime("%d-%m-%Y")
+            
+        passport_exp_str = user_inputs.get('passport_expiry_date', '')[:10]
+        if passport_exp_str:
+            try:
+                passport_exp = datetime.strptime(passport_exp_str, "%Y-%m-%d").strftime("%d-%m-%Y")
+            except Exception:
+                passport_exp = ""
+        else:
+            passport_exp = ""
+
         payload = {
             "_token": self.csrf_token,
-            "country": str(self.free_config.get("consularid", "1")),
-            "visitingcountry": str(self.free_config.get("consularid", "1")),
-            "city": "6",
-            "office": "1",
-            "officetype": "1",
+            "country": str(self.consular_id),
+            "visitingcountry": str(self.consular_id),
+            "city": str(self.city_id),
+            "office": str(self.office_id),
+            "officetype": str(self.office_type),
             "totalPerson": "1",
             "name1": user_inputs.get('first_name', '').upper(),
             "surname1": user_inputs.get('last_name', '').upper(),
-            "nationality1": "2",
+            "nationality1": str(self.nationality),
             "birthday1": str(dob.day),
             "birthmonth1": str(dob.month),
             "birthyear1": str(dob.year),
-            "passport1": user_inputs.get('passport_no'),
-            "passportExpirationDate1": datetime.strptime(user_inputs.get('passport_expiry_date', '')[:10], "%Y-%m-%d").strftime("%d-%m-%Y"),
+            "passport1": user_inputs.get('passport_no', ''),
+            "passportExpirationDate1": passport_exp,
             "email1": alias_email,
-            "phone1": user_inputs.get('phone_no'),
+            "phone1": user_inputs.get('phone_no', ''),
             "alternativephone1": "",
             "mailConfirmCode": otp,
-            "ctval": slot_data['data_id'],
-            "qtallvert": slot_data['data_all'],
-            "oldofficetype": "1",
+            "ctval": slot_data.get('data_id', '') if cal_status != "0" else "",
+            "qtallvert": slot_data.get('data_all', '') if cal_status != "0" else "",
+            "oldofficetype": str(self.office_type),
             "oldtotalperson": "1",
             "rePaymentControl": "0",
-            "view_set_app_country": "Schengen - Tourism/Family&Friend Visit/Transit Visa/Other Purposes",
-            "view_set_app_office": "Dublin",
-            "view_set_app_service_type": "NORMAL",
+            "view_set_app_country": self.app_country_view,
+            "view_set_app_office": self.app_office_view,
+            "view_set_app_service_type": self.app_service_type_view,
             "cargoactive": "0",
-            "setnewcalendarstatus": "2",
+            "setnewcalendarstatus": str(cal_status),
             "availableDaycontrol": "0",
-            "travelStartDate": datetime.strptime(user_inputs.get('travel_date', '')[:10], "%Y-%m-%d").strftime("%d-%m-%Y"),
+            "travelStartDate": travel_start,
             "personalapproveTerms": "1"
         }
         
         for i in range(2, 5):
             payload.update({
-                f"name{i}": "", f"surname{i}": "", f"nationality{i}": "0", f"birthday{i}": "0", f"birthmonth{i}": "0", f"birthyear{i}": "0", f"passport{i}": "", f"passportExpirationDate{i}": "", f"email{i}": alias_email, f"phone{i}": user_inputs.get('phone_no'), f"alternativephone{i}": ""
+                f"name{i}": "", f"surname{i}": "", f"nationality{i}": "0", f"birthday{i}": "0", f"birthmonth{i}": "0", f"birthyear{i}": "0", f"passport{i}": "", f"passportExpirationDate{i}": "", f"email{i}": alias_email, f"phone{i}": user_inputs.get('phone_no', ''), f"alternativephone{i}": ""
             })
 
         headers = {'X-Requested-With': 'XMLHttpRequest'}

+ 289 - 273
plugins/pol_plugin.py

@@ -5,12 +5,11 @@ import re
 import os
 import uuid
 import base64
-from datetime import datetime
+from datetime import datetime, timezone
 from typing import List, Dict, Optional, Any, Callable
-from DrissionPage import ChromiumPage
+import requests
 
 from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
-
 from vs_plg import IVSPlg
 from vs_types import (
     VSPlgConfig, 
@@ -19,6 +18,7 @@ from vs_types import (
     VSBookResult, 
     AvailabilityStatus, 
     DateAvailability, 
+    TimeSlot,
     NotFoundError, 
     PermissionDeniedError, 
     RateLimiteddError, 
@@ -28,343 +28,362 @@ from vs_types import (
     utc_now_str
 )
 from toolkit.vs_cloud_api import VSCloudApi
-from utils.plugin_utils import (
-    BrowserResponse,
-    init_chromium_options,
-    perform_browser_fetch,
-    filter_dates_in_range,
-    cleanup_browser_workspace
-)
+from utils.plugin_utils import filter_dates_in_range
 
 
 class PolPlugin(IVSPlg):
     """
-    Poland (e-konsulat) 签证预约插件 (Browser + Tunnel Mode)
+    Poland (e-konsulat) 签证预约插件 (Pure HTTP REST API Mode)
+    基于 official e-konsulat REST API (https://api.e-konsulat.gov.pl) 与大模型视觉验证码识别
     """
     name = "pol_plugin"
-    version = "1.0.0"
-    description = "波兰e-konsulat签证预约插件 (支持验证码识别与隧道代理)"
+    version = "2.0.0"
+    description = "波兰e-konsulat签证预约插件 (纯API与大模型验证码识别)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
         self.config: Optional[VSPlgConfig] = None
         self.free_config: Dict[str, Any] = {}
-        self.logger = None
-        
-        # 浏览器实例
-        self.page: Optional[ChromiumPage] = None
+        self.logger: Optional[Callable[[str], None]] = None
         
-        # 资源隔离
+        # 资源与状态标识
         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.user_data_path = os.path.join(self.root_workspace, "user_data")
+        self.is_healthy = True
+        self.session_create_time: float = 0
         
-        if not os.path.exists(self.root_workspace):
-            os.makedirs(self.root_workspace)
-            
+        # HTTP 会话
+        self.session: Optional[requests.Session] = None
+        self.base_api_url = "https://api.e-konsulat.gov.pl"
+        
+        # 验证码识别引擎
         self.captcha_breaker = CaptchaBreaker()
         
-        self.tunnel = None  # 代理隧道
-        self.is_healthy = True
-        self.session_create_time: float = 0
-    
+        # 缓存的服务和地点映射
+        self._cached_service_locations: Dict[str, Any] = {}
+
     def set_log(self, logger: Callable[[str], None]) -> None:
         self.logger = logger
         
-    def _log(self, message): 
+    def _log(self, message: str) -> None: 
         if self.logger:
             self.logger(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
             print(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         
-    def set_config(self, config: VSPlgConfig):
+    def set_config(self, config: VSPlgConfig) -> None:
         self.config = config
         self.free_config = config.free_config or {}
+        if self.free_config.get("base_api_url"):
+            self.base_api_url = self.free_config["base_api_url"].rstrip('/')
             
-    def keep_alive(self):
+    def keep_alive(self) -> None:
         pass
 
     def health_check(self) -> bool:
         if not self.is_healthy:
             return False
-        if not self.page:
-            return False
-        try:
-            if not self.page.run_js("return 1;"):
-                return False
-        except Exception:
+        if not self.session:
             return False
-        if self.config.session_max_life > 0:
+        if self.config and self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
-                self._log("Session expired.")
+                self._log("Session expired by session_max_life.")
                 return False
         return True
 
-    def create_session(self):
+    def create_session(self) -> None:
         """
-        创建会话:启动浏览器 -> 配置代理隧道 -> 导航至首页
+        初始化 HTTP 会话、配置代理并预热连接
         """
-        self._log(f"Initializing Session (ID: {self.instance_id})...")
-        co, self.tunnel = init_chromium_options(
-            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,
-            headless=False,
-            window_size="1920,1080",
-            logger=self._log
-        )
+        self._log(f"Initializing API Session (ID: {self.instance_id})...")
+        self.session = requests.Session()
+        
+        # 标准浏览器请求头
+        self.session.headers.update({
+            "Accept": "application/json, text/plain, */*",
+            "Accept-Language": "en-US,en;q=0.9,pl;q=0.8",
+            "Origin": "https://secure.e-konsulat.gov.pl",
+            "Referer": "https://secure.e-konsulat.gov.pl/",
+            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
+            "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
+            "sec-ch-ua-mobile": "?0",
+            "sec-ch-ua-platform": '"Windows"',
+        })
         
+        # 配置代理
+        if self.config and self.config.proxy and self.config.proxy.ip and self.config.proxy.port:
+            p = self.config.proxy
+            if p.username and p.password:
+                proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
+            else:
+                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
+            self.session.proxies = {
+                "http": proxy_str,
+                "https": proxy_str
+            }
+            self._log(f"Configured proxy: {p.proto}://{p.ip}:{p.port}")
+            
+        placowka_id = self._extract_placowka_id()
         try:
-            self.page = ChromiumPage(co)
-            url_home = "https://secure.e-konsulat.gov.pl"
-            self._log(f"Navigating to {url_home}")
-            self.page.get(url_home)
-            self.page.wait.doc_loaded()
+            # 预热并检测机构连通性
+            probe_url = f"{self.base_api_url}/api/konfiguracja/placowki/dane-placowki/2/{placowka_id}"
+            resp = self.session.get(probe_url, timeout=15)
+            if resp.status_code == 200:
+                data = resp.json()
+                self._log(f"Connected to institution [{placowka_id}]: {data.get('nazwaPlacowki', 'OK')}")
+            else:
+                self._log(f"Probe request status {resp.status_code}: {resp.text[:100]}")
+            
             self.session_create_time = time.time()
-            self._log("Session created successfully.")
+            self.is_healthy = True
+            self._log("API Session created successfully.")
         except Exception as e:
             self._log(f"Session Create Failed: {e}")
             self.cleanup()
             raise e
 
-    def query(self, apt_type: AppointmentType) -> VSQueryResult:
-        res = VSQueryResult()
-        res.success = False
-        query_url = self.free_config.get('query_url')
-        service_type = self.free_config.get('service_type')
-        location = self.free_config.get('location')
-        self._log(f"Navigating to {query_url}")
-        self.page.get(query_url)
-        captcha_image_selector = 't:img@alt=Weryfikacja obrazkowa'
-        if not self.page.wait.ele_displayed(captcha_image_selector, timeout=30):
-            raise BizLogicError(message=f"Wait for selector={captcha_image_selector} timeout")
-        time.sleep(3)
-        img_ele = self.page.ele(captcha_image_selector)
-        img_src = img_ele.attr('src')
+    def _extract_placowka_id(self) -> str:
+        """从 free_config 或 query_url 提取 placowka_id (默认 151)"""
+        if self.free_config.get("placowka_id"):
+            return str(self.free_config["placowka_id"])
+        query_url = self.free_config.get("query_url", "")
+        m = re.search(r'/placowki/(\d+)', query_url)
+        if m:
+            return m.group(1)
+        return "151"
 
-        try:
-            captcha_code = self.captcha_breaker.break_captcha(img_src)
-            self._log(f"Captcha code={captcha_code}")
-        except CaptchaBreakerError as e:
-            self._log(f"Solve captcha error: {e}")
-            raise BizLogicError(message=f"Solve captcha failed: {e}") from e
+    def _extract_visa_kind(self) -> str:
+        """提取签证类别: schengen 或 krajowe (国家签)"""
+        query_url = self.free_config.get("query_url", "").lower()
+        service_type = self.free_config.get("service_type", "").lower()
+        if "krajow" in query_url or "krajow" in service_type or "national" in service_type:
+            return "krajowe"
+        return "schengen"
 
-        if not captcha_code:
-            raise BizLogicError(message="Solve captcha failed")
+    def _resolve_localization_id(self, placowka_id: str, visa_kind: str) -> int:
+        """解析并匹配地点 ID (如 Dublin -> 577)"""
+        if self.free_config.get("localization_id"):
+            return int(self.free_config["localization_id"])
+        
+        target_location = str(self.free_config.get("location", "Dublin")).strip()
+        target_service = str(self.free_config.get("service_type", "Wiza Schengen")).strip()
+        
+        # 尝试查询服务与地点配置 (先查英语,再查波兰语)
+        for lang_id in (2, 1):
+            url = f"{self.base_api_url}/api/konfiguracja/uslugi-wizowe/{visa_kind}/{placowka_id}/{lang_id}"
+            try:
+                resp = self.session.get(url, timeout=15)
+                if resp.status_code != 200:
+                    continue
+                data = resp.json()
+                services = data.get("uslugi", [])
+                
+                # 寻找匹配的服务与地点
+                for s in services:
+                    s_name = s.get("nazwa", "")
+                    # 如果指定了具体 service_type,做模糊匹配;若只有一种服务则直接选
+                    if len(services) > 1 and target_service.lower() not in s_name.lower():
+                        continue
+                    for loc in s.get("lokalizacje", []):
+                        loc_name = loc.get("nazwa", "")
+                        loc_id = loc.get("id")
+                        if target_location.lower() in loc_name.lower() or loc_name.lower() in target_location.lower():
+                            self._log(f"Resolved localization: '{loc_name}' -> ID {loc_id} (Service: '{s_name}')")
+                            return int(loc_id)
+                        
+                # 如果没有精确匹配上 target_location,但该服务下有且仅有一个地点,直接使用
+                for s in services:
+                    locs = s.get("lokalizacje", [])
+                    if len(locs) == 1:
+                        loc_id = locs[0].get("id")
+                        self._log(f"Defaulting to sole localization '{locs[0].get('nazwa')}' -> ID {loc_id}")
+                        return int(loc_id)
+            except Exception as e:
+                self._log(f"Error fetching service configuration (lang={lang_id}): {e}")
+                
+        # 容错:如果 target_location 本身就是数字
+        if target_location.isdigit():
+            return int(target_location)
             
-        input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
-        input_ele.clear()
-        input_ele.input(captcha_code)
+        # 默认爱尔兰都柏林为 577
+        self._log(f"Warning: Could not match location '{target_location}', falling back to default 577 (Dublin)")
+        return 577
 
-        btn_selector = 'Dalej'
-        self.page.ele(btn_selector).click(by_js=True)
-   
-        toast_ele = self.page.ele('tag:app-toast', timeout=2)
-        if toast_ele:
-            error_msg = toast_ele.text.replace('\n', ' ').strip()
-            raise BizLogicError(message=f"Captcha verify error={error_msg}")
+    def _get_verified_captcha_token(self, max_retries: int = 4) -> str:
+        """
+        生成验证码并使用 CaptchaBreaker 识别,验证通过后返回 captchaToken
+        """
+        gen_url = f"{self.base_api_url}/api/u-captcha/generuj"
+        verify_url = f"{self.base_api_url}/api/u-captcha/sprawdz"
+        
+        for attempt in range(1, max_retries + 1):
+            self._log(f"Generating captcha (attempt {attempt}/{max_retries})...")
+            gen_resp = self.session.post(gen_url, json={"imageWidth": 200, "imageHeight": 100}, timeout=15)
+            if gen_resp.status_code != 200:
+                self._log(f"Generate captcha HTTP error: {gen_resp.status_code}")
+                time.sleep(1)
+                continue
+                
+            captcha_data = gen_resp.json()
+            captcha_id = captcha_data.get("id")
+            ilosc_znakow = captcha_data.get("iloscZnakow", 4)
+            image_b64 = captcha_data.get("image")
+            
+            if not captcha_id or not image_b64:
+                self._log(f"Invalid captcha response: {captcha_data}")
+                time.sleep(1)
+                continue
+                
+            image_data_uri = f"data:image/png;base64,{image_b64}"
+            prompt = (
+                f"Please identify the {ilosc_znakow} characters (letters, digits, or symbols) "
+                f"shown in the captcha image. Return only the characters without spaces or quotes."
+            )
+            
+            try:
+                code = self.captcha_breaker.break_captcha(image_data_uri, prompt=prompt)
+                code = code.strip().replace(" ", "")
+                self._log(f"Captcha solved: '{code}' (ID: {captcha_id[:8]})")
+            except CaptchaBreakerError as e:
+                self._log(f"CaptchaBreaker recognition error: {e}")
+                time.sleep(1)
+                continue
+                
+            # 提交验证
+            verify_payload = {"kod": code, "token": captcha_id}
+            verify_resp = self.session.post(verify_url, json=verify_payload, timeout=15)
+            if verify_resp.status_code == 200:
+                try:
+                    result = verify_resp.json()
+                except Exception:
+                    result = {}
+                    
+                if result.get("ok") is True:
+                    token = result.get("token")
+                    self._log(f"✅ Captcha verified successfully! Token: {token[:12]}...")
+                    return token
+                else:
+                    self._log(f"Captcha verification rejected by server: {result}")
+            else:
+                self._log(f"Captcha verify HTTP error: {verify_resp.status_code} {verify_resp.text[:100]}")
+                
+            time.sleep(1)
+            
+        raise BizLogicError(message=f"Failed to solve and verify captcha after {max_retries} attempts")
 
-        if not self._select_mat_option('Rodzaj usługi', service_type):
-            raise BizLogicError(message='Process select box failed (service_type)')
-        if not self._select_mat_option('Lokalizacja', location):
-            raise BizLogicError(message='Process select box failed (location)')
-        if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
-            raise BizLogicError(message='Process select box failed (person count)')
+    def query(self, apt_type: AppointmentType) -> VSQueryResult:
+        res = VSQueryResult()
+        res.success = False
+        res.apt_type = apt_type
+        
+        if not self.session:
+            self.create_session()
+            
+        placowka_id = self._extract_placowka_id()
+        visa_kind = self._extract_visa_kind()
+        localization_id = self._resolve_localization_id(placowka_id, visa_kind)
+        persons = int(self.free_config.get("persons", 1))
+        
+        self._log(f"Querying slots: Placowka={placowka_id}, VisaKind={visa_kind}, LocationID={localization_id}, Persons={persons}")
+        
+        # 1. 获取已验证的 Captcha Token
+        captcha_token = self._get_verified_captcha_token()
+        
+        # 2. 查询号源
+        terminy_url = f"{self.base_api_url}/api/rezerwacja-wizyt-wizowych/terminy/{localization_id}/{persons}"
+        self._log(f"Requesting appointment slots: POST {terminy_url}")
+        
+        try:
+            resp = self.session.post(terminy_url, json={"captchaToken": captcha_token}, timeout=20)
+        except Exception as e:
+            self._log(f"Query terminy network error: {e}")
+            raise BizLogicError(message=f"Query network error: {e}") from e
+            
+        if resp.status_code == 429:
+            self.is_healthy = False
+            raise RateLimiteddError("Rate limited by e-konsulat API")
+        elif resp.status_code in (401, 419):
+            self.is_healthy = False
+            raise SessionExpiredOrInvalidError("Session expired or invalid captcha token")
+        elif resp.status_code == 403:
+            raise PermissionDeniedError(f"HTTP 403 Forbidden: {resp.text[:100]}")
+        elif resp.status_code != 200:
+            raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:200]}")
+            
+        terminy_data = resp.json()
+        tabela_dni = terminy_data.get("tabelaDni", [])
+        reservation_token = terminy_data.get("token", "")
+        self._log(f"Terminy response: tabelaDni count={len(tabela_dni)}, token={reservation_token[:12]}...")
+        
+        # 3. 解析可用日期
+        available_dates: List[str] = []
+        date_availabilities: List[DateAvailability] = []
         
-        available_dates = []
-        self._log("Wait Query Slot...")
-        for _ in range(20):
+        for item in tabela_dni:
+            raw_date = ""
+            time_slot = ""
+            if isinstance(item, str):
+                raw_date = item
+            elif isinstance(item, dict):
+                raw_date = item.get("dzienWizyty") or item.get("data") or item.get("czas") or ""
+                time_slot = item.get("godzinaWizyty") or item.get("godzina") or ""
+            
+            clean_date = raw_date.split("T")[0].strip() if raw_date else ""
+            if not clean_date:
+                continue
+                
             try:
-                no_slot_alert = self.page.ele('text:Chwilowo wszystkie udostępnione terminy', timeout=0.1)
-                if no_slot_alert:
-                    self._log("No slots available")
-                    break                    
-                listbox = self.page.ele('@role=listbox', timeout=0.1)                
-                if not listbox:
-                    termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=0.5)
-                    if termin_label:
-                        termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')                        
-                        if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
-                            try:
-                                termin_select.click()
-                            except Exception:
-                                termin_select.click(by_js=True)
-                            
-                            time.sleep(0.5)
-                            listbox = self.page.ele('@role=listbox', timeout=1)
-                if listbox:
-                    option_elements = listbox.eles('.mat-option-text')
-                    for ele in option_elements:
-                        date_str = ele.text.strip()
-                        if date_str:
-                            available_dates.append(date_str)                           
-                if available_dates:
-                    self._log(f"✅ Success extracted dates: {available_dates}")
-                    break                    
+                dt = datetime.strptime(clean_date, "%Y-%m-%d")
+                available_dates.append(clean_date)
+                times = [TimeSlot(time=time_slot, label="")] if time_slot else []
+                date_availabilities.append(DateAvailability(date=dt, times=times))
             except Exception as e:
-                self._log(f"Query loop exception: {e}")                
-            time.sleep(0.5)
-            
+                self._log(f"Warning: Failed to parse date '{clean_date}': {e}")
+                
+        # 排序
+        date_availabilities.sort(key=lambda x: x.date if x.date else datetime.min)
+        available_dates = sorted(list(set(available_dates)))
+        
         if available_dates:
-            selected_date = random.choice(available_dates)
-            self._log(f"🎲 Random select date: {selected_date}...")
-            locked = self._lock_slot(selected_date)
-            if locked:
-                session_id = self._save_browser_session()
-                wechat_message = f"🎉 [Poland] Slot locked\n📍 location: {location}\n📅 date: {selected_date}\n🔑 SessionId: {session_id}"
-                VSCloudApi.Instance().push_weixin_text(wechat_message)
+            self._log(f"🔥 Available dates found ({len(available_dates)}): {available_dates}")
             res.success = True
             res.availability_status = AvailabilityStatus.Available
-            earliest_date = available_dates[0]
-            earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
-            res.earliest_date = earliest_dt
-
-            res.availability = [
-                DateAvailability(
-                    date=datetime.strptime(d, "%Y-%m-%d"),
-                    times=[],
-                )
-                for d in available_dates
-            ]
+            res.earliest_date = date_availabilities[0].date
+            res.availability = date_availabilities
+            
+            location_name = self.free_config.get("location", "Dublin")
+            wechat_msg = (
+                f"🎉 [Poland API] Available Slot Found!\n"
+                f"📍 Location: {location_name} (ID: {localization_id})\n"
+                f"📅 Dates: {', '.join(available_dates[:5])}\n"
+                f"🔑 Reservation Token: {reservation_token}"
+            )
+            VSCloudApi.Instance().push_weixin_text(wechat_msg)
         else:
+            self._log("ℹ No available slots (tabelaDni is empty).")
             res.success = False
             res.availability_status = AvailabilityStatus.NoneAvailable
             res.availability = []
-        return res
-    
-    def _lock_slot(self, lock_date: str) -> bool:
-        slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
-        slot_ele = self.page.ele(slot_selector, timeout=1)
-        if not slot_ele:
-            termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=1)
-            if termin_label:
-                termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
-                if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
-                    try:
-                        termin_select.click()
-                    except Exception:
-                        termin_select.click(by_js=True)
-                    time.sleep(0.5)
-        slot_ele = self.page.ele(slot_selector, timeout=3)
-        if not slot_ele:
-            self._log(f"❌ Can't find date {lock_date} to click.")
-            return False
-        try:
-            slot_ele.click() 
-        except Exception:
-            slot_ele.click(by_js=True)
-        self._log(f"✅ Clicked date: {lock_date}")
-        time.sleep(1)
-        btn_selector = 'xpath://button[.//span[contains(text(), "Dalej")]]'
-        next_btn = self.page.ele(btn_selector, timeout=3)
-        if not next_btn:
-            self._log("❌ Can't find 'Dalej' button")
-            return False
-        try:
-            next_btn.click()
-        except Exception:
-            next_btn.click(by_js=True)
-        self._log("✅ Clicked Dalej, locking slot...")
-        return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
-    
-    def _select_mat_option(self, label_text: str, option_text: str) -> bool:
-        self._log(f"choose: {label_text} -> {option_text}")
-        label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
-        if not label:
-            self._log(f"Can't find label: {label_text}")
-            return False
             
-        container = label.parent('tag:app-select-control')
-        select_box = container.ele('tag:mat-select')
-        
-        if not select_box:
-            self._log("Can't find select box")
-            return False
-
-        select_box.click(by_js=True)
-        time.sleep(0.5)
-        
-        option = self.page.ele(f'tag:mat-option@@text():{option_text}', timeout=3)
-        if option:
-            option.click(by_js=True)
-            time.sleep(0.5)
-            return True
-        else:
-            self._log(f"Can't find option: {option_text}")
-            return False
+        return res
 
     def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
+        self._log("Booking via API called.")
         return res
-    
-    def _save_browser_session(self) -> str:
-        self._log("Extracting browser session environment...")
-        cookies_dict = self.page.cookies(all_domains=True, all_info=True)
-        cookies_str = cookies_dict.as_json()
-        local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
-        session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
-        proxy = getattr(getattr(self, 'config', None), 'proxy', None)
-        if proxy and getattr(proxy, 'ip', None):
-            p = proxy
-            if p.username and p.password:
-                proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-        session_data = VSCloudApi.Instance().create_http_session(
-            session_id=str(uuid.uuid4().hex),
-            cookies=cookies_str,
-            local_storage=local_storage_str,
-            session_storage=session_storage_str,
-            user_agent=self.page.user_agent,
-            page=self.page.url,
-            proxy=proxy_str
-        )
-        return session_data.get('session_id', '')
-    
-    def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
-        """在浏览器上下文中注入执行 Fetch"""
-        if not self.page:
-            raise BizLogicError("Browser not initialized")
-        
-        resp = perform_browser_fetch(
-            self.page, 
-            method=method, 
-            url=url, 
-            headers=headers, 
-            data=data, 
-            json_data=json_data, 
-            params=params
-        )
-        
-        if resp.status_code == 200:
-            return resp
-        elif resp.status_code == 403:
-            raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
-        elif resp.status_code == 429:
-            self.is_healthy = False
-            raise RateLimiteddError()
-        elif resp.status_code in (401, 419):
-            self.is_healthy = False
-            raise SessionExpiredOrInvalidError()
-        else:
-            raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
 
-    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:
+    def cleanup(self) -> None:
+        """销毁 HTTP 会话"""
+        if self.session:
             try:
-                current_url = self.page.url
+                self.session.close()
             except Exception:
                 pass
+            self.session = None
+        self._log("API Session closed and cleaned up.")
 
+    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 ""
         session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
 
@@ -372,15 +391,12 @@ class PolPlugin(IVSPlg):
             instance_id=self.instance_id,
             is_healthy=self.is_healthy,
             state=state,
-            current_url=current_url,
+            current_url=self.base_api_url,
             account=account_name,
             proxy=proxy_info,
             session_age_sec=session_age,
             last_active_at=utc_now_str(),
         )
 
-    def __del__(self):
-        """
-        析构函数:当对象被垃圾回收时自动调用
-        """
+    def __del__(self) -> None:
         self.cleanup()

+ 1 - 0
standalone.py

@@ -18,6 +18,7 @@ from vs_types import (
     RateLimiteddError,
     SessionExpiredOrInvalidError,
     PermissionDeniedError,
+    NetworkTimeoutError
 )
 from vs_plg_factory import VSPlgFactory
 from utils.safe_redis_cli import SafeRedisClient

+ 37 - 19
supersaas_keygen.py

@@ -75,6 +75,9 @@ DUBLIN_ADDRESSES = [
 ]
 
 
+ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+
+
 # ==============================================================================
 # 代理池加载工具
 # ==============================================================================
@@ -84,25 +87,40 @@ def load_proxies_from_config(pool_name: str) -> List[str]:
     try:
         with open(config_path, 'r', encoding='utf-8') as f:
             data = json.load(f)
-            raw_list = data.get(pool_name) or data.get('local', [])
-            if not raw_list:
-                raise ValueError(f"代理池 '{pool_name}' 为空且不存在 local 代理!")
-            
-            proxies = []
-            for item in raw_list:
-                if isinstance(item, str):
-                    proxies.append(item)
-                elif isinstance(item, dict):
-                    proto = item.get("proto", "http")
-                    ip = item.get("ip")
-                    port = item.get("port")
-                    user = item.get("username") or item.get("user")
-                    pwd = item.get("password") or item.get("pwd")
-                    if user and pwd:
-                        proxies.append(f"{proto}://{user}:{pwd}@{ip}:{port}")
-                    else:
-                        proxies.append(f"{proto}://{ip}:{port}")
-            return proxies
+
+        clean_name = pool_name.replace('local:', '').strip() if pool_name else ''
+        raw_list = data.get(pool_name) or data.get(clean_name)
+
+        if not raw_list and clean_name:
+            raw_list = data.get(f"local_{clean_name}")
+
+        if not raw_list and '.' in clean_name:
+            for part in clean_name.split('.'):
+                if f"local_{part}" in data:
+                    raw_list = data[f"local_{part}"]
+                    break
+
+        if not raw_list:
+            raw_list = data.get('local', [])
+
+        if not raw_list:
+            raise ValueError(f"代理池 '{pool_name}' 为空且不存在 local 代理!")
+
+        proxies = []
+        for item in raw_list:
+            if isinstance(item, str):
+                proxies.append(item)
+            elif isinstance(item, dict):
+                proto = item.get("proto", "http")
+                ip = item.get("ip")
+                port = item.get("port")
+                user = item.get("username") or item.get("user")
+                pwd = item.get("password") or item.get("pwd")
+                if user and pwd:
+                    proxies.append(f"{proto}://{user}:{pwd}@{ip}:{port}")
+                else:
+                    proxies.append(f"{proto}://{ip}:{port}")
+        return proxies
     except Exception as e:
         logger.error(f"读取代理配置文件失败: {e}")
         return []

+ 23 - 5
tls_keygen.py

@@ -26,19 +26,37 @@ from utils.keyboard import HumanKeyboard
 from utils.fingerprint_utils import FingerprintGenerator
 from utils.fake_utils import generate_random_account_detail
     
+ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+
+    
 def load_proxies(pool_name):
     """从 config/proxies.json 读取对应的代理池"""
     config_path = os.path.join(ROOT_DIR, 'config', 'proxies.json')
     try:
         with open(config_path, 'r', encoding='utf-8') as f:
             data = json.load(f)
-            proxies = data.get(pool_name, [])
-            if not proxies:
-                raise ValueError(f"代理池 '{pool_name}' 为空或不存在!")
-            return proxies
+
+        clean_name = pool_name.replace('local:', '').strip() if pool_name else ''
+        proxies = data.get(pool_name) or data.get(clean_name)
+
+        if not proxies and clean_name:
+            proxies = data.get(f"local_{clean_name}")
+
+        if not proxies and '.' in clean_name:
+            for part in clean_name.split('.'):
+                if f"local_{part}" in data:
+                    proxies = data[f"local_{part}"]
+                    break
+
+        if not proxies:
+            proxies = data.get('local', [])
+
+        if not proxies:
+            raise ValueError(f"代理池 '{pool_name}' 为空且不存在 local 代理!")
+        return proxies
     except Exception as e:
         print(f"读取代理配置文件失败: {e}")
-        exit(1)
+        sys.exit(1)
 
 class TlsRegistrator:
     def __init__(self, tls_url, proxy_config: Optional[Dict]=None, capsolver_key: Optional[str]=None, account_detail: Optional[Dict]=None):

+ 135 - 32
tools/generate_clash_multi_port.py

@@ -1,6 +1,6 @@
 """
 generate_clash_multi_port.py
-一键将机场/服务商的 Clash 订阅转为多端口代理池,并自动写入 proxies.json
+一键将机场/服务商的 Clash 订阅转为多端口代理池,并按国家分类自动写入 proxies.json
 """
 
 import os
@@ -8,19 +8,77 @@ import sys
 if hasattr(sys.stdout, 'reconfigure'):
     sys.stdout.reconfigure(encoding='utf-8', errors='replace')
     sys.stderr.reconfigure(encoding='utf-8', errors='replace')
+import re
 import yaml
 import json
 import argparse
 import requests
-import subprocess
+from collections import defaultdict
+from typing import Dict, List, Optional, Tuple
 
 PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
+# 常见中文国家/地区关键词映射表
+COUNTRY_NAME_MAP = {
+    "香港": "HK", "台湾": "TW", "澳门": "MO", "日本": "JP", "韩国": "KR", "新加坡": "SG",
+    "美国": "US", "英国": "GB", "德国": "DE", "爱尔兰": "IE", "法国": "FR", "意大利": "IT",
+    "澳大利亚": "AU", "澳洲": "AU", "加拿大": "CA", "俄罗斯": "RU", "西班牙": "ES", "波兰": "PL",
+    "比利时": "BE", "希腊": "GR", "瑞士": "CH", "荷兰": "NL", "瑞典": "SE", "挪威": "NO",
+    "土耳其": "TR", "泰国": "TH", "马来西亚": "MY", "越南": "VN", "菲律宾": "PH", "印度": "IN",
+    "巴西": "BR", "阿根廷": "AR", "墨西哥": "MX", "南非": "ZA", "埃及": "EG", "中国": "CN",
+    "新西兰": "NZ", "葡萄牙": "PT", "捷克": "CZ", "匈牙利": "HU", "奥地利": "AT", "丹麦": "DK",
+    "芬兰": "FI", "冰岛": "IS", "乌克兰": "UA", "罗马尼亚": "RO", "立陶宛": "LT", "拉脱维亚": "LV",
+    "爱沙尼亚": "EE", "克罗地亚": "HR", "保加利亚": "BG", "斯洛伐克": "SK", "斯洛文尼亚": "SI",
+    "卢森堡": "LU", "塞尔维亚": "RS", "塞浦路斯": "CY", "马耳他": "MT", "阿联酋": "AE", "迪拜": "AE"
+}
+
+
+def flag_to_code(flag_str: str) -> str:
+    """将两个字符构成的国旗 emoji 转换为 ISO 3166-1 alpha-2 两位大写代码"""
+    if len(flag_str) == 2:
+        c1, c2 = flag_str[0], flag_str[1]
+        if 0x1F1E6 <= ord(c1) <= 0x1F1FF and 0x1F1E6 <= ord(c2) <= 0x1F1FF:
+            return chr(ord(c1) - 0x1F1E6 + ord('A')) + chr(ord(c2) - 0x1F1E6 + ord('A'))
+    return ""
+
+
+def detect_country(node_name: str) -> str:
+    """
+    智能识别节点归属的国家/地区代码 (大写2位,如 DE, IE, GB, US, HK...)
+    """
+    name = node_name.strip()
+    
+    # 1. 优先从末尾倍率/标签提取,例如: '丨1x HK', '丨3x US', '-HK-', '[US]'
+    m_code = re.search(r'丨\s*\d+(?:\.\d+)?x\s*([A-Za-z]{2})\b', name)
+    if m_code:
+        code = m_code.group(1).upper()
+        return "GB" if code == "UK" else code
+        
+    m_bracket = re.search(r'[\[\(\-\_]([A-Za-z]{2})[\]\)\-\_]', name)
+    if m_bracket:
+        code = m_bracket.group(1).upper()
+        if code in ("HK", "TW", "MO", "JP", "KR", "SG", "US", "UK", "GB", "DE", "IE", "FR", "IT", "CA", "AU"):
+            return "GB" if code == "UK" else code
+
+    # 2. 尝试从国旗 Emoji 解析
+    flags = re.findall(r'[\U0001F1E6-\U0001F1FF]{2}', name)
+    if flags:
+        code = flag_to_code(flags[0])
+        if code:
+            return "GB" if code == "UK" else code
+
+    # 3. 中文/关键词匹配
+    for keyword, code in COUNTRY_NAME_MAP.items():
+        if keyword in name:
+            return code
+
+    return "OTHER"
+
 
 def fetch_config(source: str) -> dict:
     """从网络链接或本地文件读取 yaml 配置"""
     if source.startswith("http://") or source.startswith("https://"):
-        print(f"[*] 正在下载订阅配置: {source[:40]}...")
+        print(f"[*] 正在下载订阅配置: {source[:60]}...")
         headers = {
             "User-Agent": "ClashforWindows/0.20.39"
         }
@@ -37,14 +95,15 @@ def fetch_config(source: str) -> dict:
 
 
 def main():
-    parser = argparse.ArgumentParser(description="Clash 订阅转本地多端口代理池工具")
+    parser = argparse.ArgumentParser(description="Clash 订阅转本地多端口代理池工具 (支持按国家智能分池)")
     parser.add_argument("--sub", type=str, required=True, help="服务商提供的订阅链接 (URL) 或本地 yaml 文件路径")
     parser.add_argument("--start-port", type=int, default=10001, help="起始监听端口 (默认: 10001)")
-    parser.add_argument("--count", type=int, default=0, help="最多导出的节点数量 (默认: 0 表示全部节点)")
-    parser.add_argument("--filter-kw", type=str, default="", help="节点关键词过滤 (如: '香港', 'HK', '专线',留空表示全选)")
-    parser.add_argument("--pool-name", type=str, default="local_multi_pool", help="写入 proxies.json 的池子名称")
-    parser.add_argument("--output-yaml", type=str, default="config/local_multi_port.yaml", help="生成的多端口 clash 配置文件")
-    parser.add_argument("--run", action="store_true", help="生成后是否立即启动 mihomo/clash 进程")
+    parser.add_argument("--count", type=int, default=0, help="最多导出的节点总数量 (默认: 0 表示全部节点)")
+    parser.add_argument("--filter-kw", type=str, default="", help="节点关键词过滤 (如: '专线', '家宽',留空表示不限制)")
+    parser.add_argument("--countries", type=str, default="", help="仅导出的国家代码列表,逗号分隔 (例如: 'DE,IE,GB,US',留空表示全量导出)")
+    parser.add_argument("--pool-prefix", type=str, default="local", help="国家池子的前缀 (默认: 'local' -> 生成 'local_de', 'local_ie' 等)")
+    parser.add_argument("--all-pool-name", type=str, default="local_multi_pool", help="全量汇总池的名称 (默认: 'local_multi_pool',设为 'none' 则不生成汇总池)")
+    parser.add_argument("--output-yaml", type=str, default="config/local_multi_port.yaml", help="生成的多端口 clash 配置文件路径")
     
     args = parser.parse_args()
 
@@ -57,45 +116,66 @@ def main():
 
     print(f"[*] 原始配置中共解析出 {len(proxies)} 个节点。")
 
-    # 2. 节点过滤
+    # 指定的国家过滤列表
+    target_countries = set()
+    if args.countries:
+        for c in args.countries.split(","):
+            c = c.strip().upper()
+            if c:
+                target_countries.add(c)
+
+    # 2. 节点过滤与国家识别
     selected_proxies = []
     for p in proxies:
         name = p.get("name", "")
-        # 排除不可用的信息节点
+        # 排除不可用的系统提示节点
         if any(bad in name for bad in ["剩余", "到期", "官网", "Traffic", "Expire", "重置"]):
             continue
-        if args.filter_kw:
-            if args.filter_kw.lower() in name.lower():
-                selected_proxies.append(p)
-        else:
-            selected_proxies.append(p)
+        if args.filter_kw and args.filter_kw.lower() not in name.lower():
+            continue
+            
+        # 国家过滤
+        c_code = detect_country(name)
+        if target_countries and c_code not in target_countries:
+            continue
+
+        p["_country_code"] = c_code
+        selected_proxies.append(p)
 
     if args.count > 0:
         selected_proxies = selected_proxies[:args.count]
+
     if not selected_proxies:
         print("❌ 过滤后没有符合条件的节点!")
         return
 
     print(f"[*] 已选取 {len(selected_proxies)} 个优质节点用于多端口映射。")
 
-    # 3. 构造极简的多端口配置
+    # 3. 构造多端口配置与国家分池数据结构
     listeners = []
-    proxies_json_list = []
+    all_proxies_list = []
+    country_pools = defaultdict(list)
     
     for idx, p in enumerate(selected_proxies):
         port = args.start_port + idx
+        c_code = p.get("_country_code", "OTHER").lower()
+        
+        # Clash listener
         listeners.append({
             "name": f"mixed_{port}",
             "type": "mixed",
             "port": port,
             "proxy": p["name"]
         })
-        proxies_json_list.append({
+        
+        proxy_item = {
             "proto": "http",
             "ip": "127.0.0.1",
             "port": port,
             "name": p["name"]
-        })
+        }
+        all_proxies_list.append(proxy_item)
+        country_pools[c_code].append(proxy_item)
 
     clean_config = {
         "mixed-port": args.start_port - 1,
@@ -106,7 +186,7 @@ def main():
         "dns": {
             "enable": False
         },
-        "proxies": selected_proxies,
+        "proxies": [{k: v for k, v in p.items() if not k.startswith("_")} for p in selected_proxies],
         "listeners": listeners,
         "rules": [
             "MATCH,DIRECT"
@@ -118,10 +198,10 @@ def main():
     os.makedirs(os.path.dirname(out_yaml_path), exist_ok=True)
     with open(out_yaml_path, "w", encoding="utf-8") as f:
         yaml.dump(clean_config, f, allow_unicode=True, sort_keys=False)
-    print(f"✅ 已生成多端口配置文件: {out_yaml_path}")
+    print(f"\n✅ 已生成多端口配置文件: {out_yaml_path}")
     print(f"   监听端口范围: {args.start_port} ~ {args.start_port + len(listeners) - 1}")
 
-    # 5. 更新 proxies.json
+    # 5. 更新写入 config/proxies.json
     proxies_json_path = os.path.join(PROJECT_ROOT, "config", "proxies.json")
     all_proxies_data = {}
     if os.path.exists(proxies_json_path):
@@ -131,17 +211,40 @@ def main():
         except Exception:
             all_proxies_data = {}
 
-    all_proxies_data[args.pool_name] = proxies_json_list
+    # (1) 写入全量汇总池
+    if args.all_pool_name and args.all_pool_name.lower() != "none":
+        all_proxies_data[args.all_pool_name] = all_proxies_list
+
+    # (2) 写入按国家划分的独立池子
+    generated_country_pools = []
+    for c_code, items in sorted(country_pools.items()):
+        pool_key = f"{args.pool_prefix}_{c_code}" if args.pool_prefix else c_code
+        all_proxies_data[pool_key] = items
+        ports = [item["port"] for item in items]
+        port_range_str = f"{min(ports)}" if len(ports) == 1 else f"{min(ports)}~{max(ports)}"
+        generated_country_pools.append((pool_key, c_code.upper(), len(items), port_range_str))
+
     with open(proxies_json_path, "w", encoding="utf-8") as f:
         json.dump(all_proxies_data, f, indent=4, ensure_ascii=False)
-    print(f"✅ 已自动将 {len(proxies_json_list)} 个代理写入 config/proxies.json -> '{args.pool_name}'")
-
-    # 6. 运行指引
-    print("\n" + "="*60)
-    print("🎉 配置已就绪!你可以通过以下方式使用:")
-    print(f"1. 启动命令: mihomo -f {out_yaml_path}")
-    print(f"2. 在任务配置中使用代理池: \"proxy-pool\": \"{args.pool_name}\"")
-    print("="*60)
+
+    print(f"\n✅ 已成功写入 config/proxies.json!按国家分类代理池明细如下:")
+    print("-" * 65)
+    print(f"{'池子名称 (Key)':<22} | {'国家':<6} | {'节点数':<8} | {'端口范围'}")
+    print("-" * 65)
+    for p_name, c_upper, cnt, p_range in generated_country_pools:
+        print(f"local:{p_name:<16} | {c_upper:<6} | {cnt:<8} | {p_range}")
+    print("-" * 65)
+    if args.all_pool_name and args.all_pool_name.lower() != "none":
+        print(f"local:{args.all_pool_name:<16} | {'ALL':<6} | {len(all_proxies_list):<8} | {args.start_port}~{args.start_port + len(listeners) - 1} (全量汇总池)")
+    print("-" * 65)
+
+    # 6. 使用示例
+    print("\n💡 在任务配置中引用方式示例:")
+    print(f"   德国任务 (DE):   \"proxy_pool\": [\"local:local_de\"]")
+    print(f"   爱尔兰任务 (IE): \"proxy_pool\": [\"local:local_ie\"]")
+    print(f"   英国任务 (GB):   \"proxy_pool\": [\"local:local_gb\"]")
+    print(f"   美国任务 (US):   \"proxy_pool\": [\"local:local_us\"]")
+    print(f"   全量轮询 (ALL):  \"proxy_pool\": [\"local:{args.all_pool_name}\"]")
 
 
 if __name__ == "__main__":

+ 27 - 8
vfs_keygen.py

@@ -124,22 +124,41 @@ class BrowserResponse:
         return self._json
 
 
-# ==========================================
-# API 交互与代理工具
-# ==========================================
+ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+
+
 def load_proxies(pool_name):
     """从 config/proxies.json 读取对应的代理池"""
     config_path = os.path.join(ROOT_DIR, 'config', 'proxies.json')
     try:
         with open(config_path, 'r', encoding='utf-8') as f:
             data = json.load(f)
-            proxies = data.get(pool_name) or data.get('local', [])
-            if not proxies:
-                raise ValueError(f"代理池 '{pool_name}' 为空且不存在 local 代理!")
-            return proxies
+
+        # 1. 尝试直接获取 (或去掉 local: 前缀后获取)
+        clean_name = pool_name.replace('local:', '').strip() if pool_name else ''
+        proxies = data.get(pool_name) or data.get(clean_name)
+
+        # 2. 若未匹配,尝试加上 local_ 前缀 (如 ie -> local_ie)
+        if not proxies and clean_name:
+            proxies = data.get(f"local_{clean_name}")
+
+        # 3. 若仍未匹配,尝试从点分命名中解析国家代码 (如 ie.nl.sentinel -> local_ie 或 local_nl)
+        if not proxies and '.' in clean_name:
+            for part in clean_name.split('.'):
+                if f"local_{part}" in data:
+                    proxies = data[f"local_{part}"]
+                    break
+
+        # 4. 兜底回退到 local 代理池
+        if not proxies:
+            proxies = data.get('local', [])
+
+        if not proxies:
+            raise ValueError(f"代理池 '{pool_name}' 为空且不存在 local 代理!")
+        return proxies
     except Exception as e:
         logger.error(f"读取代理配置文件失败: {e}")
-        exit(1)
+        sys.exit(1)
 
 
 def upload_account_to_server(account, api_url, api_token):