pol_plugin.py 17 KB

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