|
|
@@ -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()
|