usa_plugin.py 31 KB

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