import time import json import random import re import os import uuid from datetime import datetime from typing import List, Dict, Optional, Any, Callable from DrissionPage import ChromiumPage from plugin import IPlugin from core_types import ( PluginConfig, AppointmentType, QueryResult, BookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str ) from utils.plugin_utils import ( BrowserResponse, init_chromium_options, perform_browser_fetch, filter_dates_in_range, solve_capsolver_hcaptcha, cleanup_browser_workspace ) class BelPlugin(IPlugin): booking_supported = False """ Belgium (https://visaonweb.diplomatie.be/en) 签证预约插件 (Browser + Tunnel Mode) """ name = "bel_plugin" version = "1.0.0" description = "比利时签证预约插件 (Visa On Web / 浏览器与隧道模式)" def __init__(self, group_id: str): self.group_id = group_id self.config: Optional[PluginConfig] = 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.applicants = [] 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'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}') else: print(f'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}') def set_config(self, config: PluginConfig): 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 or 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 ) co.set_argument('--ignore-certificate-errors') try: self.page = ChromiumPage(co) url_home = "https://visaonweb.diplomatie.be/Account/Login?ReturnUrl=%2Fen" self._log(f"Navigating to {url_home}") self.page.get(url_home) self.page.wait.doc_loaded() self.page.wait.ele_displayed('tag:button@@type=submit', timeout=10) self.page.ele('tag:input@@name=UserName').input(self.config.account.username) self.page.ele('tag:input@@name=Password').input(self.config.account.password) self.page.ele('tag:button@@type=submit').click() self.page.listen.start('/VisaApplication/MyList') self.page.get('https://visaonweb.diplomatie.be/en/VisaApplication/IndexByUserId') packet = self.page.listen.wait(timeout=10) if not packet: raise BizLogicError(message='Get userList failed') self.page.listen.stop() resp_body = packet.response.body for dat in resp_body.get('data', []): if dat.get('St') == 'Submitted': applicant = { "id": dat.get('Id'), "first_name": dat.get('FName'), "last_name": dat.get('LName'), "vow_id": dat.get('VOWId'), "os_id": dat.get('OSId'), "sub_group_id": dat.get('SubGroupId'), "vac": dat.get('Vac'), } self.applicants.append(applicant) 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) -> QueryResult: res = QueryResult() res.success = False if not self.applicants: self._log("No submitted applicants available to query appointment.") res.availability_status = AvailabilityStatus.NoneAvailable return res applicant = random.choice(self.applicants) applicant_id = applicant.get('id') url = 'https://visaonweb.diplomatie.be/Common/GetEAppointmentUrl' params = { 'id': applicant_id } headers = { "cache-control": "max-age=0", "if-modified-since": "0", "x-requested-with": "XMLHttpRequest", } resp = self._perform_request('GET', url, headers=headers, params=params) appointment_url = resp.json().get('url') if not appointment_url: self._log("GetEAppointmentUrl returned empty URL.") res.availability_status = AvailabilityStatus.NoneAvailable return res tab = self.page.new_tab(appointment_url) try: tab.wait.doc_loaded() site_key = '5f64399c-14a8-415e-ad1a-7ebccdc4943a' capsolver_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '') token = self.get_captcha_solution(capsolver_key, site_key, appointment_url) inject_script = f""" (function() {{ var token = "{token}"; var textareas = [ document.querySelector('textarea[name="h-captcha-response"]'), document.querySelector('textarea[name="g-recaptcha-response"]'), document.querySelector('[name="h-captcha-response"]'), document.querySelector('[name="g-recaptcha-response"]') ]; textareas.forEach(function(el) {{ if (el) {{ el.value = token; el.innerHTML = token; el.dispatchEvent(new Event('input', {{ bubbles: true }})); el.dispatchEvent(new Event('change', {{ bubbles: true }})); }} }}); if (typeof window.hcaptcha !== 'undefined' && typeof window.hcaptcha.setData === 'function') {{ try {{ window.hcaptcha.setData(null, {{ response: token }}); }} catch(e) {{}} }} if (typeof window.onHCaptchaSuccess === 'function') {{ window.onHCaptchaSuccess(token); }} }})(); """ tab.run_js(inject_script) time.sleep(2) btn = tab.ele('tag:button@@type=submit', timeout=2) or tab.ele('tag:input@@type=submit', timeout=2) if btn: btn.click() tab.wait.doc_loaded() time.sleep(3) self._log(f"Page title after hCaptcha submit: {tab.title}") available_dates = [] date_eles = tab.eles('.available-date, .calendar-day-available, [data-date]') for d_ele in date_eles: d_str = d_ele.attr('data-date') or d_ele.text if d_str and re.match(r'^\d{4}-\d{2}-\d{2}$', d_str.strip()): available_dates.append(d_str.strip()) if 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 ] else: res.success = False res.availability_status = AvailabilityStatus.NoneAvailable res.availability = [] finally: try: tab.close() except Exception: pass return res def get_captcha_solution(self, api_key: str, site_key: str, site_url: str) -> str: """ 调用 Capsolver 解决 hCaptcha (HCaptchaTaskProxyLess) """ if not api_key: api_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '') return solve_capsolver_hcaptcha( api_token=api_key, site_key=site_key, page_url=site_url, proxy=self.config.proxy if self.config else None, logger=self._log ) def book(self, slot_info: QueryResult, user_inputs: Dict = None) -> BookResult: res = BookResult() return res 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") return perform_browser_fetch( self.page, method=method, url=url, headers=headers, data=data, json_data=json_data, params=params ) 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()