pol_plugin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. import base64
  8. from datetime import datetime, timezone
  9. from typing import List, Dict, Optional, Any, Callable
  10. import requests
  11. from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
  12. from plugin import IPlugin
  13. from core_types import (
  14. PluginConfig,
  15. AppointmentType,
  16. QueryResult,
  17. BookResult,
  18. AvailabilityStatus,
  19. DateAvailability,
  20. TimeSlot,
  21. NotFoundError,
  22. PermissionDeniedError,
  23. RateLimiteddError,
  24. SessionExpiredOrInvalidError,
  25. BizLogicError,
  26. PluginStatus,
  27. utc_now_str
  28. )
  29. from toolkit.cloud_api import CloudApi
  30. from utils.plugin_utils import filter_dates_in_range
  31. class PolPlugin(IPlugin):
  32. """
  33. Poland (e-konsulat) 签证预约插件 (Pure HTTP REST API Mode)
  34. 基于 official e-konsulat REST API (https://api.e-konsulat.gov.pl) 与大模型视觉验证码识别
  35. """
  36. name = "pol_plugin"
  37. version = "2.0.0"
  38. description = "波兰e-konsulat签证预约插件 (纯API与大模型验证码识别)"
  39. def __init__(self, group_id: str):
  40. self.group_id = group_id
  41. self.config: Optional[PluginConfig] = None
  42. self.free_config: Dict[str, Any] = {}
  43. self.logger: Optional[Callable[[str], None]] = None
  44. # 资源与状态标识
  45. self.instance_id = uuid.uuid4().hex[:8]
  46. self.is_healthy = True
  47. self.session_create_time: float = 0
  48. # HTTP 会话
  49. self.session: Optional[requests.Session] = None
  50. self.base_api_url = "https://api.e-konsulat.gov.pl"
  51. # 验证码识别引擎
  52. self.captcha_breaker = CaptchaBreaker()
  53. # 缓存的服务和地点映射
  54. self._cached_service_locations: Dict[str, Any] = {}
  55. def set_log(self, logger: Callable[[str], None]) -> None:
  56. self.logger = logger
  57. def _log(self, message: str) -> None:
  58. if self.logger:
  59. self.logger(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  60. else:
  61. print(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  62. def set_config(self, config: PluginConfig) -> None:
  63. self.config = config
  64. self.free_config = config.free_config or {}
  65. if self.free_config.get("base_api_url"):
  66. self.base_api_url = self.free_config["base_api_url"].rstrip('/')
  67. def keep_alive(self) -> None:
  68. pass
  69. def health_check(self) -> bool:
  70. if not self.is_healthy:
  71. return False
  72. if not self.session:
  73. return False
  74. if self.config and self.config.session_max_life > 0:
  75. if time.time() - self.session_create_time > self.config.session_max_life:
  76. self._log("Session expired by session_max_life.")
  77. return False
  78. return True
  79. def create_session(self) -> None:
  80. """
  81. 初始化 HTTP 会话、配置代理并预热连接
  82. """
  83. self._log(f"Initializing API Session (ID: {self.instance_id})...")
  84. self.session = requests.Session()
  85. # 标准浏览器请求头
  86. self.session.headers.update({
  87. "Accept": "application/json, text/plain, */*",
  88. "Accept-Language": "en-US,en;q=0.9,pl;q=0.8",
  89. "Origin": "https://secure.e-konsulat.gov.pl",
  90. "Referer": "https://secure.e-konsulat.gov.pl/",
  91. "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",
  92. "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
  93. "sec-ch-ua-mobile": "?0",
  94. "sec-ch-ua-platform": '"Windows"',
  95. })
  96. # 配置代理
  97. if self.config and self.config.proxy and self.config.proxy.ip and self.config.proxy.port:
  98. p = self.config.proxy
  99. if p.username and p.password:
  100. proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
  101. else:
  102. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  103. self.session.proxies = {
  104. "http": proxy_str,
  105. "https": proxy_str
  106. }
  107. self._log(f"Configured proxy: {p.proto}://{p.ip}:{p.port}")
  108. placowka_id = self._extract_placowka_id()
  109. try:
  110. # 预热并检测机构连通性
  111. probe_url = f"{self.base_api_url}/api/konfiguracja/placowki/dane-placowki/2/{placowka_id}"
  112. resp = self.session.get(probe_url, timeout=15)
  113. if resp.status_code == 200:
  114. data = resp.json()
  115. self._log(f"Connected to institution [{placowka_id}]: {data.get('nazwaPlacowki', 'OK')}")
  116. else:
  117. self._log(f"Probe request status {resp.status_code}: {resp.text[:100]}")
  118. self.session_create_time = time.time()
  119. self.is_healthy = True
  120. self._log("API Session created successfully.")
  121. except Exception as e:
  122. self._log(f"Session Create Failed: {e}")
  123. self.cleanup()
  124. raise e
  125. def _extract_placowka_id(self) -> str:
  126. """从 free_config 或 query_url 提取 placowka_id (默认 151)"""
  127. if self.free_config.get("placowka_id"):
  128. return str(self.free_config["placowka_id"])
  129. query_url = self.free_config.get("query_url", "")
  130. m = re.search(r'/placowki/(\d+)', query_url)
  131. if m:
  132. return m.group(1)
  133. return "151"
  134. def _extract_visa_kind(self) -> str:
  135. """提取签证类别: schengen 或 krajowe (国家签)"""
  136. query_url = self.free_config.get("query_url", "").lower()
  137. service_type = self.free_config.get("service_type", "").lower()
  138. if "krajow" in query_url or "krajow" in service_type or "national" in service_type:
  139. return "krajowe"
  140. return "schengen"
  141. def _resolve_localization_id(self, placowka_id: str, visa_kind: str) -> int:
  142. """解析并匹配地点 ID (如 Dublin -> 577)"""
  143. if self.free_config.get("localization_id"):
  144. return int(self.free_config["localization_id"])
  145. target_location = str(self.free_config.get("location", "Dublin")).strip()
  146. target_service = str(self.free_config.get("service_type", "Wiza Schengen")).strip()
  147. # 尝试查询服务与地点配置 (先查英语,再查波兰语)
  148. for lang_id in (2, 1):
  149. url = f"{self.base_api_url}/api/konfiguracja/uslugi-wizowe/{visa_kind}/{placowka_id}/{lang_id}"
  150. try:
  151. resp = self.session.get(url, timeout=15)
  152. if resp.status_code != 200:
  153. continue
  154. data = resp.json()
  155. services = data.get("uslugi", [])
  156. # 寻找匹配的服务与地点
  157. for s in services:
  158. s_name = s.get("nazwa", "")
  159. # 如果指定了具体 service_type,做模糊匹配;若只有一种服务则直接选
  160. if len(services) > 1 and target_service.lower() not in s_name.lower():
  161. continue
  162. for loc in s.get("lokalizacje", []):
  163. loc_name = loc.get("nazwa", "")
  164. loc_id = loc.get("id")
  165. if target_location.lower() in loc_name.lower() or loc_name.lower() in target_location.lower():
  166. self._log(f"Resolved localization: '{loc_name}' -> ID {loc_id} (Service: '{s_name}')")
  167. return int(loc_id)
  168. # 如果没有精确匹配上 target_location,但该服务下有且仅有一个地点,直接使用
  169. for s in services:
  170. locs = s.get("lokalizacje", [])
  171. if len(locs) == 1:
  172. loc_id = locs[0].get("id")
  173. self._log(f"Defaulting to sole localization '{locs[0].get('nazwa')}' -> ID {loc_id}")
  174. return int(loc_id)
  175. except Exception as e:
  176. self._log(f"Error fetching service configuration (lang={lang_id}): {e}")
  177. # 容错:如果 target_location 本身就是数字
  178. if target_location.isdigit():
  179. return int(target_location)
  180. # 默认爱尔兰都柏林为 577
  181. self._log(f"Warning: Could not match location '{target_location}', falling back to default 577 (Dublin)")
  182. return 577
  183. def _get_verified_captcha_token(self, max_retries: int = 4) -> str:
  184. """
  185. 生成验证码并使用 CaptchaBreaker 识别,验证通过后返回 captchaToken
  186. """
  187. gen_url = f"{self.base_api_url}/api/u-captcha/generuj"
  188. verify_url = f"{self.base_api_url}/api/u-captcha/sprawdz"
  189. for attempt in range(1, max_retries + 1):
  190. self._log(f"Generating captcha (attempt {attempt}/{max_retries})...")
  191. gen_resp = self.session.post(gen_url, json={"imageWidth": 200, "imageHeight": 100}, timeout=15)
  192. if gen_resp.status_code != 200:
  193. self._log(f"Generate captcha HTTP error: {gen_resp.status_code}")
  194. time.sleep(1)
  195. continue
  196. captcha_data = gen_resp.json()
  197. captcha_id = captcha_data.get("id")
  198. ilosc_znakow = captcha_data.get("iloscZnakow", 4)
  199. image_b64 = captcha_data.get("image")
  200. if not captcha_id or not image_b64:
  201. self._log(f"Invalid captcha response: {captcha_data}")
  202. time.sleep(1)
  203. continue
  204. image_data_uri = f"data:image/png;base64,{image_b64}"
  205. prompt = (
  206. f"Please identify the {ilosc_znakow} characters (letters, digits, or symbols) "
  207. f"shown in the captcha image. Return only the characters without spaces or quotes."
  208. )
  209. try:
  210. code = self.captcha_breaker.break_captcha(image_data_uri, prompt=prompt)
  211. code = code.strip().replace(" ", "")
  212. self._log(f"Captcha solved: '{code}' (ID: {captcha_id[:8]})")
  213. except CaptchaBreakerError as e:
  214. self._log(f"CaptchaBreaker recognition error: {e}")
  215. time.sleep(1)
  216. continue
  217. # 提交验证
  218. verify_payload = {"kod": code, "token": captcha_id}
  219. verify_resp = self.session.post(verify_url, json=verify_payload, timeout=15)
  220. if verify_resp.status_code == 200:
  221. try:
  222. result = verify_resp.json()
  223. except Exception:
  224. result = {}
  225. if result.get("ok") is True:
  226. token = result.get("token")
  227. self._log(f"✅ Captcha verified successfully! Token: {token[:12]}...")
  228. return token
  229. else:
  230. self._log(f"Captcha verification rejected by server: {result}")
  231. else:
  232. self._log(f"Captcha verify HTTP error: {verify_resp.status_code} {verify_resp.text[:100]}")
  233. time.sleep(1)
  234. raise BizLogicError(message=f"Failed to solve and verify captcha after {max_retries} attempts")
  235. def query(self, apt_type: AppointmentType) -> QueryResult:
  236. res = QueryResult()
  237. res.success = False
  238. res.apt_type = apt_type
  239. if not self.session:
  240. self.create_session()
  241. placowka_id = self._extract_placowka_id()
  242. visa_kind = self._extract_visa_kind()
  243. localization_id = self._resolve_localization_id(placowka_id, visa_kind)
  244. persons = int(self.free_config.get("persons", 1))
  245. self._log(f"Querying slots: Placowka={placowka_id}, VisaKind={visa_kind}, LocationID={localization_id}, Persons={persons}")
  246. # 1. 获取已验证的 Captcha Token
  247. captcha_token = self._get_verified_captcha_token()
  248. # 2. 查询号源
  249. terminy_url = f"{self.base_api_url}/api/rezerwacja-wizyt-wizowych/terminy/{localization_id}/{persons}"
  250. self._log(f"Requesting appointment slots: POST {terminy_url}")
  251. try:
  252. resp = self.session.post(terminy_url, json={"captchaToken": captcha_token}, timeout=20)
  253. except Exception as e:
  254. self._log(f"Query terminy network error: {e}")
  255. raise BizLogicError(message=f"Query network error: {e}") from e
  256. if resp.status_code == 429:
  257. self.is_healthy = False
  258. raise RateLimiteddError("Rate limited by e-konsulat API")
  259. elif resp.status_code in (401, 419):
  260. self.is_healthy = False
  261. raise SessionExpiredOrInvalidError("Session expired or invalid captcha token")
  262. elif resp.status_code == 403:
  263. raise PermissionDeniedError(f"HTTP 403 Forbidden: {resp.text[:100]}")
  264. elif resp.status_code != 200:
  265. raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:200]}")
  266. terminy_data = resp.json()
  267. tabela_dni = terminy_data.get("tabelaDni", [])
  268. reservation_token = terminy_data.get("token", "")
  269. self._log(f"Terminy response: tabelaDni count={len(tabela_dni)}, token={reservation_token[:12]}...")
  270. # 3. 解析可用日期
  271. available_dates: List[str] = []
  272. date_availabilities: List[DateAvailability] = []
  273. for item in tabela_dni:
  274. raw_date = ""
  275. time_slot = ""
  276. if isinstance(item, str):
  277. raw_date = item
  278. elif isinstance(item, dict):
  279. raw_date = item.get("dzienWizyty") or item.get("data") or item.get("czas") or ""
  280. time_slot = item.get("godzinaWizyty") or item.get("godzina") or ""
  281. clean_date = raw_date.split("T")[0].strip() if raw_date else ""
  282. if not clean_date:
  283. continue
  284. try:
  285. dt = datetime.strptime(clean_date, "%Y-%m-%d")
  286. available_dates.append(clean_date)
  287. times = [TimeSlot(time=time_slot, label="")] if time_slot else []
  288. date_availabilities.append(DateAvailability(date=dt, times=times))
  289. except Exception as e:
  290. self._log(f"Warning: Failed to parse date '{clean_date}': {e}")
  291. # 排序
  292. date_availabilities.sort(key=lambda x: x.date if x.date else datetime.min)
  293. available_dates = sorted(list(set(available_dates)))
  294. if available_dates:
  295. self._log(f"🔥 Available dates found ({len(available_dates)}): {available_dates}")
  296. res.success = True
  297. res.availability_status = AvailabilityStatus.Available
  298. res.earliest_date = date_availabilities[0].date
  299. res.availability = date_availabilities
  300. location_name = self.free_config.get("location", "Dublin")
  301. wechat_msg = (
  302. f"🎉 [Poland API] Available Slot Found!\n"
  303. f"📍 Location: {location_name} (ID: {localization_id})\n"
  304. f"📅 Dates: {', '.join(available_dates[:5])}\n"
  305. f"🔑 Reservation Token: {reservation_token}"
  306. )
  307. CloudApi.Instance().push_weixin_text(wechat_msg)
  308. else:
  309. self._log("ℹ No available slots (tabelaDni is empty).")
  310. res.success = False
  311. res.availability_status = AvailabilityStatus.NoneAvailable
  312. res.availability = []
  313. return res
  314. def book(self, slot_info: QueryResult, user_inputs: Dict = None) -> BookResult:
  315. res = BookResult()
  316. self._log("Booking via API called.")
  317. return res
  318. def cleanup(self) -> None:
  319. """销毁 HTTP 会话"""
  320. if self.session:
  321. try:
  322. self.session.close()
  323. except Exception:
  324. pass
  325. self.session = None
  326. self._log("API Session closed and cleaned up.")
  327. def get_plugin_status(self) -> PluginStatus:
  328. account_name = self.config.account.username if self.config and self.config.account else ""
  329. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  330. session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
  331. state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
  332. return PluginStatus(
  333. instance_id=self.instance_id,
  334. is_healthy=self.is_healthy,
  335. state=state,
  336. current_url=self.base_api_url,
  337. account=account_name,
  338. proxy=proxy_info,
  339. session_age_sec=session_age,
  340. last_active_at=utc_now_str(),
  341. )
  342. def __del__(self) -> None:
  343. self.cleanup()