usa_plugin.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. import shutil
  8. import socket
  9. from datetime import date, datetime
  10. from typing import List, Dict, Optional, Any, Callable
  11. from urllib.parse import urljoin, urlparse, urlencode, parse_qs
  12. from concurrent.futures import ThreadPoolExecutor
  13. from DrissionPage import ChromiumPage, ChromiumOptions
  14. import configure
  15. from vs_plg import IVSPlg
  16. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  17. from toolkit.mihomo_tunnel import MihomoTunnel
  18. from utils.mouse import HumanMouse
  19. from utils.keyboard import HumanKeyboard
  20. from utils.fingerprint_utils import FingerprintGenerator
  21. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  22. class BrowserResponse:
  23. """模拟 requests.Response"""
  24. def __init__(self, result_dict):
  25. result_dict = result_dict or {}
  26. self.status_code = result_dict.get('status', 0)
  27. self.text = result_dict.get('body', '')
  28. self.headers = result_dict.get('headers', {})
  29. self.url = result_dict.get('url', '')
  30. self._json = None
  31. def json(self):
  32. if self._json is None:
  33. if not self.text:
  34. return {}
  35. try:
  36. self._json = json.loads(self.text)
  37. except:
  38. self._json = {}
  39. return self._json
  40. class UsaPlugin(IVSPlg):
  41. LOCATIONS = {
  42. "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
  43. "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
  44. "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
  45. }
  46. def __init__(self, group_id: str):
  47. self.group_id = group_id
  48. self.config: Optional[VSPlgConfig] = None
  49. self.free_config: Dict[str, Any] = {}
  50. self.is_healthy = True
  51. self.logger = None
  52. self.mouse = None
  53. self.keyboard = None
  54. self.page: Optional[ChromiumPage] = None
  55. self.instance_id = uuid.uuid4().hex[:8]
  56. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  57. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  58. if not os.path.exists(self.root_workspace):
  59. os.makedirs(self.root_workspace)
  60. self.tunnel = None
  61. self.session_create_time: float = 0
  62. def _log(self, message):
  63. if self.logger:
  64. self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  65. else:
  66. print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  67. def _get_free_port(self):
  68. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  69. s.bind(('', 0))
  70. return s.getsockname()[1]
  71. def set_config(self, config: VSPlgConfig):
  72. """设置 API 的配置信息"""
  73. self.config = config
  74. self.free_config = config.free_config or {}
  75. def set_log(self, logger: Callable[[str], None]) -> None:
  76. """设置日志输出工具"""
  77. self.logger = logger
  78. def keep_alive(self):
  79. pass
  80. def health_check(self) -> bool:
  81. if not self.is_healthy:
  82. return False
  83. if self.page is None:
  84. return False
  85. try:
  86. if not self.page.run_js("return 1;"):
  87. return False
  88. except:
  89. return False
  90. if self.config.session_max_life > 0:
  91. current_time = time.time()
  92. elapsed_time = current_time - self.session_create_time
  93. if elapsed_time > self.config.session_max_life:
  94. self._log(f"Session expired.")
  95. return False
  96. return True
  97. def _save_screenshot(self, name_prefix):
  98. try:
  99. timestamp = int(time.time())
  100. filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
  101. save_path = os.path.join("data", filename)
  102. os.makedirs("data", exist_ok=True)
  103. self.page.get_screenshot(path=save_path, full_page=False)
  104. self._log(f"Screenshot saved to {save_path}")
  105. except Exception as e:
  106. self._log(f"Failed to save screenshot: {e}")
  107. def create_session(self) -> None:
  108. """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
  109. self._log(f"Initializing Session (ID: {self.instance_id})...")
  110. def get_free_port():
  111. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  112. s.bind(('', 0))
  113. return s.getsockname()[1]
  114. co = ChromiumOptions()
  115. debug_port = get_free_port()
  116. self._log(f"Assigned Debug Port: {debug_port}")
  117. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  118. co.set_local_port(debug_port)
  119. co.set_user_data_path(self.user_data_path)
  120. chrome_path = configure.CHROME_PATH
  121. if not chrome_path:
  122. chrome_path = os.getenv("CHROME_BIN")
  123. if chrome_path and os.path.exists(chrome_path):
  124. co.set_paths(browser_path=chrome_path)
  125. if self.config.proxy and self.config.proxy.ip:
  126. p = self.config.proxy
  127. if p.username and p.password:
  128. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  129. exit_node = {
  130. "name": "ExitNode",
  131. "type": p.proto,
  132. "server": p.ip,
  133. "port": p.port,
  134. "username": p.username,
  135. "password": p.password
  136. }
  137. relay_node = None
  138. if configure.MIHOMO_RELAY_NODES:
  139. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  140. mihomo_path = configure.MIHOMO_BIN_PATH
  141. if not mihomo_path:
  142. mihomo_path = os.getenv("MIHOMO_BIN")
  143. if not mihomo_path:
  144. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  145. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  146. local_proxy = self.tunnel.start()
  147. self._log(f"Tunnel started at {local_proxy}")
  148. co.set_argument(f'--proxy-server={local_proxy}')
  149. else:
  150. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  151. co.set_argument(f'--proxy-server={proxy_str}')
  152. else:
  153. self._log("[WARN] No proxy configured!")
  154. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  155. fp_seed = specific_fp.get("seed")
  156. fp_platform = specific_fp.get("platform")
  157. fp_brand = specific_fp.get("brand")
  158. self._log(f'browser fingerprint seed={fp_seed}')
  159. co.headless(False)
  160. co.set_argument('--no-sandbox')
  161. co.set_argument('--disable-dev-shm-usage')
  162. co.set_argument('--window-size=1920,1080')
  163. co.set_argument('--disable-blink-features=AutomationControlled')
  164. co.set_argument(f"--fingerprint={fp_seed}")
  165. co.set_argument(f"--fingerprint-platform={fp_platform}")
  166. co.set_argument(f"--fingerprint-brand={fp_brand}")
  167. self.page = ChromiumPage(co)
  168. # 获取基础 URL
  169. usa_url = self.free_config.get('usa_url', '')
  170. self._log(f"Navigating: {usa_url}")
  171. self.page.get(usa_url)
  172. time.sleep(5)
  173. if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
  174. self._log(f'Block by cloudflare, try refresh...')
  175. self.page.refresh()
  176. self.page.wait.load_start(timeout=2)
  177. self.page.wait.doc_loaded()
  178. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  179. if not cf_bypasser.bypass(max_retry=6):
  180. raise BizLogicError("Cloudflare bypass timeout")
  181. time.sleep(3)
  182. cf_bypasser.handle_waiting_room()
  183. self._log("Init humanize tools...")
  184. self.mouse = HumanMouse(self.page, debug=False)
  185. self.keyboard = HumanKeyboard(self.page)
  186. viewport_width = self.page.rect.viewport_size[0]
  187. viewport_height = self.page.rect.viewport_size[1]
  188. init_x = random.randint(10, viewport_width - 10)
  189. init_y = random.randint(10, viewport_height - 10)
  190. self.mouse.move(init_x, init_y)
  191. username = self.config.account.username
  192. password = self.config.account.password
  193. security = self.free_config.get('security', {})
  194. max_steps = 15 # 由于状态多,步数可以稍微调大一点
  195. stuck_counter = 0
  196. last_url = ""
  197. session_created = False
  198. has_submitted_login = False
  199. for step in range(max_steps):
  200. self.page.wait.doc_loaded()
  201. time.sleep(1)
  202. current_url = self.page.url
  203. current_title = self.page.title.lower()
  204. current_html_content = self.page.html
  205. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  206. if current_url == last_url:
  207. stuck_counter += 1
  208. else:
  209. last_url = current_url
  210. stuck_counter = 0
  211. # --- [异常处理层] ---
  212. if stuck_counter >= 3:
  213. self._log("[WARN] Page stucked, try to refresh...")
  214. self.page.refresh()
  215. self.page.wait.load_start(timeout=5)
  216. stuck_counter = 0
  217. continue
  218. server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable"]
  219. # 网络出现故障,直接重试
  220. if any(err in current_html_content for err in server_error_indicators):
  221. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  222. time.sleep(2)
  223. self.page.refresh()
  224. self.page.wait.load_start(timeout=5)
  225. continue
  226. cloudflare_blocked_indicators = [
  227. "Sorry, you have been blocked" in current_html_content,
  228. "You are being rate limited" in current_html_content,
  229. "Cloudflare Ray ID" in current_html_content
  230. ]
  231. if any(cloudflare_blocked_indicators):
  232. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  233. # 遇到五秒盾先绕盾
  234. if "just a moment" in current_title:
  235. cf_bypasser.bypass(max_retry=3)
  236. time.sleep(3)
  237. continue
  238. if self.page.ele('#post_select', timeout=1):
  239. self._log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")
  240. self.session_create_time = time.time()
  241. session_created = True
  242. break
  243. # 状态 2: 密保问题页面
  244. elif self.page.ele('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]', timeout=1):
  245. self._log("[State] Security question verification detected. Filling in answers...")
  246. answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
  247. for ans_ele in answer_eles:
  248. ele_id = ans_ele.attr('id')
  249. match = re.search(r'kba(\d+)_response', ele_id)
  250. if match:
  251. q_num = match.group(1)
  252. config_key = f"{q_num}_quest"
  253. q_data = security.get(config_key)
  254. ans_text = q_data.get('a')
  255. ans_ele.input(ans_text)
  256. self._log(f"-> Find input {ele_id}, successfully filled in the answer for question {q_num}.")
  257. self.page.ele('#continue').click()
  258. self._log("Security answers submitted. Waiting for redirection...")
  259. time.sleep(3)
  260. continue
  261. # 状态 1: 登录页面
  262. elif self.page.ele('#signInName', timeout=1):
  263. self._log("[State] Login page detected. Submitting credentials...")
  264. username_input = self.page.ele('#signInName')
  265. username_input.clear()
  266. username_input.input(username)
  267. password_input = self.page.ele('#password')
  268. password_input.clear()
  269. password_input.input(password)
  270. self.page.ele('#continue').click()
  271. has_submitted_login = True
  272. self._log("Login form submitted. Waiting for the next step to load...")
  273. time.sleep(3)
  274. continue
  275. # 状态 3: 预约主页(控制台) -> 选择首签或改签
  276. elif self.page.ele('#atlas-sidebar', timeout=1):
  277. self._log("[State] At the main booking dashboard. Looking for navigation button...")
  278. reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
  279. if reschedule_btn:
  280. self._log("-> Detected [Reschedule Appointment]. Currently in rescheduling mode, clicking to proceed...")
  281. reschedule_btn.click()
  282. else:
  283. schedule_btn = self.page.ele('xpath://ul[@id="atlas-sidebar"]//a[text()="安排预约" or text()="New Appointment" or text()="Schedule Appointment"]', timeout=0.5)
  284. if schedule_btn:
  285. self._log("-> Detected [Schedule Appointment]. Currently in first-time booking mode, clicking to proceed...")
  286. schedule_btn.click()
  287. else:
  288. self._log("-> [WARN] Sidebar found, but no 'Schedule' or 'Reschedule' button detected. The page may still be loading...")
  289. time.sleep(3)
  290. continue
  291. else:
  292. self._log("[State] In unknown or transitional state. No matching UI elements found. Waiting for next polling cycle...")
  293. time.sleep(2)
  294. if not session_created:
  295. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  296. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  297. """查询可用的签证预约信息"""
  298. self._log("Querying available slots...")
  299. res = VSQueryResult()
  300. res.success = False
  301. # 1. 刷新页面以获取最新数据
  302. self.page.refresh()
  303. time.sleep(3)
  304. current_url = self.page.url.lower()
  305. if 'auth' in current_url or 'login' in current_url:
  306. self.is_healthy = False
  307. raise SessionExpiredOrInvalidError()
  308. applicant = self.free_config.get('applicant')
  309. location_name = self.free_config.get('location')
  310. location_id = self.LOCATIONS.get(location_name.upper(), {}).get('id')
  311. # 2. 等待页面元素
  312. self.page.ele(f"xpath://label[text()='{applicant}']", timeout=60)
  313. post_select = self.page.ele('#post_select', timeout=60)
  314. # 3. 选择领事馆
  315. self.page.ele(f"xpath://select[@id='post_select']/option[@value='{location_id}']", timeout=60)
  316. post_select.select.by_value(location_id)
  317. # 4. 等待日历加载
  318. self.page.ele('xpath://p[@id="datepicker-message"]', timeout=60)
  319. # 5. 抓取所有可用日期
  320. available_dates = []
  321. day_cells = self.page.eles("css:td[data-handler='selectDay'].greenday")
  322. for cell in day_cells:
  323. day = cell.ele("css:a.ui-state-default").text
  324. month = int(cell.attr("data-month")) + 1
  325. year = int(cell.attr("data-year"))
  326. available_dates.append(date(year, month, int(day)).isoformat())
  327. if available_dates:
  328. res.success = True
  329. res.availability_status = AvailabilityStatus.Available
  330. earliest_date = available_dates[0]
  331. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  332. res.earliest_date = earliest_dt
  333. res.availability = [
  334. DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
  335. for d in available_dates
  336. ]
  337. self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
  338. else:
  339. res.success = False
  340. res.availability_status = AvailabilityStatus.NoneAvailable
  341. self._log("No slots available.")
  342. return res
  343. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  344. """进行预约操作"""
  345. res = VSBookResult()
  346. res.success = False
  347. exp_start = user_inputs.get('expected_start_date', '')
  348. exp_end = user_inputs.get('expected_end_date', '')
  349. available_dates_str =[
  350. da.date.strftime("%Y-%m-%d")
  351. for da in slot_info.availability if da.date
  352. ]
  353. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  354. if not valid_dates_list:
  355. raise NotFoundError(message="No dates match user constraints")
  356. selected_date = random.choice(valid_dates_list)
  357. book_date_obj = datetime.strptime(selected_date, "%Y-%m-%d").date()
  358. day_to_click = str(book_date_obj.day)
  359. month_to_click = str(book_date_obj.month - 1)
  360. year_to_click = str(book_date_obj.year)
  361. target_cell_xpath = f"xpath://td[@data-year='{year_to_click}' and @data-month='{month_to_click}']//a[text()='{day_to_click}']"
  362. # 1. 点击目标日期
  363. self._log(f"Clicking date {selected_date}...")
  364. self.page.ele(target_cell_xpath, timeout=30).click(by_js=True)
  365. # 2. 等待并选择时间
  366. self._log("Selecting earliest available time...")
  367. first_time_radio = self.page.ele("css:#time_select input[name='schedule-entries']", timeout=30)
  368. booked_time = first_time_radio.parent().text.strip()
  369. first_time_radio.click()
  370. # 3. 提交
  371. self._log("Submitting booking...")
  372. submit_button = self.page.ele("#submitbtn", timeout=30)
  373. submit_button.click()
  374. self._log("Booking submitted successfully!")
  375. # 构造返回结果
  376. res = VSBookResult()
  377. res.success = True
  378. res.book_date = selected_date
  379. res.book_time = booked_time
  380. res.account = self.config.account.username
  381. return res
  382. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  383. if not start_str or not end_str:
  384. return dates
  385. valid_dates = []
  386. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  387. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  388. for date_str in dates:
  389. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  390. if s_date <= curr_date <= e_date:
  391. valid_dates.append(date_str)
  392. random.shuffle(valid_dates)
  393. return valid_dates
  394. # --- 资源清理核心方法 ---
  395. def cleanup(self):
  396. """
  397. 销毁浏览器并彻底删除临时文件
  398. """
  399. if self.page:
  400. try:
  401. self.page.quit(force=True)
  402. except Exception:
  403. pass
  404. self.page = None
  405. if os.path.exists(self.root_workspace):
  406. for _ in range(3):
  407. try:
  408. time.sleep(0.2)
  409. shutil.rmtree(self.root_workspace, ignore_errors=True)
  410. break
  411. except Exception as e:
  412. self._log(f"Cleanup retry: {e}")
  413. time.sleep(0.5)
  414. if os.path.exists(self.root_workspace):
  415. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  416. if self.tunnel:
  417. try: self.tunnel.stop()
  418. except: pass
  419. self.tunnel = None
  420. def __del__(self):
  421. """
  422. 析构函数:当对象被垃圾回收时自动调用
  423. """
  424. self.cleanup()