import time import json import random import re import os import uuid import base64 from datetime import datetime from typing import List, Dict, Optional, Any, Callable from DrissionPage import ChromiumPage from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError from vs_plg import IVSPlg from vs_types import ( VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, 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 ) class PolPlugin(IVSPlg): """ Poland (e-konsulat) 签证预约插件 (Browser + Tunnel Mode) """ name = "pol_plugin" version = "1.0.0" description = "波兰e-konsulat签证预约插件 (支持验证码识别与隧道代理)" 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.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") if not os.path.exists(self.root_workspace): os.makedirs(self.root_workspace) self.captcha_breaker = CaptchaBreaker() self.tunnel = None # 代理隧道 self.is_healthy = True self.session_create_time: float = 0 def set_log(self, logger: Callable[[str], None]) -> None: self.logger = logger def _log(self, message): 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): self.config = config self.free_config = config.free_config or {} def keep_alive(self): 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: return False if self.config.session_max_life > 0: if time.time() - self.session_create_time > self.config.session_max_life: self._log("Session expired.") return False return True def create_session(self): """ 创建会话:启动浏览器 -> 配置代理隧道 -> 导航至首页 """ 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 ) 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() self.session_create_time = time.time() self._log("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') 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 if not captcha_code: raise BizLogicError(message="Solve captcha failed") input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka') input_ele.clear() input_ele.input(captcha_code) 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}") 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)') available_dates = [] self._log("Wait Query Slot...") for _ in range(20): 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 except Exception as e: self._log(f"Query loop exception: {e}") time.sleep(0.5) 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) 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 ] else: 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 def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult: res = VSBookResult() 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: try: current_url = self.page.url except Exception: pass 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=current_url, account=account_name, proxy=proxy_info, session_age_sec=session_age, last_active_at=utc_now_str(), ) def __del__(self): """ 析构函数:当对象被垃圾回收时自动调用 """ self.cleanup()