pol_plugin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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
  9. from typing import List, Dict, Optional, Any, Callable
  10. from DrissionPage import ChromiumPage
  11. from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
  12. from vs_plg import IVSPlg
  13. from vs_types import (
  14. VSPlgConfig,
  15. AppointmentType,
  16. VSQueryResult,
  17. VSBookResult,
  18. AvailabilityStatus,
  19. DateAvailability,
  20. NotFoundError,
  21. PermissionDeniedError,
  22. RateLimiteddError,
  23. SessionExpiredOrInvalidError,
  24. BizLogicError,
  25. PluginStatus,
  26. utc_now_str
  27. )
  28. from toolkit.vs_cloud_api import VSCloudApi
  29. from utils.plugin_utils import (
  30. BrowserResponse,
  31. init_chromium_options,
  32. perform_browser_fetch,
  33. filter_dates_in_range,
  34. cleanup_browser_workspace
  35. )
  36. class PolPlugin(IVSPlg):
  37. """
  38. Poland (e-konsulat) 签证预约插件 (Browser + Tunnel Mode)
  39. """
  40. name = "pol_plugin"
  41. version = "1.0.0"
  42. description = "波兰e-konsulat签证预约插件 (支持验证码识别与隧道代理)"
  43. def __init__(self, group_id: str):
  44. self.group_id = group_id
  45. self.config: Optional[VSPlgConfig] = 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.captcha_breaker = CaptchaBreaker()
  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'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  65. else:
  66. print(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  67. def set_config(self, config: VSPlgConfig):
  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:
  74. return False
  75. if not self.page:
  76. return False
  77. try:
  78. if not self.page.run_js("return 1;"):
  79. return False
  80. except Exception:
  81. return False
  82. if self.config.session_max_life > 0:
  83. if time.time() - self.session_create_time > self.config.session_max_life:
  84. self._log("Session expired.")
  85. return False
  86. return True
  87. def create_session(self):
  88. """
  89. 创建会话:启动浏览器 -> 配置代理隧道 -> 导航至首页
  90. """
  91. self._log(f"Initializing Session (ID: {self.instance_id})...")
  92. co, self.tunnel = init_chromium_options(
  93. user_data_path=self.user_data_path,
  94. username_seed=self.config.account.username if self.config and self.config.account else None,
  95. proxy=self.config.proxy if self.config else None,
  96. headless=False,
  97. window_size="1920,1080",
  98. logger=self._log
  99. )
  100. try:
  101. self.page = ChromiumPage(co)
  102. url_home = "https://secure.e-konsulat.gov.pl"
  103. self._log(f"Navigating to {url_home}")
  104. self.page.get(url_home)
  105. self.page.wait.doc_loaded()
  106. self.session_create_time = time.time()
  107. self._log("Session created successfully.")
  108. except Exception as e:
  109. self._log(f"Session Create Failed: {e}")
  110. self.cleanup()
  111. raise e
  112. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  113. res = VSQueryResult()
  114. res.success = False
  115. query_url = self.free_config.get('query_url')
  116. service_type = self.free_config.get('service_type')
  117. location = self.free_config.get('location')
  118. self._log(f"Navigating to {query_url}")
  119. self.page.get(query_url)
  120. captcha_image_selector = 't:img@alt=Weryfikacja obrazkowa'
  121. if not self.page.wait.ele_displayed(captcha_image_selector, timeout=30):
  122. raise BizLogicError(message=f"Wait for selector={captcha_image_selector} timeout")
  123. time.sleep(3)
  124. img_ele = self.page.ele(captcha_image_selector)
  125. img_src = img_ele.attr('src')
  126. try:
  127. captcha_code = self.captcha_breaker.break_captcha(img_src)
  128. self._log(f"Captcha code={captcha_code}")
  129. except CaptchaBreakerError as e:
  130. self._log(f"Solve captcha error: {e}")
  131. raise BizLogicError(message=f"Solve captcha failed: {e}") from e
  132. if not captcha_code:
  133. raise BizLogicError(message="Solve captcha failed")
  134. input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
  135. input_ele.clear()
  136. input_ele.input(captcha_code)
  137. btn_selector = 'Dalej'
  138. self.page.ele(btn_selector).click(by_js=True)
  139. toast_ele = self.page.ele('tag:app-toast', timeout=2)
  140. if toast_ele:
  141. error_msg = toast_ele.text.replace('\n', ' ').strip()
  142. raise BizLogicError(message=f"Captcha verify error={error_msg}")
  143. if not self._select_mat_option('Rodzaj usługi', service_type):
  144. raise BizLogicError(message='Process select box failed (service_type)')
  145. if not self._select_mat_option('Lokalizacja', location):
  146. raise BizLogicError(message='Process select box failed (location)')
  147. if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
  148. raise BizLogicError(message='Process select box failed (person count)')
  149. available_dates = []
  150. self._log("Wait Query Slot...")
  151. for _ in range(20):
  152. try:
  153. no_slot_alert = self.page.ele('text:Chwilowo wszystkie udostępnione terminy', timeout=0.1)
  154. if no_slot_alert:
  155. self._log("No slots available")
  156. break
  157. listbox = self.page.ele('@role=listbox', timeout=0.1)
  158. if not listbox:
  159. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=0.5)
  160. if termin_label:
  161. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  162. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  163. try:
  164. termin_select.click()
  165. except Exception:
  166. termin_select.click(by_js=True)
  167. time.sleep(0.5)
  168. listbox = self.page.ele('@role=listbox', timeout=1)
  169. if listbox:
  170. option_elements = listbox.eles('.mat-option-text')
  171. for ele in option_elements:
  172. date_str = ele.text.strip()
  173. if date_str:
  174. available_dates.append(date_str)
  175. if available_dates:
  176. self._log(f"✅ Success extracted dates: {available_dates}")
  177. break
  178. except Exception as e:
  179. self._log(f"Query loop exception: {e}")
  180. time.sleep(0.5)
  181. if available_dates:
  182. selected_date = random.choice(available_dates)
  183. self._log(f"🎲 Random select date: {selected_date}...")
  184. locked = self._lock_slot(selected_date)
  185. if locked:
  186. session_id = self._save_browser_session()
  187. wechat_message = f"🎉 [Poland] Slot locked\n📍 location: {location}\n📅 date: {selected_date}\n🔑 SessionId: {session_id}"
  188. VSCloudApi.Instance().push_weixin_text(wechat_message)
  189. res.success = True
  190. res.availability_status = AvailabilityStatus.Available
  191. earliest_date = available_dates[0]
  192. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  193. res.earliest_date = earliest_dt
  194. res.availability = [
  195. DateAvailability(
  196. date=datetime.strptime(d, "%Y-%m-%d"),
  197. times=[],
  198. )
  199. for d in available_dates
  200. ]
  201. else:
  202. res.success = False
  203. res.availability_status = AvailabilityStatus.NoneAvailable
  204. res.availability = []
  205. return res
  206. def _lock_slot(self, lock_date: str) -> bool:
  207. slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
  208. slot_ele = self.page.ele(slot_selector, timeout=1)
  209. if not slot_ele:
  210. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=1)
  211. if termin_label:
  212. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  213. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  214. try:
  215. termin_select.click()
  216. except Exception:
  217. termin_select.click(by_js=True)
  218. time.sleep(0.5)
  219. slot_ele = self.page.ele(slot_selector, timeout=3)
  220. if not slot_ele:
  221. self._log(f"❌ Can't find date {lock_date} to click.")
  222. return False
  223. try:
  224. slot_ele.click()
  225. except Exception:
  226. slot_ele.click(by_js=True)
  227. self._log(f"✅ Clicked date: {lock_date}")
  228. time.sleep(1)
  229. btn_selector = 'xpath://button[.//span[contains(text(), "Dalej")]]'
  230. next_btn = self.page.ele(btn_selector, timeout=3)
  231. if not next_btn:
  232. self._log("❌ Can't find 'Dalej' button")
  233. return False
  234. try:
  235. next_btn.click()
  236. except Exception:
  237. next_btn.click(by_js=True)
  238. self._log("✅ Clicked Dalej, locking slot...")
  239. return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
  240. def _select_mat_option(self, label_text: str, option_text: str) -> bool:
  241. self._log(f"choose: {label_text} -> {option_text}")
  242. label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
  243. if not label:
  244. self._log(f"Can't find label: {label_text}")
  245. return False
  246. container = label.parent('tag:app-select-control')
  247. select_box = container.ele('tag:mat-select')
  248. if not select_box:
  249. self._log("Can't find select box")
  250. return False
  251. select_box.click(by_js=True)
  252. time.sleep(0.5)
  253. option = self.page.ele(f'tag:mat-option@@text():{option_text}', timeout=3)
  254. if option:
  255. option.click(by_js=True)
  256. time.sleep(0.5)
  257. return True
  258. else:
  259. self._log(f"Can't find option: {option_text}")
  260. return False
  261. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  262. res = VSBookResult()
  263. return res
  264. def _save_browser_session(self) -> str:
  265. self._log("Extracting browser session environment...")
  266. cookies_dict = self.page.cookies(all_domains=True, all_info=True)
  267. cookies_str = cookies_dict.as_json()
  268. local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
  269. session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
  270. proxy = getattr(getattr(self, 'config', None), 'proxy', None)
  271. if proxy and getattr(proxy, 'ip', None):
  272. p = proxy
  273. if p.username and p.password:
  274. proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
  275. else:
  276. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  277. session_data = VSCloudApi.Instance().create_http_session(
  278. session_id=str(uuid.uuid4().hex),
  279. cookies=cookies_str,
  280. local_storage=local_storage_str,
  281. session_storage=session_storage_str,
  282. user_agent=self.page.user_agent,
  283. page=self.page.url,
  284. proxy=proxy_str
  285. )
  286. return session_data.get('session_id', '')
  287. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  288. """在浏览器上下文中注入执行 Fetch"""
  289. if not self.page:
  290. raise BizLogicError("Browser not initialized")
  291. resp = perform_browser_fetch(
  292. self.page,
  293. method=method,
  294. url=url,
  295. headers=headers,
  296. data=data,
  297. json_data=json_data,
  298. params=params
  299. )
  300. if resp.status_code == 200:
  301. return resp
  302. elif resp.status_code == 403:
  303. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  304. elif resp.status_code == 429:
  305. self.is_healthy = False
  306. raise RateLimiteddError()
  307. elif resp.status_code in (401, 419):
  308. self.is_healthy = False
  309. raise SessionExpiredOrInvalidError()
  310. else:
  311. raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
  312. def cleanup(self):
  313. """销毁浏览器并彻底删除临时文件"""
  314. cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
  315. self.page = None
  316. self.tunnel = None
  317. def get_plugin_status(self) -> PluginStatus:
  318. account_name = self.config.account.username if self.config and self.config.account else ""
  319. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  320. current_url = ""
  321. if self.page:
  322. try:
  323. current_url = self.page.url
  324. except Exception:
  325. pass
  326. session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
  327. state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
  328. return PluginStatus(
  329. instance_id=self.instance_id,
  330. is_healthy=self.is_healthy,
  331. state=state,
  332. current_url=current_url,
  333. account=account_name,
  334. proxy=proxy_info,
  335. session_age_sec=session_age,
  336. last_active_at=utc_now_str(),
  337. )
  338. def __del__(self):
  339. """
  340. 析构函数:当对象被垃圾回收时自动调用
  341. """
  342. self.cleanup()