| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403 |
- import time
- import json
- import random
- import re
- import os
- import uuid
- import base64
- from datetime import datetime, timezone
- from typing import List, Dict, Optional, Any, Callable
- import requests
- from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
- from plugin import IPlugin
- from core_types import (
- PluginConfig,
- AppointmentType,
- QueryResult,
- BookResult,
- AvailabilityStatus,
- DateAvailability,
- TimeSlot,
- NotFoundError,
- PermissionDeniedError,
- RateLimiteddError,
- SessionExpiredOrInvalidError,
- BizLogicError,
- PluginStatus,
- utc_now_str
- )
- from toolkit.cloud_api import CloudApi
- from utils.plugin_utils import filter_dates_in_range
- class PolPlugin(IPlugin):
- booking_supported = False
- """
- Poland (e-konsulat) 签证预约插件 (Pure HTTP REST API Mode)
- 基于 official e-konsulat REST API (https://api.e-konsulat.gov.pl) 与大模型视觉验证码识别
- """
- name = "pol_plugin"
- version = "2.0.0"
- description = "波兰e-konsulat签证预约插件 (纯API与大模型验证码识别)"
- def __init__(self, group_id: str):
- self.group_id = group_id
- self.config: Optional[PluginConfig] = None
- self.free_config: Dict[str, Any] = {}
- self.logger: Optional[Callable[[str], None]] = None
-
- # 资源与状态标识
- self.instance_id = uuid.uuid4().hex[:8]
- self.is_healthy = True
- self.session_create_time: float = 0
-
- # HTTP 会话
- self.session: Optional[requests.Session] = None
- self.base_api_url = "https://api.e-konsulat.gov.pl"
-
- # 验证码识别引擎
- self.captcha_breaker = CaptchaBreaker()
-
- # 缓存的服务和地点映射
- self._cached_service_locations: Dict[str, Any] = {}
- def set_log(self, logger: Callable[[str], None]) -> None:
- self.logger = logger
-
- 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: PluginConfig) -> 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) -> None:
- pass
- def health_check(self) -> bool:
- if not self.is_healthy:
- return False
- if not self.session:
- return False
- 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 by session_max_life.")
- return False
- return True
- def create_session(self) -> None:
- """
- 初始化 HTTP 会话、配置代理并预热连接
- """
- 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:
- # 预热并检测机构连通性
- 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.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 _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"
- 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"
- 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)
-
- # 默认爱尔兰都柏林为 577
- self._log(f"Warning: Could not match location '{target_location}', falling back to default 577 (Dublin)")
- return 577
- 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")
- def query(self, apt_type: AppointmentType) -> QueryResult:
- res = QueryResult()
- 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] = []
-
- 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:
- 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"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:
- self._log(f"🔥 Available dates found ({len(available_dates)}): {available_dates}")
- res.success = True
- res.availability_status = AvailabilityStatus.Available
- 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}"
- )
- CloudApi.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 book(self, slot_info: QueryResult, user_inputs: Dict = None) -> BookResult:
- res = BookResult()
- self._log("Booking via API called.")
- return res
- def cleanup(self) -> None:
- """销毁 HTTP 会话"""
- if self.session:
- try:
- 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"
- return PluginStatus(
- instance_id=self.instance_id,
- is_healthy=self.is_healthy,
- state=state,
- 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) -> None:
- self.cleanup()
|