|
@@ -51,7 +51,8 @@ class UsaLoginFlow(BaseFlow):
|
|
|
max_stuck_cycles=30
|
|
max_stuck_cycles=30
|
|
|
)
|
|
)
|
|
|
self.plugin = plugin
|
|
self.plugin = plugin
|
|
|
- self.has_submitted_login = False
|
|
|
|
|
|
|
+ self.login_submit_attempts = 0
|
|
|
|
|
+ self.last_login_submit_time = 0.0
|
|
|
|
|
|
|
|
# --- 异常守卫与自愈 (Priority 5~7) ---
|
|
# --- 异常守卫与自愈 (Priority 5~7) ---
|
|
|
@guard(text="502 Bad Gateway", priority=5)
|
|
@guard(text="502 Bad Gateway", priority=5)
|
|
@@ -100,9 +101,31 @@ class UsaLoginFlow(BaseFlow):
|
|
|
# --- 状态流转与表单处理 (Priority 35~50) ---
|
|
# --- 状态流转与表单处理 (Priority 35~50) ---
|
|
|
@on(ele="#signInName", priority=50)
|
|
@on(ele="#signInName", priority=50)
|
|
|
def handle_login_form(self):
|
|
def handle_login_form(self):
|
|
|
- if self.has_submitted_login:
|
|
|
|
|
|
|
+ # 1. 冷却保护:若距离上次提交不足 15 秒,避免高频点击,静候跳转
|
|
|
|
|
+ if time.time() - self.last_login_submit_time < 15.0:
|
|
|
|
|
+ self.log("Login form recently submitted, waiting for redirect...")
|
|
|
|
|
+ time.sleep(2)
|
|
|
return
|
|
return
|
|
|
- self.log("[State] Login page detected. Submitting credentials...")
|
|
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 检查是否有页面报错(如凭证无效、被锁等)
|
|
|
|
|
+ err_ele = (
|
|
|
|
|
+ self.page.ele('.pageLevel', timeout=0.2)
|
|
|
|
|
+ or self.page.ele('.claimVerificationServerError', timeout=0.2)
|
|
|
|
|
+ or self.page.ele('.error:not([aria-hidden="true"])', timeout=0.2)
|
|
|
|
|
+ )
|
|
|
|
|
+ if err_ele and err_ele.text:
|
|
|
|
|
+ err_msg = err_ele.text.strip().replace('\n', ' ')
|
|
|
|
|
+ self.log(f"[WARN] 登录页面提示错误: '{err_msg}'", level="warning")
|
|
|
|
|
+ if any(k in err_msg.lower() for k in ["invalid", "无效", "locked", "锁定"]):
|
|
|
|
|
+ if self.login_submit_attempts >= 2:
|
|
|
|
|
+ raise BizLogicError(f"美签登录凭据无效或账号被锁定: {err_msg}")
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 最大重试上限防护
|
|
|
|
|
+ if self.login_submit_attempts >= 5:
|
|
|
|
|
+ raise BizLogicError("登录失败:已重试 5 次登录仍停留在登录页面,请检查账号密码或代理网络。")
|
|
|
|
|
+
|
|
|
|
|
+ self.login_submit_attempts += 1
|
|
|
|
|
+ self.log(f"[State] Login page detected. Submitting credentials (attempt {self.login_submit_attempts}/5)...")
|
|
|
username = self.plugin.config.account.username
|
|
username = self.plugin.config.account.username
|
|
|
password = self.plugin.config.account.password
|
|
password = self.plugin.config.account.password
|
|
|
|
|
|
|
@@ -110,20 +133,21 @@ class UsaLoginFlow(BaseFlow):
|
|
|
self.plugin.mouse.human_click_ele(username_input)
|
|
self.plugin.mouse.human_click_ele(username_input)
|
|
|
username_input.clear()
|
|
username_input.clear()
|
|
|
self.plugin.keyboard.type_text(username, humanize=True)
|
|
self.plugin.keyboard.type_text(username, humanize=True)
|
|
|
- self.plugin._random_sleep(3, 5)
|
|
|
|
|
|
|
+ self.plugin._random_sleep(2, 4)
|
|
|
|
|
|
|
|
password_input = self.page.ele('#password')
|
|
password_input = self.page.ele('#password')
|
|
|
self.plugin.mouse.human_click_ele(password_input)
|
|
self.plugin.mouse.human_click_ele(password_input)
|
|
|
password_input.clear()
|
|
password_input.clear()
|
|
|
self.plugin.keyboard.type_text(password, humanize=True)
|
|
self.plugin.keyboard.type_text(password, humanize=True)
|
|
|
- self.plugin._random_sleep(3, 5)
|
|
|
|
|
|
|
+ self.plugin._random_sleep(2, 4)
|
|
|
|
|
|
|
|
continue_btn = self.page.ele('#continue')
|
|
continue_btn = self.page.ele('#continue')
|
|
|
if continue_btn:
|
|
if continue_btn:
|
|
|
self.plugin.mouse.human_click_ele(continue_btn)
|
|
self.plugin.mouse.human_click_ele(continue_btn)
|
|
|
- self.has_submitted_login = True
|
|
|
|
|
|
|
+
|
|
|
|
|
+ self.last_login_submit_time = time.time()
|
|
|
self.log("Login form submitted. Waiting for the next step to load...")
|
|
self.log("Login form submitted. Waiting for the next step to load...")
|
|
|
- self.plugin._random_sleep(30, 40)
|
|
|
|
|
|
|
+ self.plugin._random_sleep(10, 15)
|
|
|
|
|
|
|
|
def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]:
|
|
def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]:
|
|
|
if not security:
|
|
if not security:
|
|
@@ -189,27 +213,11 @@ class UsaLoginFlow(BaseFlow):
|
|
|
self.log("Security answers submitted. Waiting for redirection...")
|
|
self.log("Security answers submitted. Waiting for redirection...")
|
|
|
self.plugin._random_sleep(30, 40)
|
|
self.plugin._random_sleep(30, 40)
|
|
|
|
|
|
|
|
- @on(ele="#continue_application", priority=30)
|
|
|
|
|
- def handle_continue_application(self):
|
|
|
|
|
- self.log("Found '#continue_application' (安排预约), clicking to proceed...")
|
|
|
|
|
- schedule_btn = self.page.ele('#continue_application')
|
|
|
|
|
- if schedule_btn:
|
|
|
|
|
- self.plugin.mouse.human_click_ele(schedule_btn)
|
|
|
|
|
- self.plugin._random_sleep(15, 25)
|
|
|
|
|
-
|
|
|
|
|
@on(ele="#atlas-sidebar", priority=35)
|
|
@on(ele="#atlas-sidebar", priority=35)
|
|
|
def handle_dashboard_sidebar(self):
|
|
def handle_dashboard_sidebar(self):
|
|
|
self.log("[State] At the main booking dashboard. Looking for navigation button...")
|
|
self.log("[State] At the main booking dashboard. Looking for navigation button...")
|
|
|
|
|
|
|
|
- # 1. 优先检查继续/安排预约按钮 (#continue_application)
|
|
|
|
|
- continue_btn = self.page.ele('#continue_application', timeout=0.5)
|
|
|
|
|
- if continue_btn:
|
|
|
|
|
- self.log("Found '#continue_application' (安排预约), clicking to proceed...")
|
|
|
|
|
- self.plugin.mouse.human_click_ele(continue_btn)
|
|
|
|
|
- self.plugin._random_sleep(15, 25)
|
|
|
|
|
- return
|
|
|
|
|
-
|
|
|
|
|
- # 2. 检查重新安排预约按钮 (#reschedule_appointment)
|
|
|
|
|
|
|
+ # 1. 优先检查重新安排预约按钮 (#reschedule_appointment,针对已有预约账号的改约)
|
|
|
reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
|
|
reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
|
|
|
if reschedule_btn:
|
|
if reschedule_btn:
|
|
|
self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...")
|
|
self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...")
|
|
@@ -217,7 +225,7 @@ class UsaLoginFlow(BaseFlow):
|
|
|
self.plugin._random_sleep(15, 25)
|
|
self.plugin._random_sleep(15, 25)
|
|
|
return
|
|
return
|
|
|
|
|
|
|
|
- # 3. 检查首次预约按钮 (#schedule_appointment)
|
|
|
|
|
|
|
+ # 2. 检查首次预约按钮 (#schedule_appointment)
|
|
|
schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5)
|
|
schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5)
|
|
|
if schedule_btn:
|
|
if schedule_btn:
|
|
|
self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...")
|
|
self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...")
|
|
@@ -225,7 +233,7 @@ class UsaLoginFlow(BaseFlow):
|
|
|
self.plugin._random_sleep(15, 25)
|
|
self.plugin._random_sleep(15, 25)
|
|
|
return
|
|
return
|
|
|
|
|
|
|
|
- # 4. 检查动态注入的 admin_link 安排预约
|
|
|
|
|
|
|
+ # 3. 检查动态注入的 admin_link 安排预约
|
|
|
admin_link = self.page.ele('#admin_link', timeout=0.5)
|
|
admin_link = self.page.ele('#admin_link', timeout=0.5)
|
|
|
if admin_link:
|
|
if admin_link:
|
|
|
self.log("Found '#admin_link' (安排预约), clicking to proceed...")
|
|
self.log("Found '#admin_link' (安排预约), clicking to proceed...")
|
|
@@ -233,10 +241,10 @@ class UsaLoginFlow(BaseFlow):
|
|
|
self.plugin._random_sleep(15, 25)
|
|
self.plugin._random_sleep(15, 25)
|
|
|
return
|
|
return
|
|
|
|
|
|
|
|
- # 5. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本为 '安排预约' 的链接
|
|
|
|
|
|
|
+ # 4. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本匹配预约/改约的链接
|
|
|
fallback_link = (
|
|
fallback_link = (
|
|
|
self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5)
|
|
self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5)
|
|
|
- or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "Schedule")]', timeout=0.5)
|
|
|
|
|
|
|
+ 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)
|
|
|
)
|
|
)
|
|
|
if fallback_link:
|
|
if fallback_link:
|
|
|
self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...")
|
|
self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...")
|
|
@@ -321,9 +329,15 @@ class UsaPlugin(IVSPlg):
|
|
|
if self.page is None:
|
|
if self.page is None:
|
|
|
return False
|
|
return False
|
|
|
try:
|
|
try:
|
|
|
|
|
+ # 优先关闭可能阻塞页面的 alert 弹窗,防止阻断 run_js 执行
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.page.handle_alert(accept=True, timeout=0.2)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
if not self.page.run_js("return 1;"):
|
|
if not self.page.run_js("return 1;"):
|
|
|
return False
|
|
return False
|
|
|
- except:
|
|
|
|
|
|
|
+ except Exception:
|
|
|
return False
|
|
return False
|
|
|
|
|
|
|
|
if self.config.session_max_life > 0:
|
|
if self.config.session_max_life > 0:
|
|
@@ -334,6 +348,34 @@ class UsaPlugin(IVSPlg):
|
|
|
return False
|
|
return False
|
|
|
return True
|
|
return True
|
|
|
|
|
|
|
|
|
|
+ def _refresh_and_bypass_cf(self):
|
|
|
|
|
+ """
|
|
|
|
|
+ 处理长时间静置后由于 Cloudflare 凭据失效导致的拦截(如页面弹窗“服务不可用”),
|
|
|
|
|
+ 关闭弹窗并主动刷新页面,触发并穿透 Cloudflare 5 秒盾以获取新 token。
|
|
|
|
|
+ """
|
|
|
|
|
+ self._log("Refreshing page to trigger and solve Cloudflare 5s shield...")
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.page.handle_alert(accept=True, timeout=0.5)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+ self.page.refresh()
|
|
|
|
|
+ self._random_sleep(2, 4)
|
|
|
|
|
+
|
|
|
|
|
+ # 刷新后若弹出 5 秒盾挑战,使用 CloudflareBypasser 进行穿透
|
|
|
|
|
+ cf_bypasser = CloudflareBypasser(self.page, log=True, logger=self._log)
|
|
|
|
|
+ page_title = (getattr(self.page, "title", "") or "").lower()
|
|
|
|
|
+ if not cf_bypasser.is_bypassed() or any(w in page_title for w in ["just a moment", "请稍候", "attention required", "cloudflare"]):
|
|
|
|
|
+ self._log("🛡️ 检测到刷新后触发 Cloudflare 5秒盾,正在进行穿透...")
|
|
|
|
|
+ if not cf_bypasser.bypass(max_retry=8):
|
|
|
|
|
+ raise BizLogicError("Cloudflare 5秒盾穿透超时")
|
|
|
|
|
+ self._random_sleep(2, 4)
|
|
|
|
|
+ cf_bypasser.handle_waiting_room()
|
|
|
|
|
+
|
|
|
|
|
+ # 等待排期页面核心元素重新加载完成
|
|
|
|
|
+ self.page.ele("css:#gm_select label", timeout=30)
|
|
|
|
|
+ self.page.ele("css:#post_select option:not([value=''])", timeout=30)
|
|
|
|
|
+
|
|
|
def create_session(self) -> None:
|
|
def create_session(self) -> None:
|
|
|
"""创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
|
|
"""创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
|
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
self._log(f"Initializing Session (ID: {self.instance_id})...")
|
|
@@ -380,142 +422,175 @@ class UsaPlugin(IVSPlg):
|
|
|
res = VSQueryResult()
|
|
res = VSQueryResult()
|
|
|
res.success = False
|
|
res.success = False
|
|
|
|
|
|
|
|
- current_url = (getattr(self.page, "url", "") or "").lower()
|
|
|
|
|
- if "schedule" not in current_url:
|
|
|
|
|
- self._log(f"Current url '{current_url}' not on schedule page, navigating...")
|
|
|
|
|
- schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
|
|
|
|
|
- self.page.get(schedule_url)
|
|
|
|
|
- self._random_sleep(3, 5)
|
|
|
|
|
- else:
|
|
|
|
|
- self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
|
|
|
|
|
-
|
|
|
|
|
- if "just a moment" in (getattr(self.page, "title", "") or "").lower():
|
|
|
|
|
- cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
|
|
|
|
|
- if not cf_bypasser.bypass(max_retry=5):
|
|
|
|
|
- raise BizLogicError("Cloudflare bypass timeout")
|
|
|
|
|
- self._random_sleep(3, 5)
|
|
|
|
|
- cf_bypasser.handle_waiting_room()
|
|
|
|
|
-
|
|
|
|
|
- current_url = (getattr(self.page, "url", "") or "").lower()
|
|
|
|
|
- if 'auth' in current_url or 'login' in current_url:
|
|
|
|
|
- self.is_healthy = False
|
|
|
|
|
- raise SessionExpiredOrInvalidError()
|
|
|
|
|
|
|
+ location_name = (self.free_config.get('location') or "").strip()
|
|
|
|
|
|
|
|
- # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
|
|
|
|
|
- self._log("Waiting for applicant list (#gm_select) to populate...")
|
|
|
|
|
- self.page.ele("css:#gm_select label", timeout=30)
|
|
|
|
|
|
|
+ # 最多尝试 2 次:首次查询 + 若遇 alert/超时则刷新过 5 秒盾重试
|
|
|
|
|
+ for attempt in range(2):
|
|
|
|
|
+ # 1. 检查并清理可能存在的残留弹窗
|
|
|
|
|
+ try:
|
|
|
|
|
+ alert_text = self.page.handle_alert(accept=True, timeout=0.5)
|
|
|
|
|
+ if alert_text:
|
|
|
|
|
+ self._log(f"[WARN] 发现并关闭残留弹窗: '{alert_text}'")
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
|
|
|
- # 2. 等待领事馆下拉框选项加载完成(从 page1 仅空 option 异步加载到 page2 包含各领事馆 option)
|
|
|
|
|
- self._log("Waiting for consular post options to populate in #post_select...")
|
|
|
|
|
- post_select = self.page.ele('#post_select', timeout=30)
|
|
|
|
|
- if not post_select:
|
|
|
|
|
- raise BizLogicError("Element #post_select not found.")
|
|
|
|
|
|
|
+ current_url = (getattr(self.page, "url", "") or "").lower()
|
|
|
|
|
+ if "schedule" not in current_url:
|
|
|
|
|
+ self._log(f"Current url '{current_url}' not on schedule page, navigating...")
|
|
|
|
|
+ schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
|
|
|
|
|
+ self.page.get(schedule_url)
|
|
|
|
|
+ self._random_sleep(3, 5)
|
|
|
|
|
+ else:
|
|
|
|
|
+ self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
|
|
|
|
|
+
|
|
|
|
|
+ if "just a moment" in (getattr(self.page, "title", "") or "").lower():
|
|
|
|
|
+ cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
|
|
|
|
|
+ if not cf_bypasser.bypass(max_retry=5):
|
|
|
|
|
+ raise BizLogicError("Cloudflare bypass timeout")
|
|
|
|
|
+ self._random_sleep(3, 5)
|
|
|
|
|
+ cf_bypasser.handle_waiting_room()
|
|
|
|
|
+
|
|
|
|
|
+ current_url = (getattr(self.page, "url", "") or "").lower()
|
|
|
|
|
+ if 'auth' in current_url or 'login' in current_url:
|
|
|
|
|
+ self.is_healthy = False
|
|
|
|
|
+ raise SessionExpiredOrInvalidError()
|
|
|
|
|
+
|
|
|
|
|
+ # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
|
|
|
|
|
+ self._log("Waiting for applicant list (#gm_select) to populate...")
|
|
|
|
|
+ self.page.ele("css:#gm_select label", timeout=30)
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 等待领事馆下拉框选项加载完成
|
|
|
|
|
+ self._log("Waiting for consular post options to populate in #post_select...")
|
|
|
|
|
+ post_select = self.page.ele('#post_select', timeout=30)
|
|
|
|
|
+ if not post_select:
|
|
|
|
|
+ if attempt == 0:
|
|
|
|
|
+ self._log("[WARN] 未找到 #post_select,尝试刷新页面刷新 token...")
|
|
|
|
|
+ self._refresh_and_bypass_cf()
|
|
|
|
|
+ continue
|
|
|
|
|
+ raise BizLogicError("Element #post_select not found.")
|
|
|
|
|
+
|
|
|
|
|
+ # 等待至少出现一个有效选项
|
|
|
|
|
+ self.page.ele("css:#post_select option:not([value=''])", timeout=30)
|
|
|
|
|
+
|
|
|
|
|
+ # 获取所有已加载的领事馆 options
|
|
|
|
|
+ all_options = post_select.eles("tag:option")
|
|
|
|
|
+ available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
|
|
|
|
|
+ opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
|
|
|
|
|
+ self._log(f"Available consular posts: {opts_summary}")
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 匹配目标领事馆
|
|
|
|
|
+ matched_id = None
|
|
|
|
|
+
|
|
|
|
|
+ # 策略 A: 优先检查 LOCATIONS 字典
|
|
|
|
|
+ known_info = self.LOCATIONS.get(location_name.upper())
|
|
|
|
|
+ if known_info:
|
|
|
|
|
+ target_id = known_info["id"]
|
|
|
|
|
+ if any(opt.attrs.get("value") == target_id for opt in available_options):
|
|
|
|
|
+ matched_id = target_id
|
|
|
|
|
+
|
|
|
|
|
+ # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
|
|
|
|
|
+ if not matched_id:
|
|
|
|
|
+ for opt in available_options:
|
|
|
|
|
+ opt_text = (getattr(opt, "text", "") or "").upper()
|
|
|
|
|
+ if location_name.upper() in opt_text:
|
|
|
|
|
+ matched_id = opt.attrs.get("value")
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
|
|
|
|
|
+ if not matched_id and available_options:
|
|
|
|
|
+ fallback_opt = available_options[0]
|
|
|
|
|
+ matched_id = fallback_opt.attrs.get("value")
|
|
|
|
|
+ self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
|
|
|
|
|
+
|
|
|
|
|
+ if not matched_id:
|
|
|
|
|
+ raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
|
|
|
|
|
+
|
|
|
|
|
+ # 开启监听目标 API
|
|
|
|
|
+ target_api = 'get-family-consular-schedule-days'
|
|
|
|
|
+ self.page.listen.start(target_api)
|
|
|
|
|
+
|
|
|
|
|
+ # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
|
|
|
|
|
+ self._log(f"Selecting consular post ID: {matched_id}...")
|
|
|
|
|
+ post_select.select.by_value(matched_id)
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"[DEBUG] Triggering change event via JS: {e}")
|
|
|
|
|
|
|
|
- # 等待至少出现一个有效选项
|
|
|
|
|
- self.page.ele("css:#post_select option:not([value=''])", timeout=30)
|
|
|
|
|
|
|
+ # 5. 等待拦截 API 响应 (设置超时时间)
|
|
|
|
|
+ self._log("Waiting for schedule dates API response...")
|
|
|
|
|
+ packet = self.page.listen.wait(timeout=20)
|
|
|
|
|
+ self.page.listen.stop()
|
|
|
|
|
|
|
|
- # 获取所有已加载的领事馆 options
|
|
|
|
|
- all_options = post_select.eles("tag:option")
|
|
|
|
|
- available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
|
|
|
|
|
- opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
|
|
|
|
|
- self._log(f"Available consular posts: {opts_summary}")
|
|
|
|
|
|
|
+ # 检查是否有 alert 弹出(如“服务不可用”)
|
|
|
|
|
+ alert_msg = None
|
|
|
|
|
+ try:
|
|
|
|
|
+ alert_msg = self.page.handle_alert(accept=True, timeout=1.0)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
|
|
|
- # 3. 匹配目标领事馆
|
|
|
|
|
- location_name = (self.free_config.get('location') or "").strip()
|
|
|
|
|
- matched_id = None
|
|
|
|
|
-
|
|
|
|
|
- # 策略 A: 优先检查 LOCATIONS 字典
|
|
|
|
|
- known_info = self.LOCATIONS.get(location_name.upper())
|
|
|
|
|
- if known_info:
|
|
|
|
|
- target_id = known_info["id"]
|
|
|
|
|
- if any(opt.attrs.get("value") == target_id for opt in available_options):
|
|
|
|
|
- matched_id = target_id
|
|
|
|
|
-
|
|
|
|
|
- # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
|
|
|
|
|
- if not matched_id:
|
|
|
|
|
- for opt in available_options:
|
|
|
|
|
- opt_text = (getattr(opt, "text", "") or "").upper()
|
|
|
|
|
- if location_name.upper() in opt_text:
|
|
|
|
|
- matched_id = opt.attrs.get("value")
|
|
|
|
|
- break
|
|
|
|
|
-
|
|
|
|
|
- # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
|
|
|
|
|
- if not matched_id and available_options:
|
|
|
|
|
- fallback_opt = available_options[0]
|
|
|
|
|
- matched_id = fallback_opt.attrs.get("value")
|
|
|
|
|
- self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
|
|
|
|
|
-
|
|
|
|
|
- if not matched_id:
|
|
|
|
|
- raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
|
|
|
|
|
-
|
|
|
|
|
- # 开启监听目标 API
|
|
|
|
|
- target_api = 'get-family-consular-schedule-days'
|
|
|
|
|
- self.page.listen.start(target_api)
|
|
|
|
|
-
|
|
|
|
|
- # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
|
|
|
|
|
- self._log(f"Selecting consular post ID: {matched_id}...")
|
|
|
|
|
- post_select.select.by_value(matched_id)
|
|
|
|
|
- try:
|
|
|
|
|
- self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
|
|
|
|
|
- except Exception as e:
|
|
|
|
|
- self._log(f"[DEBUG] Triggering change event via JS: {e}")
|
|
|
|
|
-
|
|
|
|
|
- # 5. 等待拦截 API 响应 (设置超时时间)
|
|
|
|
|
- self._log("Waiting for schedule dates API response...")
|
|
|
|
|
- packet = self.page.listen.wait(timeout=30)
|
|
|
|
|
- self.page.listen.stop()
|
|
|
|
|
-
|
|
|
|
|
- if not packet:
|
|
|
|
|
- raise BizLogicError("Timeout waiting for schedule API response")
|
|
|
|
|
-
|
|
|
|
|
- status_code = packet.response.status
|
|
|
|
|
- body = packet.response.body
|
|
|
|
|
- if isinstance(body, bytes):
|
|
|
|
|
- body = body.decode("utf-8", errors="ignore")
|
|
|
|
|
- self._log(f"API Response Status: {status_code}")
|
|
|
|
|
-
|
|
|
|
|
- # 处理 HTTP 返回码不是200的情况
|
|
|
|
|
- if status_code != 200:
|
|
|
|
|
- err_text = str(body)[:512]
|
|
|
|
|
- if status_code == 403:
|
|
|
|
|
- raise PermissionDeniedError(f"HTTP 403: {err_text}")
|
|
|
|
|
- if status_code == 429:
|
|
|
|
|
- self.is_healthy = False
|
|
|
|
|
- raise RateLimiteddError(f"HTTP 429: {err_text}")
|
|
|
|
|
- raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
|
|
|
|
|
-
|
|
|
|
|
- # 6. 解析返回的数据
|
|
|
|
|
- available_dates = []
|
|
|
|
|
- data = body if isinstance(body, dict) else None
|
|
|
|
|
- if not data:
|
|
|
|
|
- match = re.search(r'(\{.*\})', str(body), re.DOTALL)
|
|
|
|
|
- data = json.loads(match.group(1)) if match else json.loads(str(body))
|
|
|
|
|
-
|
|
|
|
|
- schedule_days = data.get("ScheduleDays", [])
|
|
|
|
|
- if schedule_days:
|
|
|
|
|
- for day_obj in schedule_days:
|
|
|
|
|
- date_str = day_obj.get("Date")
|
|
|
|
|
- if date_str:
|
|
|
|
|
- available_dates.append(date_str)
|
|
|
|
|
-
|
|
|
|
|
- # 6. 处理最终结果
|
|
|
|
|
- if available_dates:
|
|
|
|
|
- available_dates.sort()
|
|
|
|
|
- res.success = True
|
|
|
|
|
- res.availability_status = AvailabilityStatus.Available
|
|
|
|
|
- earliest_date = available_dates[0]
|
|
|
|
|
- res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
|
|
|
|
|
- res.availability = [
|
|
|
|
|
- DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
|
|
|
|
|
- for d in available_dates
|
|
|
|
|
- ]
|
|
|
|
|
- self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
|
|
|
|
|
- else:
|
|
|
|
|
- res.success = False
|
|
|
|
|
- res.availability_status = AvailabilityStatus.NoneAvailable
|
|
|
|
|
- self._log("No slots available.")
|
|
|
|
|
-
|
|
|
|
|
- return res
|
|
|
|
|
|
|
+ if alert_msg or not packet:
|
|
|
|
|
+ if attempt == 0:
|
|
|
|
|
+ self._log(f"[WARN] 查询未成功 (alert='{alert_msg}', packet={bool(packet)}),判定为长时间未操作导致凭据失效。正在刷新页面并解决 5 秒盾...")
|
|
|
|
|
+ self._refresh_and_bypass_cf()
|
|
|
|
|
+ continue
|
|
|
|
|
+ else:
|
|
|
|
|
+ if alert_msg:
|
|
|
|
|
+ raise BizLogicError(f"页面弹出提示: {alert_msg}")
|
|
|
|
|
+ raise BizLogicError("Timeout waiting for schedule API response")
|
|
|
|
|
+
|
|
|
|
|
+ status_code = packet.response.status
|
|
|
|
|
+ body = packet.response.body
|
|
|
|
|
+ if isinstance(body, bytes):
|
|
|
|
|
+ body = body.decode("utf-8", errors="ignore")
|
|
|
|
|
+ self._log(f"API Response Status: {status_code}")
|
|
|
|
|
+
|
|
|
|
|
+ # 处理 HTTP 返回码不是200的情况
|
|
|
|
|
+ if status_code != 200:
|
|
|
|
|
+ err_text = str(body)[:512]
|
|
|
|
|
+ if status_code == 403:
|
|
|
|
|
+ if attempt == 0:
|
|
|
|
|
+ self._log(f"[WARN] HTTP 403 权限受限,尝试刷新页面过 5 秒盾...")
|
|
|
|
|
+ self._refresh_and_bypass_cf()
|
|
|
|
|
+ continue
|
|
|
|
|
+ raise PermissionDeniedError(f"HTTP 403: {err_text}")
|
|
|
|
|
+ if status_code == 429:
|
|
|
|
|
+ self.is_healthy = False
|
|
|
|
|
+ raise RateLimiteddError(f"HTTP 429: {err_text}")
|
|
|
|
|
+ raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
|
|
|
|
|
+
|
|
|
|
|
+ # 6. 解析返回的数据
|
|
|
|
|
+ available_dates = []
|
|
|
|
|
+ data = body if isinstance(body, dict) else None
|
|
|
|
|
+ if not data:
|
|
|
|
|
+ match = re.search(r'(\{.*\})', str(body), re.DOTALL)
|
|
|
|
|
+ data = json.loads(match.group(1)) if match else json.loads(str(body))
|
|
|
|
|
+
|
|
|
|
|
+ schedule_days = data.get("ScheduleDays", [])
|
|
|
|
|
+ if schedule_days:
|
|
|
|
|
+ for day_obj in schedule_days:
|
|
|
|
|
+ date_str = day_obj.get("Date")
|
|
|
|
|
+ if date_str:
|
|
|
|
|
+ available_dates.append(date_str)
|
|
|
|
|
+
|
|
|
|
|
+ # 6. 处理最终结果
|
|
|
|
|
+ if available_dates:
|
|
|
|
|
+ available_dates.sort()
|
|
|
|
|
+ res.success = True
|
|
|
|
|
+ res.availability_status = AvailabilityStatus.Available
|
|
|
|
|
+ earliest_date = available_dates[0]
|
|
|
|
|
+ res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
|
|
|
|
|
+ res.availability = [
|
|
|
|
|
+ DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
|
|
|
|
|
+ for d in available_dates
|
|
|
|
|
+ ]
|
|
|
|
|
+ self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
|
|
|
|
|
+ else:
|
|
|
|
|
+ res.success = False
|
|
|
|
|
+ res.availability_status = AvailabilityStatus.NoneAvailable
|
|
|
|
|
+ self._log("No slots available.")
|
|
|
|
|
+
|
|
|
|
|
+ return res
|
|
|
|
|
|
|
|
def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
|
|
def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
|
|
|
"""进行预约操作"""
|
|
"""进行预约操作"""
|