pol_plugin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. Germany (Visametric) 签证预约插件 (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 * 60:
  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.scheme}://{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. co.set_argument('--ignore-certificate-errors')
  125. try:
  126. self.page = ChromiumPage(co)
  127. url_home = "https://secure.e-konsulat.gov.pl"
  128. self._log(f"Navigating to {url_home}")
  129. self.page.get(url_home)
  130. self.page.wait.doc_loaded()
  131. self.session_create_time = time.time()
  132. self._log("Session created successfully.")
  133. except Exception as e:
  134. self._log(f"Session Create Failed: {e}")
  135. self.cleanup()
  136. raise e
  137. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  138. res = VSQueryResult()
  139. res.success = False
  140. query_url = self.free_config.get('query_url')
  141. service_type = self.free_config.get('service_type')
  142. location = self.free_config.get('location')
  143. self._log(f"Navigating to {query_url}")
  144. self.page.get(query_url)
  145. captcha_image_selector = 't:img@alt=Weryfikacja obrazkowa'
  146. if not self.page.wait.ele_displayed(captcha_image_selector, timeout=30):
  147. raise BizLogicError(message=f"Wait for selector={captcha_image_selector} timeout")
  148. time.sleep(3)
  149. img_ele = self.page.ele(captcha_image_selector)
  150. img_src = img_ele.attr('src')
  151. base64_data = img_src.split(',')[1]
  152. image_bytes = base64.b64decode(base64_data)
  153. result = self.reader.readtext(image_bytes)
  154. captcha_code = result[0][-2] if result else ""
  155. self._log(f"Captcha code={captcha_code}")
  156. if not captcha_code:
  157. BizLogicError(message="Solve captcha failed")
  158. input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
  159. input_ele.clear()
  160. input_ele.input(captcha_code)
  161. btn_selector = 'Dalej'
  162. self.page.ele(btn_selector).click(by_js=True)
  163. toast_ele = self.page.ele('tag:app-toast', timeout=2)
  164. if toast_ele:
  165. error_msg = toast_ele.text.replace('\n', ' ').strip()
  166. raise BizLogicError(message=f"Captcha verify error={error_msg}")
  167. if not self._select_mat_option('Rodzaj usługi', service_type):
  168. raise BizLogicError(message=f'Process select box failed')
  169. if not self._select_mat_option('Lokalizacja', location):
  170. raise BizLogicError(message=f'Process select box failed')
  171. if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
  172. raise BizLogicError(message=f'Process select box failed')
  173. available_dates = []
  174. self._log("Wait Query Slot...")
  175. for _ in range(20):
  176. try:
  177. no_slot_alert = self.page.ele('text:Chwilowo wszystkie udostępnione terminy', timeout=0.1)
  178. if no_slot_alert:
  179. self._log("No slots available")
  180. break
  181. listbox = self.page.ele('@role=listbox', timeout=0.1)
  182. if not listbox:
  183. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=0.5)
  184. if termin_label:
  185. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  186. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  187. try:
  188. termin_select.click()
  189. except:
  190. termin_select.click(by_js=True)
  191. time.sleep(0.5)
  192. listbox = self.page.ele('@role=listbox', timeout=1)
  193. if listbox:
  194. option_elements = listbox.eles('.mat-option-text')
  195. for ele in option_elements:
  196. date_str = ele.text.strip()
  197. if date_str:
  198. available_dates.append(date_str)
  199. if available_dates:
  200. self._log(f"✅ Success extracted dates: {available_dates}")
  201. break
  202. except Exception as e:
  203. self._log(f"Query loop exception: {e}")
  204. time.sleep(0.5)
  205. if available_dates:
  206. selected_date = random.choice(available_dates)
  207. self._log(f"🎲 Random select date: {selected_date}...")
  208. locked = self._lock_slot(selected_date)
  209. if locked:
  210. session_id = self._save_browser_session()
  211. wechat_message = f"🎉 [Poland] Slot locked\n📍 location: {location}\n📅 date: {selected_date}\n🔑 SessionId: {session_id}"
  212. VSCloudApi.Instance().push_weixin_text(wechat_message)
  213. res.success = True
  214. res.availability_status = AvailabilityStatus.Available
  215. earliest_date = available_dates[0]
  216. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  217. res.earliest_date = earliest_dt
  218. res.availability = [
  219. DateAvailability(
  220. date=datetime.strptime(d, "%Y-%m-%d"),
  221. times=[],
  222. )
  223. for d in available_dates
  224. ]
  225. else:
  226. res.success = False
  227. res.availability_status = AvailabilityStatus.NoneAvailable
  228. res.availability = []
  229. return res
  230. def _lock_slot(self, lock_date):
  231. slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
  232. slot_ele = self.page.ele(slot_selector, timeout=1)
  233. if not slot_ele:
  234. termin_label = self.page.ele('tag:mat-label@@text():Termin', timeout=1)
  235. if termin_label:
  236. termin_select = termin_label.parent('tag:app-select-control').ele('tag:mat-select')
  237. if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
  238. try:
  239. termin_select.click()
  240. except:
  241. termin_select.click(by_js=True)
  242. time.sleep(0.5)
  243. slot_ele = self.page.ele(slot_selector, timeout=3)
  244. if not slot_ele:
  245. self._log(f"❌ Can't find date {lock_date} to click.")
  246. return False
  247. try:
  248. slot_ele.click()
  249. except:
  250. slot_ele.click(by_js=True)
  251. self._log(f"✅ Clicked date: {lock_date}")
  252. time.sleep(1)
  253. btn_selector = 'xpath://button[.//span[contains(text(), "Dalej")]]'
  254. next_btn = self.page.ele(btn_selector, timeout=3)
  255. if not next_btn:
  256. self._log("❌ Can't find 'Dalej' button")
  257. return False
  258. try:
  259. next_btn.click()
  260. except:
  261. next_btn.click(by_js=True)
  262. self._log("✅ Clicked Dalej, locking slot...")
  263. return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
  264. def _select_mat_option(self, label_text, option_text):
  265. self._log(f"choose: {label_text} -> {option_text}")
  266. label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
  267. if not label:
  268. self._log(f"Can't find label: {label_text}")
  269. return False
  270. container = label.parent('tag:app-select-control')
  271. select_box = container.ele('tag:mat-select')
  272. if not select_box:
  273. self._log("Can't find select box")
  274. return False
  275. select_box.click(by_js=True)
  276. time.sleep(0.5)
  277. option = self.page.ele(f'tag:mat-option@@text():{option_text}', timeout=3)
  278. if option:
  279. option.click(by_js=True)
  280. time.sleep(0.5)
  281. return True
  282. else:
  283. self._log(f"Can't find option: {option_text}")
  284. return False
  285. def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
  286. res = VSBookResult()
  287. return res
  288. def _save_browser_session(self):
  289. self._log("Abstract browser session env...")
  290. cookies_dict = self.page.cookies(all_domains=True, all_info=True)
  291. cookies_str = cookies_dict.as_json()
  292. local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
  293. session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
  294. proxy_str = ""
  295. if hasattr(self, 'config') and hasattr(self.config, 'proxy') and self.config.proxy.ip:
  296. p = self.config.proxy
  297. if p.username and p.password:
  298. proxy_str = f"{p.scheme}://{p.username}:{p.password}@{p.ip}:{p.port}"
  299. else:
  300. proxy_str = f"{p.scheme}://{p.ip}:{p.port}"
  301. session_data = VSCloudApi.Instance().create_http_session(
  302. session_id=str(uuid.uuid4().hex),
  303. cookies=cookies_str,
  304. local_storage=local_storage_str,
  305. session_storage=session_storage_str,
  306. user_agent=self.page.user_agent,
  307. page=self.page.url,
  308. proxy=proxy_str
  309. )
  310. return session_data.get('session_id')
  311. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  312. if not self.page:
  313. raise BizLogicError("Browser not init")
  314. req_url = url
  315. if params:
  316. sep = '&' if '?' in req_url else '?'
  317. req_url += sep + urlencode(params)
  318. fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
  319. if json_data:
  320. fetch_opts['body'] = json.dumps(json_data)
  321. fetch_opts['headers']['Content-Type'] = 'application/json'
  322. elif data:
  323. if isinstance(data, dict):
  324. fetch_opts['body'] = urlencode(data)
  325. fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  326. else:
  327. fetch_opts['body'] = data
  328. js = f"""
  329. return fetch("{req_url}", {json.dumps(fetch_opts)})
  330. .then(async r => {{
  331. const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
  332. return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
  333. }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
  334. """
  335. resp = BrowserResponse(self.page.run_js(js, timeout=60))
  336. if resp.status_code == 200:
  337. return resp
  338. elif resp.status_code == 403:
  339. if "Just a moment" in resp.text and retry_count < 2:
  340. self._log("Cloudflare 403. Refreshing...")
  341. if self._refresh_firewall_session():
  342. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  343. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  344. elif resp.status_code == 429:
  345. self.is_healthy = False
  346. raise RateLimiteddError()
  347. elif resp.status_code in [401, 419]:
  348. self.is_healthy = False
  349. raise SessionExpiredOrInvalidError()
  350. else:
  351. raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
  352. def _filter_dates(self, dates, start, end):
  353. if not start or not end: return dates
  354. valid = []
  355. s = datetime.strptime(start[:10], "%Y-%m-%d")
  356. e = datetime.strptime(end[:10], "%Y-%m-%d")
  357. for d in dates:
  358. c = datetime.strptime(d, "%Y-%m-%d")
  359. if s <= c <= e: valid.append(d)
  360. random.shuffle(valid)
  361. return valid
  362. def cleanup(self):
  363. if self.page:
  364. try: self.page.quit()
  365. except: pass
  366. self.page = None
  367. if os.path.exists(self.root_workspace):
  368. for _ in range(3):
  369. try: time.sleep(0.2); shutil.rmtree(self.root_workspace, ignore_errors=True); break
  370. except: time.sleep(0.5)
  371. if self.tunnel:
  372. try: self.tunnel.stop()
  373. except: pass
  374. self.tunnel = None
  375. def __del__(self):
  376. self.cleanup()