bel_plugin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. from datetime import datetime
  8. from typing import List, Dict, Optional, Any, Callable
  9. from DrissionPage import ChromiumPage
  10. from plugin import IPlugin
  11. from core_types import (
  12. PluginConfig,
  13. AppointmentType,
  14. QueryResult,
  15. BookResult,
  16. AvailabilityStatus,
  17. TimeSlot,
  18. DateAvailability,
  19. NotFoundError,
  20. PermissionDeniedError,
  21. RateLimiteddError,
  22. SessionExpiredOrInvalidError,
  23. BizLogicError,
  24. PluginStatus,
  25. utc_now_str
  26. )
  27. from utils.plugin_utils import (
  28. BrowserResponse,
  29. init_chromium_options,
  30. perform_browser_fetch,
  31. filter_dates_in_range,
  32. solve_capsolver_hcaptcha,
  33. cleanup_browser_workspace
  34. )
  35. class BelPlugin(IPlugin):
  36. booking_supported = False
  37. """
  38. Belgium (https://visaonweb.diplomatie.be/en) 签证预约插件 (Browser + Tunnel Mode)
  39. """
  40. name = "bel_plugin"
  41. version = "1.0.0"
  42. description = "比利时签证预约插件 (Visa On Web / 浏览器与隧道模式)"
  43. def __init__(self, group_id: str):
  44. self.group_id = group_id
  45. self.config: Optional[PluginConfig] = None
  46. self.free_config: Dict[str, Any] = {}
  47. self.logger = None
  48. # 浏览器实例
  49. self.page: Optional[ChromiumPage] = None
  50. # 资源隔离
  51. self.instance_id = uuid.uuid4().hex[:8]
  52. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  53. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  54. if not os.path.exists(self.root_workspace):
  55. os.makedirs(self.root_workspace)
  56. self.applicants = []
  57. self.tunnel = None # 代理隧道
  58. self.is_healthy = True
  59. self.session_create_time: float = 0
  60. def set_log(self, logger: Callable[[str], None]) -> None:
  61. self.logger = logger
  62. def _log(self, message):
  63. if self.logger:
  64. self.logger(f'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  65. else:
  66. print(f'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  67. def set_config(self, config: PluginConfig):
  68. self.config = config
  69. self.free_config = config.free_config or {}
  70. def keep_alive(self):
  71. pass
  72. def health_check(self) -> bool:
  73. if not self.is_healthy or not self.page:
  74. return False
  75. try:
  76. if not self.page.run_js("return 1;"):
  77. return False
  78. except Exception:
  79. return False
  80. if self.config.session_max_life > 0:
  81. if time.time() - self.session_create_time > self.config.session_max_life:
  82. self._log("Session expired.")
  83. return False
  84. return True
  85. def create_session(self):
  86. """
  87. 创建会话:启动浏览器 -> 代理隧道 -> 登录 -> 获取申请人列表
  88. """
  89. self._log(f"Initializing Session (ID: {self.instance_id})...")
  90. co, self.tunnel = init_chromium_options(
  91. user_data_path=self.user_data_path,
  92. username_seed=self.config.account.username if self.config and self.config.account else None,
  93. proxy=self.config.proxy if self.config else None,
  94. headless=False,
  95. window_size="1920,1080",
  96. logger=self._log
  97. )
  98. co.set_argument('--ignore-certificate-errors')
  99. try:
  100. self.page = ChromiumPage(co)
  101. url_home = "https://visaonweb.diplomatie.be/Account/Login?ReturnUrl=%2Fen"
  102. self._log(f"Navigating to {url_home}")
  103. self.page.get(url_home)
  104. self.page.wait.doc_loaded()
  105. self.page.wait.ele_displayed('tag:button@@type=submit', timeout=10)
  106. self.page.ele('tag:input@@name=UserName').input(self.config.account.username)
  107. self.page.ele('tag:input@@name=Password').input(self.config.account.password)
  108. self.page.ele('tag:button@@type=submit').click()
  109. self.page.listen.start('/VisaApplication/MyList')
  110. self.page.get('https://visaonweb.diplomatie.be/en/VisaApplication/IndexByUserId')
  111. packet = self.page.listen.wait(timeout=10)
  112. if not packet:
  113. raise BizLogicError(message='Get userList failed')
  114. self.page.listen.stop()
  115. resp_body = packet.response.body
  116. for dat in resp_body.get('data', []):
  117. if dat.get('St') == 'Submitted':
  118. applicant = {
  119. "id": dat.get('Id'),
  120. "first_name": dat.get('FName'),
  121. "last_name": dat.get('LName'),
  122. "vow_id": dat.get('VOWId'),
  123. "os_id": dat.get('OSId'),
  124. "sub_group_id": dat.get('SubGroupId'),
  125. "vac": dat.get('Vac'),
  126. }
  127. self.applicants.append(applicant)
  128. self.session_create_time = time.time()
  129. self._log("Session created successfully.")
  130. except Exception as e:
  131. self._log(f"Session Create Failed: {e}")
  132. self.cleanup()
  133. raise e
  134. def query(self, apt_type: AppointmentType) -> QueryResult:
  135. res = QueryResult()
  136. res.success = False
  137. if not self.applicants:
  138. self._log("No submitted applicants available to query appointment.")
  139. res.availability_status = AvailabilityStatus.NoneAvailable
  140. return res
  141. applicant = random.choice(self.applicants)
  142. applicant_id = applicant.get('id')
  143. url = 'https://visaonweb.diplomatie.be/Common/GetEAppointmentUrl'
  144. params = {
  145. 'id': applicant_id
  146. }
  147. headers = {
  148. "cache-control": "max-age=0",
  149. "if-modified-since": "0",
  150. "x-requested-with": "XMLHttpRequest",
  151. }
  152. resp = self._perform_request('GET', url, headers=headers, params=params)
  153. appointment_url = resp.json().get('url')
  154. if not appointment_url:
  155. self._log("GetEAppointmentUrl returned empty URL.")
  156. res.availability_status = AvailabilityStatus.NoneAvailable
  157. return res
  158. tab = self.page.new_tab(appointment_url)
  159. try:
  160. tab.wait.doc_loaded()
  161. site_key = '5f64399c-14a8-415e-ad1a-7ebccdc4943a'
  162. capsolver_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
  163. token = self.get_captcha_solution(capsolver_key, site_key, appointment_url)
  164. inject_script = f"""
  165. (function() {{
  166. var token = "{token}";
  167. var textareas = [
  168. document.querySelector('textarea[name="h-captcha-response"]'),
  169. document.querySelector('textarea[name="g-recaptcha-response"]'),
  170. document.querySelector('[name="h-captcha-response"]'),
  171. document.querySelector('[name="g-recaptcha-response"]')
  172. ];
  173. textareas.forEach(function(el) {{
  174. if (el) {{
  175. el.value = token;
  176. el.innerHTML = token;
  177. el.dispatchEvent(new Event('input', {{ bubbles: true }}));
  178. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  179. }}
  180. }});
  181. if (typeof window.hcaptcha !== 'undefined' && typeof window.hcaptcha.setData === 'function') {{
  182. try {{ window.hcaptcha.setData(null, {{ response: token }}); }} catch(e) {{}}
  183. }}
  184. if (typeof window.onHCaptchaSuccess === 'function') {{
  185. window.onHCaptchaSuccess(token);
  186. }}
  187. }})();
  188. """
  189. tab.run_js(inject_script)
  190. time.sleep(2)
  191. btn = tab.ele('tag:button@@type=submit', timeout=2) or tab.ele('tag:input@@type=submit', timeout=2)
  192. if btn:
  193. btn.click()
  194. tab.wait.doc_loaded()
  195. time.sleep(3)
  196. self._log(f"Page title after hCaptcha submit: {tab.title}")
  197. available_dates = []
  198. date_eles = tab.eles('.available-date, .calendar-day-available, [data-date]')
  199. for d_ele in date_eles:
  200. d_str = d_ele.attr('data-date') or d_ele.text
  201. if d_str and re.match(r'^\d{4}-\d{2}-\d{2}$', d_str.strip()):
  202. available_dates.append(d_str.strip())
  203. if available_dates:
  204. res.success = True
  205. res.availability_status = AvailabilityStatus.Available
  206. earliest_date = available_dates[0]
  207. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  208. res.earliest_date = earliest_dt
  209. res.availability = [
  210. DateAvailability(
  211. date=datetime.strptime(d, "%Y-%m-%d"),
  212. times=[],
  213. )
  214. for d in available_dates
  215. ]
  216. else:
  217. res.success = False
  218. res.availability_status = AvailabilityStatus.NoneAvailable
  219. res.availability = []
  220. finally:
  221. try:
  222. tab.close()
  223. except Exception:
  224. pass
  225. return res
  226. def get_captcha_solution(self, api_key: str, site_key: str, site_url: str) -> str:
  227. """
  228. 调用 Capsolver 解决 hCaptcha (HCaptchaTaskProxyLess)
  229. """
  230. if not api_key:
  231. api_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
  232. return solve_capsolver_hcaptcha(
  233. api_token=api_key,
  234. site_key=site_key,
  235. page_url=site_url,
  236. proxy=self.config.proxy if self.config else None,
  237. logger=self._log
  238. )
  239. def book(self, slot_info: QueryResult, user_inputs: Dict = None) -> BookResult:
  240. res = BookResult()
  241. return res
  242. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  243. """在浏览器上下文中注入执行 Fetch"""
  244. if not self.page:
  245. raise BizLogicError("Browser not initialized")
  246. return perform_browser_fetch(
  247. self.page,
  248. method=method,
  249. url=url,
  250. headers=headers,
  251. data=data,
  252. json_data=json_data,
  253. params=params
  254. )
  255. def cleanup(self):
  256. """销毁浏览器并彻底删除临时文件"""
  257. cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
  258. self.page = None
  259. self.tunnel = None
  260. def get_plugin_status(self) -> PluginStatus:
  261. account_name = self.config.account.username if self.config and self.config.account else ""
  262. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  263. current_url = ""
  264. if self.page:
  265. try:
  266. current_url = self.page.url
  267. except Exception:
  268. pass
  269. session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
  270. state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
  271. return PluginStatus(
  272. instance_id=self.instance_id,
  273. is_healthy=self.is_healthy,
  274. state=state,
  275. current_url=current_url,
  276. account=account_name,
  277. proxy=proxy_info,
  278. session_age_sec=session_age,
  279. last_active_at=utc_now_str(),
  280. )
  281. def __del__(self):
  282. """
  283. 析构函数:当对象被垃圾回收时自动调用
  284. """
  285. self.cleanup()