usa_plugin.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. from datetime import datetime
  8. from typing import List, Dict, Optional, Any, Callable
  9. from DrissionPage import ChromiumPage
  10. from vs_plg import IVSPlg
  11. from vs_types import (
  12. VSPlgConfig,
  13. AppointmentType,
  14. VSQueryResult,
  15. VSBookResult,
  16. AvailabilityStatus,
  17. DateAvailability,
  18. NotFoundError,
  19. PermissionDeniedError,
  20. RateLimiteddError,
  21. SessionExpiredOrInvalidError,
  22. BizLogicError,
  23. PluginStatus,
  24. utc_now_str
  25. )
  26. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  27. from utils.mouse import HumanMouse
  28. from utils.keyboard import HumanKeyboard
  29. from utils.flow_engine import BaseFlow, on, guard, done, fatal
  30. from utils.plugin_utils import (
  31. init_chromium_options,
  32. filter_dates_in_range,
  33. cleanup_browser_workspace,
  34. save_screenshot
  35. )
  36. class UsaLoginFlow(BaseFlow):
  37. """
  38. 基于 BaseFlow 注解状态机驱动的美签 USVisaScheduling 会话创建与自动导航流
  39. """
  40. def __init__(self, page, plugin: 'UsaPlugin', interval: float = 1.0):
  41. super().__init__(
  42. page=page,
  43. config=plugin.config,
  44. context={"plugin": plugin},
  45. interval=interval,
  46. logger=plugin._log,
  47. cf_bypasser=CloudflareBypasser(page, log=True, logger=plugin._log),
  48. max_stuck_cycles=30
  49. )
  50. self.plugin = plugin
  51. self.has_submitted_login = False
  52. # --- 异常守卫与自愈 (Priority 5~7) ---
  53. @guard(text="502 Bad Gateway", priority=5)
  54. @guard(text="503 Service Temporarily Unavailable", priority=5)
  55. def on_server_network_error(self):
  56. self.log("[WARN] 检测到服务器网络错误 (502/503),等待并刷新自愈...", level="warning")
  57. self.plugin._random_sleep(30, 40)
  58. self.page.refresh()
  59. try:
  60. self.page.wait.doc_loaded()
  61. except Exception:
  62. pass
  63. @guard(text="Sorry, you have been blocked", priority=6)
  64. @guard(text="You are being rate limited", priority=6)
  65. @guard(text="Cloudflare Ray ID", priority=6)
  66. @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  67. def on_cloudflare_blocked(self):
  68. pass
  69. @guard(title="just a moment", priority=7)
  70. @guard(title="请稍候", priority=7)
  71. @guard(title="attention required", priority=7)
  72. @guard(title="security check", priority=7)
  73. @guard(title="cloudflare", priority=7)
  74. @guard(ele="@src:challenges.cloudflare.com", priority=7)
  75. @guard(ele="#challenge-stage", priority=7)
  76. @guard(ele="#challenge-form", priority=7)
  77. @guard(predicate=lambda flow: flow.cf_bypasser and not flow.cf_bypasser.is_bypassed(), priority=7)
  78. def on_cloudflare_turnstile_challenge(self):
  79. self.log("🛡️ 检测到 Cloudflare 5秒盾/Turnstile挑战,正在尝试穿透...")
  80. if self.cf_bypasser.bypass(max_retry=8):
  81. self.log("✅ Cloudflare 挑战通过!")
  82. self.plugin._random_sleep(2, 4)
  83. self.cf_bypasser.handle_waiting_room()
  84. else:
  85. self.log("[WARN] 本周期未完全通过 Cloudflare,将在下一周期继续尝试...")
  86. @guard(title="waitting room", priority=7)
  87. @guard(title="waiting room", priority=7)
  88. def on_cloudflare_waiting_room(self):
  89. self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...")
  90. self.cf_bypasser.handle_waiting_room()
  91. time.sleep(2)
  92. # --- 状态流转与表单处理 (Priority 35~50) ---
  93. @on(ele="#signInName", priority=50)
  94. def handle_login_form(self):
  95. if self.has_submitted_login:
  96. return
  97. self.log("[State] Login page detected. Submitting credentials...")
  98. username = self.plugin.config.account.username
  99. password = self.plugin.config.account.password
  100. username_input = self.page.ele('#signInName')
  101. self.plugin.mouse.human_click_ele(username_input)
  102. username_input.clear()
  103. self.plugin.keyboard.type_text(username, humanize=True)
  104. self.plugin._random_sleep(3, 5)
  105. password_input = self.page.ele('#password')
  106. self.plugin.mouse.human_click_ele(password_input)
  107. password_input.clear()
  108. self.plugin.keyboard.type_text(password, humanize=True)
  109. self.plugin._random_sleep(3, 5)
  110. continue_btn = self.page.ele('#continue')
  111. if continue_btn:
  112. self.plugin.mouse.human_click_ele(continue_btn)
  113. self.has_submitted_login = True
  114. self.log("Login form submitted. Waiting for the next step to load...")
  115. self.plugin._random_sleep(30, 40)
  116. def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]:
  117. if not security:
  118. return None
  119. # 1. 列表格式: ["ans1", "ans2", "ans3"]
  120. if isinstance(security, list):
  121. idx = int(q_num) - 1
  122. if 0 <= idx < len(security):
  123. return str(security[idx])
  124. return None
  125. # 2. 字典格式
  126. if isinstance(security, dict):
  127. # 极简键格式: {"1": "ans1", "2": "ans2"} 或 {1: "ans1", 2: "ans2"}
  128. if q_num in security:
  129. val = security[q_num]
  130. return str(val.get('a', '')) if isinstance(val, dict) else str(val)
  131. if q_num.isdigit() and int(q_num) in security:
  132. val = security[int(q_num)]
  133. return str(val.get('a', '')) if isinstance(val, dict) else str(val)
  134. # 旧版嵌套键格式: {"1_quest": {"a": "ans1"}} 或 {"1_quest": "ans1"}
  135. config_key = f"{q_num}_quest"
  136. if config_key in security:
  137. val = security[config_key]
  138. return str(val.get('a', '')) if isinstance(val, dict) else str(val)
  139. return None
  140. @on(ele="xpath://input[starts-with(@id, 'kba') and contains(@id, '_response')]", priority=45)
  141. def handle_kba_security_questions(self):
  142. self.log("[State] Security question verification detected. Filling in answers...")
  143. security = self.plugin.free_config.get('security')
  144. answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
  145. if not security:
  146. save_screenshot(self.page, self.plugin.instance_id, "kba_security_missing", logger=self.log)
  147. err_msg = "美签登录触发了 KBA 密保问题验证,但在 free_config 中未配置 'security' 答案,无法继续登录。"
  148. self.log(f"[ERROR] {err_msg}", level="error")
  149. raise BizLogicError(err_msg)
  150. for ans_ele in answer_eles:
  151. ele_id = ans_ele.attr('id')
  152. match = re.search(r'kba(\d+)_response', ele_id)
  153. if match:
  154. q_num = match.group(1)
  155. ans_text = self._extract_security_answer(security, q_num)
  156. if ans_text is None:
  157. save_screenshot(self.page, self.plugin.instance_id, f"kba_q{q_num}_missing", logger=self.log)
  158. err_msg = f"美签登录触发了第 {q_num} 道密保问题,但配置中未提供对应答案(当前配置: {security})。"
  159. self.log(f"[ERROR] {err_msg}", level="error")
  160. raise BizLogicError(err_msg)
  161. self.plugin.mouse.human_click_ele(ans_ele)
  162. ans_ele.clear()
  163. self.plugin.keyboard.type_text(ans_text, humanize=True)
  164. self.log(f"-> Found input {ele_id}, successfully filled in answer for question {q_num}.")
  165. continue_btn = self.page.ele('#continue')
  166. if continue_btn:
  167. self.plugin.mouse.human_click_ele(continue_btn)
  168. self.log("Security answers submitted. Waiting for redirection...")
  169. self.plugin._random_sleep(30, 40)
  170. @on(ele="#continue_application", priority=30)
  171. def handle_continue_application(self):
  172. self.log("Found '#continue_application' (安排预约), clicking to proceed...")
  173. schedule_btn = self.page.ele('#continue_application')
  174. if schedule_btn:
  175. self.plugin.mouse.human_click_ele(schedule_btn)
  176. self.plugin._random_sleep(15, 25)
  177. @on(ele="#atlas-sidebar", priority=35)
  178. def handle_dashboard_sidebar(self):
  179. self.log("[State] At the main booking dashboard. Looking for navigation button...")
  180. # 1. 优先检查继续/安排预约按钮 (#continue_application)
  181. continue_btn = self.page.ele('#continue_application', timeout=0.5)
  182. if continue_btn:
  183. self.log("Found '#continue_application' (安排预约), clicking to proceed...")
  184. self.plugin.mouse.human_click_ele(continue_btn)
  185. self.plugin._random_sleep(15, 25)
  186. return
  187. # 2. 检查重新安排预约按钮 (#reschedule_appointment)
  188. reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
  189. if reschedule_btn:
  190. self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...")
  191. self.plugin.mouse.human_click_ele(reschedule_btn)
  192. self.plugin._random_sleep(15, 25)
  193. return
  194. # 3. 检查首次预约按钮 (#schedule_appointment)
  195. schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5)
  196. if schedule_btn:
  197. self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...")
  198. self.plugin.mouse.human_click_ele(schedule_btn)
  199. self.plugin._random_sleep(15, 25)
  200. return
  201. # 4. 检查动态注入的 admin_link 安排预约
  202. admin_link = self.page.ele('#admin_link', timeout=0.5)
  203. if admin_link:
  204. self.log("Found '#admin_link' (安排预约), clicking to proceed...")
  205. self.plugin.mouse.human_click_ele(admin_link)
  206. self.plugin._random_sleep(15, 25)
  207. return
  208. # 5. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本为 '安排预约' 的链接
  209. fallback_link = (
  210. self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5)
  211. or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "Schedule")]', timeout=0.5)
  212. )
  213. if fallback_link:
  214. self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...")
  215. self.plugin.mouse.human_click_ele(fallback_link)
  216. self.plugin._random_sleep(15, 25)
  217. return
  218. self.log("Not found schedule or reschedule button. The page may still be loading...")
  219. time.sleep(2)
  220. # --- 成功终态到达 (Priority 10) ---
  221. @on(ele="#post_select", priority=10)
  222. @done
  223. def on_reached_slot_search_page(self):
  224. self.plugin.session_create_time = time.time()
  225. self.log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")
  226. class UsaPlugin(IVSPlg):
  227. name = "usa_plugin"
  228. version = "1.0.0"
  229. description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)"
  230. LOCATIONS = {
  231. "BEIJING": {"name": "BEIJING", "id": "106bf614-b0db-ec11-a7b4-001dd80234f6"},
  232. "GUANGZHOU": {"name": "GUANGZHOU", "id": "a26af614-b0db-ec11-a7b4-001dd80234f6"},
  233. "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
  234. "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
  235. "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
  236. }
  237. def __init__(self, group_id: str):
  238. self.group_id = group_id
  239. self.config: Optional[VSPlgConfig] = None
  240. self.free_config: Dict[str, Any] = {}
  241. self.is_healthy = True
  242. self.logger = None
  243. self.mouse = None
  244. self.keyboard = None
  245. self.page: Optional[ChromiumPage] = None
  246. self.instance_id = uuid.uuid4().hex[:8]
  247. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  248. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  249. if not os.path.exists(self.root_workspace):
  250. os.makedirs(self.root_workspace)
  251. self.tunnel = None
  252. self.session_create_time: float = 0
  253. def _log(self, message):
  254. if self.logger:
  255. self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  256. else:
  257. print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  258. def _random_sleep(self, min_sec=30, max_sec=60):
  259. """
  260. 核心防限速控制:模拟人类阅读和操作的长时间停顿,确保网络请求间隔在30-60秒
  261. """
  262. sleep_time = random.uniform(min_sec, max_sec)
  263. self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
  264. time.sleep(sleep_time)
  265. def set_config(self, config: VSPlgConfig):
  266. """设置 API 的配置信息"""
  267. self.config = config
  268. self.free_config = config.free_config or {}
  269. def set_log(self, logger: Callable[[str], None]) -> None:
  270. """设置日志输出工具"""
  271. self.logger = logger
  272. def keep_alive(self):
  273. pass
  274. def health_check(self) -> bool:
  275. if not self.is_healthy:
  276. return False
  277. if self.page is None:
  278. return False
  279. try:
  280. if not self.page.run_js("return 1;"):
  281. return False
  282. except:
  283. return False
  284. if self.config.session_max_life > 0:
  285. current_time = time.time()
  286. elapsed_time = current_time - self.session_create_time
  287. if elapsed_time > self.config.session_max_life:
  288. self._log("Session expired.")
  289. return False
  290. return True
  291. def create_session(self) -> None:
  292. """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
  293. self._log(f"Initializing Session (ID: {self.instance_id})...")
  294. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}")
  295. co, self.tunnel = init_chromium_options(
  296. user_data_path=self.user_data_path,
  297. username_seed=self.config.account.username if self.config and self.config.account else None,
  298. proxy=self.config.proxy if self.config else None,
  299. headless=False,
  300. window_size="1920,1080",
  301. logger=self._log
  302. )
  303. self.page = ChromiumPage(co)
  304. self._log("Init humanize tools...")
  305. self.mouse = HumanMouse(self.page, debug=False)
  306. self.keyboard = HumanKeyboard(self.page)
  307. viewport_width = self.page.rect.viewport_size[0]
  308. viewport_height = self.page.rect.viewport_size[1]
  309. init_x = random.randint(10, viewport_width - 10)
  310. init_y = random.randint(10, viewport_height - 10)
  311. self.mouse.move(init_x, init_y)
  312. usa_url = self.free_config.get('usa_url', '')
  313. if usa_url:
  314. self._log(f"Navigating: {usa_url}")
  315. self.page.get(usa_url)
  316. # 启动 UsaLoginFlow 注解流状态机
  317. login_flow = UsaLoginFlow(
  318. self.page,
  319. plugin=self,
  320. interval=1.0
  321. )
  322. login_flow.run(max_steps=100, timeout=600.0)
  323. self.session_create_time = time.time()
  324. self._log("🎉 UsaLoginFlow completed successfully. Session created.")
  325. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  326. """查询可用的签证预约信息"""
  327. self._log("Querying available slots...")
  328. res = VSQueryResult()
  329. res.success = False
  330. current_url = (getattr(self.page, "url", "") or "").lower()
  331. if "schedule" not in current_url:
  332. self._log(f"Current url '{current_url}' not on schedule page, navigating...")
  333. schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
  334. self.page.get(schedule_url)
  335. self._random_sleep(3, 5)
  336. else:
  337. self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
  338. if "just a moment" in (getattr(self.page, "title", "") or "").lower():
  339. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
  340. if not cf_bypasser.bypass(max_retry=5):
  341. raise BizLogicError("Cloudflare bypass timeout")
  342. self._random_sleep(3, 5)
  343. cf_bypasser.handle_waiting_room()
  344. current_url = (getattr(self.page, "url", "") or "").lower()
  345. if 'auth' in current_url or 'login' in current_url:
  346. self.is_healthy = False
  347. raise SessionExpiredOrInvalidError()
  348. # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
  349. self._log("Waiting for applicant list (#gm_select) to populate...")
  350. self.page.ele("css:#gm_select label", timeout=30)
  351. # 2. 等待领事馆下拉框选项加载完成(从 page1 仅空 option 异步加载到 page2 包含各领事馆 option)
  352. self._log("Waiting for consular post options to populate in #post_select...")
  353. post_select = self.page.ele('#post_select', timeout=30)
  354. if not post_select:
  355. raise BizLogicError("Element #post_select not found.")
  356. # 等待至少出现一个有效选项
  357. self.page.ele("css:#post_select option:not([value=''])", timeout=30)
  358. # 获取所有已加载的领事馆 options
  359. all_options = post_select.eles("tag:option")
  360. available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
  361. opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
  362. self._log(f"Available consular posts: {opts_summary}")
  363. # 3. 匹配目标领事馆
  364. location_name = (self.free_config.get('location') or "").strip()
  365. matched_id = None
  366. # 策略 A: 优先检查 LOCATIONS 字典
  367. known_info = self.LOCATIONS.get(location_name.upper())
  368. if known_info:
  369. target_id = known_info["id"]
  370. if any(opt.attrs.get("value") == target_id for opt in available_options):
  371. matched_id = target_id
  372. # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
  373. if not matched_id:
  374. for opt in available_options:
  375. opt_text = (getattr(opt, "text", "") or "").upper()
  376. if location_name.upper() in opt_text:
  377. matched_id = opt.attrs.get("value")
  378. break
  379. # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
  380. if not matched_id and available_options:
  381. fallback_opt = available_options[0]
  382. matched_id = fallback_opt.attrs.get("value")
  383. self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
  384. if not matched_id:
  385. raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
  386. # 开启监听目标 API
  387. target_api = 'get-family-consular-schedule-days'
  388. self.page.listen.start(target_api)
  389. # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
  390. self._log(f"Selecting consular post ID: {matched_id}...")
  391. post_select.select.by_value(matched_id)
  392. try:
  393. self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
  394. except Exception as e:
  395. self._log(f"[DEBUG] Triggering change event via JS: {e}")
  396. # 5. 等待拦截 API 响应 (设置超时时间)
  397. self._log("Waiting for schedule dates API response...")
  398. packet = self.page.listen.wait(timeout=30)
  399. self.page.listen.stop()
  400. if not packet:
  401. raise BizLogicError("Timeout waiting for schedule API response")
  402. status_code = packet.response.status
  403. body = packet.response.body
  404. if isinstance(body, bytes):
  405. body = body.decode("utf-8", errors="ignore")
  406. self._log(f"API Response Status: {status_code}")
  407. # 处理 HTTP 返回码不是200的情况
  408. if status_code != 200:
  409. err_text = str(body)[:512]
  410. if status_code == 403:
  411. raise PermissionDeniedError(f"HTTP 403: {err_text}")
  412. if status_code == 429:
  413. self.is_healthy = False
  414. raise RateLimiteddError(f"HTTP 429: {err_text}")
  415. raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
  416. # 6. 解析返回的数据
  417. available_dates = []
  418. data = body if isinstance(body, dict) else None
  419. if not data:
  420. match = re.search(r'(\{.*\})', str(body), re.DOTALL)
  421. data = json.loads(match.group(1)) if match else json.loads(str(body))
  422. schedule_days = data.get("ScheduleDays", [])
  423. if schedule_days:
  424. for day_obj in schedule_days:
  425. date_str = day_obj.get("Date")
  426. if date_str:
  427. available_dates.append(date_str)
  428. # 6. 处理最终结果
  429. if available_dates:
  430. available_dates.sort()
  431. res.success = True
  432. res.availability_status = AvailabilityStatus.Available
  433. earliest_date = available_dates[0]
  434. res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
  435. res.availability = [
  436. DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
  437. for d in available_dates
  438. ]
  439. self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
  440. else:
  441. res.success = False
  442. res.availability_status = AvailabilityStatus.NoneAvailable
  443. self._log("No slots available.")
  444. return res
  445. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  446. """进行预约操作"""
  447. res = VSBookResult()
  448. res.success = False
  449. exp_start = user_inputs.get('expected_date_start', '')
  450. exp_end = user_inputs.get('expected_date_end', '')
  451. available_dates_str = [
  452. da.date.strftime("%Y-%m-%d")
  453. for da in slot_info.availability if da.date
  454. ]
  455. valid_dates_list = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True)
  456. if not valid_dates_list:
  457. raise NotFoundError(message="No dates match user constraints")
  458. selected_slot_date = random.choice(valid_dates_list)
  459. book_date_obj = datetime.strptime(selected_slot_date, "%Y-%m-%d").date()
  460. # jQuery UI Datepicker 月份是 0-11
  461. target_day = str(book_date_obj.day)
  462. target_month = str(book_date_obj.month - 1)
  463. target_year = str(book_date_obj.year)
  464. self._log(f"Target booking date: {selected_slot_date}. Navigating calendar...")
  465. # 1. 适配不在当前日历的情况:通过下拉框选择年份和月份
  466. year_select = self.page.ele('.ui-datepicker-year', timeout=10) # 查找年份下拉框
  467. if year_select and year_select.value != target_year:
  468. self._log(f"Changing year to {target_year}")
  469. year_select.select.by_value(target_year)
  470. self._random_sleep(0.5, 1)
  471. month_select = self.page.ele('.ui-datepicker-month', timeout=10) # 查找月份下拉框
  472. if month_select and month_select.value != target_month:
  473. self._log(f"Changing month to {target_month}")
  474. month_select.select.by_value(target_month)
  475. self._random_sleep(0.5, 1)
  476. # 2. 点击目标日期
  477. self._log(f"Clicking date {selected_slot_date}...")
  478. target_cell_selector = f"xpath://td[@data-year='{target_year}' and @data-month='{target_month}']//a[text()='{target_day}']"
  479. target_date_cell = self.page.ele(target_cell_selector, timeout=10)
  480. if not target_date_cell:
  481. raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.")
  482. self.mouse.human_click_ele(target_date_cell)
  483. self._log("Waiting for available times to load...")
  484. self._random_sleep(3, 5)
  485. # 3. 等待并选择时间
  486. self._log("Selecting earliest available time...")
  487. slot_time_selector = "css:#time_select input[name='schedule-entries']"
  488. first_time_radio = self.page.ele(slot_time_selector, timeout=15)
  489. if not first_time_radio:
  490. raise BizLogicError("Failed to load time slots after clicking date. Might be rate limited or slots gone.")
  491. selected_slot_time = first_time_radio.parent().text.strip()
  492. self.mouse.human_click_ele(first_time_radio)
  493. # 4. 点击提交
  494. self._random_sleep(1, 2)
  495. self._log("Submitting booking...")
  496. submit_appointment_selector = "#submitbtn"
  497. submit_button = self.page.ele(submit_appointment_selector, timeout=10)
  498. self.mouse.human_click_ele(submit_button)
  499. self._log("Booking submitted successfully!")
  500. # 构造返回结果
  501. res = VSBookResult()
  502. res.success = True
  503. res.book_date = selected_slot_date
  504. res.book_time = selected_slot_time
  505. res.account = self.config.account.username
  506. return res
  507. def cleanup(self):
  508. """销毁浏览器并彻底删除临时文件"""
  509. if getattr(self, "keep_browser_on_error", False):
  510. self._log("[DEBUG] keep_browser_on_error 生效,跳过浏览器清理并保留窗口供分析。")
  511. return
  512. cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
  513. self.page = None
  514. self.tunnel = None
  515. def get_plugin_status(self) -> PluginStatus:
  516. account_name = self.config.account.username if self.config and self.config.account else ""
  517. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  518. current_url = ""
  519. if self.page:
  520. try:
  521. current_url = self.page.url
  522. except Exception:
  523. pass
  524. session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
  525. state = "running" if self.is_healthy else "unhealthy"
  526. return PluginStatus(
  527. instance_id=self.instance_id,
  528. is_healthy=self.is_healthy,
  529. state=state,
  530. current_url=current_url,
  531. account=account_name,
  532. proxy=proxy_info,
  533. session_age_sec=session_age,
  534. last_active_at=utc_now_str(),
  535. )
  536. def __del__(self):
  537. """
  538. 析构函数:当对象被垃圾回收时自动调用
  539. """
  540. self.cleanup()