pol_plugin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. import shutil
  8. import base64
  9. import socket
  10. import easyocr
  11. from datetime import datetime
  12. from typing import List, Dict, Optional, Any, Callable
  13. from urllib.parse import urljoin, urlparse, urlencode
  14. # DrissionPage 核心
  15. from DrissionPage import ChromiumPage, ChromiumOptions
  16. from vs_plg import IVSPlg
  17. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  18. from toolkit.vs_cloud_api import VSCloudApi
  19. from toolkit.proxy_tunnel import ProxyTunnel
  20. class BrowserResponse:
  21. def __init__(self, result_dict):
  22. result_dict = result_dict or {}
  23. self.status_code = result_dict.get('status', 0)
  24. self.text = result_dict.get('body', '')
  25. self.headers = result_dict.get('headers', {})
  26. self.url = result_dict.get('url', '')
  27. self._json = None
  28. def json(self):
  29. if self._json is None:
  30. if not self.text: return {}
  31. try: self._json = json.loads(self.text)
  32. except: self._json = {}
  33. return self._json
  34. def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
  35. dt = datetime.strptime(data_str, date_str_format)
  36. return dt.strftime("%Y-%m-%d")
  37. def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
  38. if "@" not in email: raise ValueError(f"Invalid email: {email}")
  39. local_part, _ = email.rsplit("@", 1)
  40. return f"{local_part}@{new_domain}"
  41. class PolPlugin(IVSPlg):
  42. """
  43. Poland (e-konsulat) 签证预约插件 (Browser + Tunnel Mode)
  44. """
  45. def __init__(self, group_id: str):
  46. self.group_id = group_id
  47. self.config: Optional[VSPlgConfig] = None
  48. self.free_config: Dict[str, Any] = {}
  49. self.logger = None
  50. # 浏览器实例
  51. self.page: Optional[ChromiumPage] = None
  52. # 资源隔离
  53. self.instance_id = uuid.uuid4().hex[:8]
  54. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  55. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  56. if not os.path.exists(self.root_workspace):
  57. os.makedirs(self.root_workspace)
  58. self.reader = easyocr.Reader(['en'], gpu=False)
  59. self.tunnel = None # 代理隧道
  60. self.is_healthy = True
  61. self.session_create_time: float = 0
  62. def set_log(self, logger: Callable[[str], None]) -> None:
  63. self.logger = logger
  64. def _log(self, message):
  65. if self.logger:
  66. self.logger(f'[PolPlugin] [{self.group_id}] {message}')
  67. else:
  68. print(f'[PolPlugin] [{self.group_id}] {message}')
  69. def set_config(self, config: VSPlgConfig):
  70. self.config = config
  71. self.free_config = config.free_config or {}
  72. def keep_alive(self):
  73. pass
  74. def health_check(self) -> bool:
  75. if not self.is_healthy:
  76. return False
  77. if not self.page:
  78. return False
  79. try:
  80. if not self.page.run_js("return 1;"):
  81. return False
  82. except:
  83. return False
  84. if self.config.session_max_life > 0:
  85. if time.time() - self.session_create_time > self.config.session_max_life:
  86. self._log("Session expired.")
  87. return False
  88. return True
  89. def create_session(self):
  90. """
  91. 创建会话:启动浏览器 -> 代理隧道 -> 提取 Captcha -> 本地识别 -> 提交 -> 获取 Context
  92. """
  93. self._log(f"Initializing Session (ID: {self.instance_id})...")
  94. co = ChromiumOptions()
  95. def get_free_port():
  96. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  97. s.bind(('', 0)); return s.getsockname()[1]
  98. co.set_local_port(get_free_port())
  99. co.set_user_data_path(self.user_data_path)
  100. chrome_path = os.getenv("CHROME_BIN")
  101. if chrome_path and os.path.exists(chrome_path):
  102. co.set_paths(browser_path=chrome_path)
  103. if self.config.proxy and self.config.proxy.ip:
  104. p = self.config.proxy
  105. if p.username and p.password:
  106. self._log(f"Starting Tunnel for {p.ip}...")
  107. self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
  108. local_proxy = self.tunnel.start()
  109. self._log(f"Tunnel started at {local_proxy}")
  110. co.set_argument(f'--proxy-server={local_proxy}')
  111. else:
  112. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  113. co.set_argument(f'--proxy-server={proxy_str}')
  114. else:
  115. self._log("[WARN] No proxy configured!")
  116. co.headless(False)
  117. co.set_argument('--no-sandbox')
  118. co.set_argument('--disable-gpu')
  119. co.set_argument('--disable-dev-shm-usage')
  120. co.set_argument('--window-size=1920,1080')
  121. co.set_argument('--disable-blink-features=AutomationControlled')
  122. try:
  123. self.page = ChromiumPage(co)
  124. url_home = "https://secure.e-konsulat.gov.pl"
  125. self._log(f"Navigating to {url_home}")
  126. self.page.get(url_home)
  127. self.page.wait.doc_loaded()
  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) -> VSQueryResult:
  135. res = VSQueryResult()
  136. res.success = False
  137. query_url = self.free_config.get('query_url')
  138. service_type = self.free_config.get('service_type')
  139. location = self.free_config.get('location')
  140. self._log(f"Navigating to {query_url}")
  141. self.page.get(query_url)
  142. captcha_image_selector = 't:img@alt=Weryfikacja obrazkowa'
  143. if not self.page.wait.ele_displayed(captcha_image_selector, timeout=30):
  144. raise BizLogicError(message=f"Wait for selector={captcha_image_selector} timeout")
  145. time.sleep(3)
  146. img_ele = self.page.ele(captcha_image_selector)
  147. img_src = img_ele.attr('src')
  148. base64_data = img_src.split(',')[1]
  149. image_bytes = base64.b64decode(base64_data)
  150. result = self.reader.readtext(image_bytes)
  151. captcha_code = result[0][-2] if result else ""
  152. self._log(f"Captcha code={captcha_code}")
  153. if not captcha_code:
  154. BizLogicError(message="Solve captcha failed")
  155. input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
  156. input_ele.clear()
  157. input_ele.input(captcha_code)
  158. btn_selector = 'Dalej'
  159. self.page.ele(btn_selector).click(by_js=True)
  160. toast_ele = self.page.ele('tag:app-toast', timeout=2)
  161. if toast_ele:
  162. error_msg = toast_ele.text.replace('\n', ' ').strip()
  163. raise BizLogicError(message=f"Captcha verify error={error_msg}")
  164. if not self._select_mat_option('Rodzaj usługi', service_type):
  165. raise BizLogicError(message=f'Process select box failed')
  166. if not self._select_mat_option('Lokalizacja', location):
  167. raise BizLogicError(message=f'Process select box failed')
  168. if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
  169. raise BizLogicError(message=f'Process select box failed')
  170. available_dates = []
  171. self._log("Wait Query Slot...")
  172. for _ in range(20):
  173. try:
  174. no_slot_alert = self.page.ele('text:Chwilowo wszystkie udostępnione terminy', timeout=0.1)
  175. if no_slot_alert:
  176. self._log("No slots available")
  177. break
  178. listbox = self.page.ele('@role=listbox', timeout=0.1)
  179. if not listbox:
  180. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=0.5)
  181. if termin_label:
  182. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  183. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  184. try:
  185. termin_select.click()
  186. except:
  187. termin_select.click(by_js=True)
  188. time.sleep(0.5)
  189. listbox = self.page.ele('@role=listbox', timeout=1)
  190. if listbox:
  191. option_elements = listbox.eles('.mat-option-text')
  192. for ele in option_elements:
  193. date_str = ele.text.strip()
  194. if date_str:
  195. available_dates.append(date_str)
  196. if available_dates:
  197. self._log(f"✅ Success extracted dates: {available_dates}")
  198. break
  199. except Exception as e:
  200. self._log(f"Query loop exception: {e}")
  201. time.sleep(0.5)
  202. if available_dates:
  203. selected_date = random.choice(available_dates)
  204. self._log(f"🎲 Random select date: {selected_date}...")
  205. locked = self._lock_slot(selected_date)
  206. if locked:
  207. session_id = self._save_browser_session()
  208. wechat_message = f"🎉 [Poland] Slot locked\n📍 location: {location}\n📅 date: {selected_date}\n🔑 SessionId: {session_id}"
  209. VSCloudApi.Instance().push_weixin_text(wechat_message)
  210. res.success = True
  211. res.availability_status = AvailabilityStatus.Available
  212. earliest_date = available_dates[0]
  213. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  214. res.earliest_date = earliest_dt
  215. res.availability = [
  216. DateAvailability(
  217. date=datetime.strptime(d, "%Y-%m-%d"),
  218. times=[],
  219. )
  220. for d in available_dates
  221. ]
  222. else:
  223. res.success = False
  224. res.availability_status = AvailabilityStatus.NoneAvailable
  225. res.availability = []
  226. return res
  227. def _lock_slot(self, lock_date):
  228. slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
  229. slot_ele = self.page.ele(slot_selector, timeout=1)
  230. if not slot_ele:
  231. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=1)
  232. if termin_label:
  233. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  234. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  235. try:
  236. termin_select.click()
  237. except:
  238. termin_select.click(by_js=True)
  239. time.sleep(0.5)
  240. slot_ele = self.page.ele(slot_selector, timeout=3)
  241. if not slot_ele:
  242. self._log(f"❌ Can't find date {lock_date} to click.")
  243. return False
  244. try:
  245. slot_ele.click()
  246. except:
  247. slot_ele.click(by_js=True)
  248. self._log(f"✅ Clicked date: {lock_date}")
  249. time.sleep(1)
  250. btn_selector = 'xpath://button[.//span[contains(text(), "Dalej")]]'
  251. next_btn = self.page.ele(btn_selector, timeout=3)
  252. if not next_btn:
  253. self._log("❌ Can't find 'Dalej' button")
  254. return False
  255. try:
  256. next_btn.click()
  257. except:
  258. next_btn.click(by_js=True)
  259. self._log("✅ Clicked Dalej, locking slot...")
  260. return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
  261. def _select_mat_option(self, label_text, option_text):
  262. self._log(f"choose: {label_text} -> {option_text}")
  263. label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
  264. if not label:
  265. self._log(f"Can't find label: {label_text}")
  266. return False
  267. container = label.parent('tag:app-select-control')
  268. select_box = container.ele('tag:mat-select')
  269. if not select_box:
  270. self._log("Can't find select box")
  271. return False
  272. select_box.click(by_js=True)
  273. time.sleep(0.5)
  274. option = self.page.ele(f'tag:mat-option@@text():{option_text}', timeout=3)
  275. if option:
  276. option.click(by_js=True)
  277. time.sleep(0.5)
  278. return True
  279. else:
  280. self._log(f"Can't find option: {option_text}")
  281. return False
  282. def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
  283. res = VSBookResult()
  284. return res
  285. def _save_browser_session(self):
  286. self._log("Abstract browser session env...")
  287. cookies_dict = self.page.cookies(all_domains=True, all_info=True)
  288. cookies_str = cookies_dict.as_json()
  289. local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
  290. session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
  291. proxy_str = ""
  292. if hasattr(self, 'config') and hasattr(self.config, 'proxy') and self.config.proxy.ip:
  293. p = self.config.proxy
  294. if p.username and p.password:
  295. proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
  296. else:
  297. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  298. session_data = VSCloudApi.Instance().create_http_session(
  299. session_id=str(uuid.uuid4().hex),
  300. cookies=cookies_str,
  301. local_storage=local_storage_str,
  302. session_storage=session_storage_str,
  303. user_agent=self.page.user_agent,
  304. page=self.page.url,
  305. proxy=proxy_str
  306. )
  307. return session_data.get('session_id')
  308. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  309. if not self.page:
  310. raise BizLogicError("Browser not init")
  311. req_url = url
  312. if params:
  313. sep = '&' if '?' in req_url else '?'
  314. req_url += sep + urlencode(params)
  315. fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
  316. if json_data:
  317. fetch_opts['body'] = json.dumps(json_data)
  318. fetch_opts['headers']['Content-Type'] = 'application/json'
  319. elif data:
  320. if isinstance(data, dict):
  321. fetch_opts['body'] = urlencode(data)
  322. fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  323. else:
  324. fetch_opts['body'] = data
  325. js = f"""
  326. return fetch("{req_url}", {json.dumps(fetch_opts)})
  327. .then(async r => {{
  328. const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
  329. return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
  330. }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
  331. """
  332. resp = BrowserResponse(self.page.run_js(js, timeout=60))
  333. if resp.status_code == 200:
  334. return resp
  335. elif resp.status_code == 403:
  336. if "Just a moment" in resp.text and retry_count < 2:
  337. self._log("Cloudflare 403. Refreshing...")
  338. if self._refresh_firewall_session():
  339. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  340. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  341. elif resp.status_code == 429:
  342. self.is_healthy = False
  343. raise RateLimiteddError()
  344. elif resp.status_code in [401, 419]:
  345. self.is_healthy = False
  346. raise SessionExpiredOrInvalidError()
  347. else:
  348. raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
  349. def _filter_dates(self, dates, start, end):
  350. if not start or not end: return dates
  351. valid = []
  352. s = datetime.strptime(start[:10], "%Y-%m-%d")
  353. e = datetime.strptime(end[:10], "%Y-%m-%d")
  354. for d in dates:
  355. c = datetime.strptime(d, "%Y-%m-%d")
  356. if s <= c <= e: valid.append(d)
  357. random.shuffle(valid)
  358. return valid
  359. def cleanup(self):
  360. if self.page:
  361. try: self.page.quit()
  362. except: pass
  363. self.page = None
  364. if os.path.exists(self.root_workspace):
  365. for _ in range(3):
  366. try: time.sleep(0.2); shutil.rmtree(self.root_workspace, ignore_errors=True); break
  367. except: time.sleep(0.5)
  368. if self.tunnel:
  369. try: self.tunnel.stop()
  370. except: pass
  371. self.tunnel = None
  372. def __del__(self):
  373. self.cleanup()