|
@@ -75,15 +75,9 @@ class UsaLoginFlow(BaseFlow):
|
|
|
|
|
|
|
|
@guard(title="just a moment", priority=7)
|
|
@guard(title="just a moment", priority=7)
|
|
|
@guard(title="请稍候", priority=7)
|
|
@guard(title="请稍候", priority=7)
|
|
|
- @guard(title="attention required", priority=7)
|
|
|
|
|
- @guard(title="security check", priority=7)
|
|
|
|
|
- @guard(title="cloudflare", priority=7)
|
|
|
|
|
- @guard(ele="@src:challenges.cloudflare.com", priority=7)
|
|
|
|
|
- @guard(ele="#challenge-stage", priority=7)
|
|
|
|
|
- @guard(ele="#challenge-form", priority=7)
|
|
|
|
|
@guard(predicate=lambda flow: flow.cf_bypasser and not flow.cf_bypasser.is_bypassed(), priority=7)
|
|
@guard(predicate=lambda flow: flow.cf_bypasser and not flow.cf_bypasser.is_bypassed(), priority=7)
|
|
|
- def on_cloudflare_turnstile_challenge(self):
|
|
|
|
|
- self.log("🛡️ 检测到 Cloudflare 5秒盾/Turnstile挑战,正在尝试穿透...")
|
|
|
|
|
|
|
+ def on_cloudflare_5s_challenge(self):
|
|
|
|
|
+ self.log("🛡️ 检测到 Cloudflare 5秒盾,正在尝试穿透...")
|
|
|
if self.cf_bypasser.bypass(max_retry=8):
|
|
if self.cf_bypasser.bypass(max_retry=8):
|
|
|
self.log("✅ Cloudflare 挑战通过!")
|
|
self.log("✅ Cloudflare 挑战通过!")
|
|
|
self.plugin._random_sleep(2, 4)
|
|
self.plugin._random_sleep(2, 4)
|
|
@@ -331,22 +325,7 @@ class UsaPlugin(IVSPlg):
|
|
|
return
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
try:
|
|
|
- # 1. 快速检查并关闭可能阻塞页面的 alert 弹窗
|
|
|
|
|
- try:
|
|
|
|
|
- self.page.handle_alert(accept=True, timeout=0.1)
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
-
|
|
|
|
|
- # 2. 检查是否有静默弹出的 Cloudflare 盾,若有则提前穿透
|
|
|
|
|
- page_title = (getattr(self.page, "title", "") or "").lower()
|
|
|
|
|
- if any(w in page_title for w in ["just a moment", "请稍候", "attention required", "cloudflare"]):
|
|
|
|
|
- cf_bypasser = CloudflareBypasser(self.page, log=False, logger=self._log)
|
|
|
|
|
- if not cf_bypasser.is_bypassed():
|
|
|
|
|
- self._log("🛡️ [KeepAlive] 检测到 Cloudflare 挑战,提前穿透...")
|
|
|
|
|
- cf_bypasser.bypass(max_retry=4)
|
|
|
|
|
- return
|
|
|
|
|
-
|
|
|
|
|
- # 3. 在浏览器页面上下文内发起轻量 fetch 请求 (/favicon.ico)
|
|
|
|
|
|
|
+ # 在浏览器页面上下文内发起轻量 fetch 请求 (/favicon.ico)
|
|
|
js_code = """
|
|
js_code = """
|
|
|
return fetch('/favicon.ico?_t=' + Date.now(), {
|
|
return fetch('/favicon.ico?_t=' + Date.now(), {
|
|
|
method: 'GET',
|
|
method: 'GET',
|
|
@@ -357,20 +336,10 @@ class UsaPlugin(IVSPlg):
|
|
|
"""
|
|
"""
|
|
|
result = self.page.run_js(js_code)
|
|
result = self.page.run_js(js_code)
|
|
|
status = result.get("status", 0) if isinstance(result, dict) else 0
|
|
status = result.get("status", 0) if isinstance(result, dict) else 0
|
|
|
-
|
|
|
|
|
- if status in (200, 304):
|
|
|
|
|
- if self.config and self.config.debug:
|
|
|
|
|
- self._log(f"🟢 [KeepAlive] Ping ok (Status: {status})")
|
|
|
|
|
- elif status == 403:
|
|
|
|
|
- self._log("⚠️ [KeepAlive] 收到 403,可能凭据失效,尝试刷新页面过盾...")
|
|
|
|
|
- self._refresh_and_bypass_cf()
|
|
|
|
|
- elif status != 0:
|
|
|
|
|
- self._log(f"🟡 [KeepAlive] Ping 响应状态: {status}")
|
|
|
|
|
-
|
|
|
|
|
|
|
+ self._log(f"🟡 [KeepAlive] Ping 响应状态: {status}")
|
|
|
|
|
+
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
- if self.config and self.config.debug:
|
|
|
|
|
- self._log(f"⚠️ [KeepAlive] 保活调用异常: {e}")
|
|
|
|
|
-
|
|
|
|
|
|
|
+ self._log(f"⚠️ [KeepAlive] 保活调用异常: {e}")
|
|
|
|
|
|
|
|
def health_check(self) -> bool:
|
|
def health_check(self) -> bool:
|
|
|
if not self.is_healthy:
|
|
if not self.is_healthy:
|
|
@@ -378,12 +347,6 @@ 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 Exception:
|
|
except Exception:
|
|
@@ -397,33 +360,51 @@ class UsaPlugin(IVSPlg):
|
|
|
return False
|
|
return False
|
|
|
return True
|
|
return True
|
|
|
|
|
|
|
|
- def _refresh_and_bypass_cf(self):
|
|
|
|
|
|
|
+ def _bypass_cf_via_new_tab(self) -> bool:
|
|
|
"""
|
|
"""
|
|
|
- 处理长时间静置后由于 Cloudflare 凭据失效导致的拦截(如页面弹窗“服务不可用”),
|
|
|
|
|
- 关闭弹窗并主动刷新页面,触发并穿透 Cloudflare 5 秒盾以获取新 token。
|
|
|
|
|
|
|
+ 打开新标签页访问首页,绕过 Cloudflare 机器人验证页面并获取更新的 clearance 凭据,
|
|
|
|
|
+ 完成后关闭新标签页并切换回原排期页面。
|
|
|
"""
|
|
"""
|
|
|
- self._log("Refreshing page to trigger and solve Cloudflare 5s shield...")
|
|
|
|
|
|
|
+ root_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/"
|
|
|
|
|
+ self._log(f"Opening new tab to '{root_url}' to bypass Cloudflare verification...")
|
|
|
|
|
+ tab = None
|
|
|
|
|
+ original_tab_id = self.page.tab_id
|
|
|
try:
|
|
try:
|
|
|
- self.page.handle_alert(accept=True, timeout=0.5)
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
|
|
+ # 1. 打开新标签页
|
|
|
|
|
+ tab = self.page.new_tab(root_url)
|
|
|
|
|
+ self._random_sleep(2, 3)
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 检查并穿透 Cloudflare 机器人验证 / 5秒盾
|
|
|
|
|
+ cf_bypasser = CloudflareBypasser(tab, log=True, logger=self._log)
|
|
|
|
|
+ page_title = (getattr(tab, "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 挑战,正在穿透...")
|
|
|
|
|
+ if not cf_bypasser.bypass(max_retry=8):
|
|
|
|
|
+ self._log("[WARN] 新标签页 Cloudflare 穿透未完全成功")
|
|
|
|
|
+ self._random_sleep(2, 4)
|
|
|
|
|
+ cf_bypasser.handle_waiting_room()
|
|
|
|
|
+ else:
|
|
|
|
|
+ self._log("新标签页未触发挑战或已通过 Cloudflare 验证。")
|
|
|
|
|
+ self._random_sleep(1, 2)
|
|
|
|
|
+ cf_bypasser.handle_waiting_room()
|
|
|
|
|
|
|
|
- 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)
|
|
|
|
|
|
|
+ self._log("✅ 新标签页 Cloudflare 验证处理完成。")
|
|
|
|
|
+ return True
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"[ERROR] 新标签页穿透 Cloudflare 发生异常: {e}")
|
|
|
|
|
+ return False
|
|
|
|
|
+ finally:
|
|
|
|
|
+ if tab:
|
|
|
|
|
+ try:
|
|
|
|
|
+ tab.close()
|
|
|
|
|
+ self._log("新标签页已关闭。")
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"[WARN] 关闭新标签页失败: {e}")
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.page.activate_tab(original_tab_id)
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"[DEBUG] 激活原排期标签页失败: {e}")
|
|
|
|
|
+ self._random_sleep(1, 2)
|
|
|
|
|
|
|
|
def create_session(self) -> None:
|
|
def create_session(self) -> None:
|
|
|
"""创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
|
|
"""创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
|
|
@@ -473,16 +454,8 @@ class UsaPlugin(IVSPlg):
|
|
|
|
|
|
|
|
location_name = (self.free_config.get('location') or "").strip()
|
|
location_name = (self.free_config.get('location') or "").strip()
|
|
|
|
|
|
|
|
- # 最多尝试 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
|
|
|
|
|
-
|
|
|
|
|
|
|
+ # 最多尝试 3 次:首次查询 + 若遇 PSE0501/CF质询/超时则在新标签页过盾重试
|
|
|
|
|
+ for attempt in range(3):
|
|
|
current_url = (getattr(self.page, "url", "") or "").lower()
|
|
current_url = (getattr(self.page, "url", "") or "").lower()
|
|
|
if "schedule" not in current_url:
|
|
if "schedule" not in current_url:
|
|
|
self._log(f"Current url '{current_url}' not on schedule page, navigating...")
|
|
self._log(f"Current url '{current_url}' not on schedule page, navigating...")
|
|
@@ -512,9 +485,9 @@ class UsaPlugin(IVSPlg):
|
|
|
self._log("Waiting for consular post options to populate in #post_select...")
|
|
self._log("Waiting for consular post options to populate in #post_select...")
|
|
|
post_select = self.page.ele('#post_select', timeout=30)
|
|
post_select = self.page.ele('#post_select', timeout=30)
|
|
|
if not post_select:
|
|
if not post_select:
|
|
|
- if attempt == 0:
|
|
|
|
|
- self._log("[WARN] 未找到 #post_select,尝试刷新页面刷新 token...")
|
|
|
|
|
- self._refresh_and_bypass_cf()
|
|
|
|
|
|
|
+ if attempt < 2:
|
|
|
|
|
+ self._log("[WARN] 未找到 #post_select,尝试在新标签页绕过人机验证重试...")
|
|
|
|
|
+ self._bypass_cf_via_new_tab()
|
|
|
continue
|
|
continue
|
|
|
raise BizLogicError("Element #post_select not found.")
|
|
raise BizLogicError("Element #post_select not found.")
|
|
|
|
|
|
|
@@ -568,46 +541,64 @@ class UsaPlugin(IVSPlg):
|
|
|
|
|
|
|
|
# 5. 等待拦截 API 响应 (设置超时时间)
|
|
# 5. 等待拦截 API 响应 (设置超时时间)
|
|
|
self._log("Waiting for schedule dates API response...")
|
|
self._log("Waiting for schedule dates API response...")
|
|
|
- packet = self.page.listen.wait(timeout=20)
|
|
|
|
|
- self.page.listen.stop()
|
|
|
|
|
-
|
|
|
|
|
- # 检查是否有 alert 弹出(如“服务不可用”)
|
|
|
|
|
- alert_msg = None
|
|
|
|
|
|
|
+ packet = None
|
|
|
try:
|
|
try:
|
|
|
- alert_msg = self.page.handle_alert(accept=True, timeout=1.0)
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
-
|
|
|
|
|
- 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:
|
|
|
|
|
|
|
+ packet = self.page.listen.wait(timeout=20)
|
|
|
|
|
+ finally:
|
|
|
|
|
+ self.page.listen.stop()
|
|
|
|
|
+
|
|
|
|
|
+ # 仅在未收到响应或状态码非 200 时检查是否有错误弹窗(如 PSE0501)
|
|
|
|
|
+ if not packet or packet.response.status != 200:
|
|
|
|
|
+ alert_msg = None
|
|
|
|
|
+ try:
|
|
|
|
|
+ alert_msg = self.page.handle_alert(accept=True, timeout=0.2)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+ if alert_msg:
|
|
|
|
|
+ self._log(f"[WARN] 页面弹出提示: '{alert_msg}'")
|
|
|
|
|
+
|
|
|
|
|
+ is_pse0501 = bool(alert_msg and ("PSE0501" in alert_msg or "无法加载可预约日期" in alert_msg))
|
|
|
|
|
+
|
|
|
|
|
+ # 场景 1: 遇到 PSE0501 或 403 (CF 质询拦截)
|
|
|
|
|
+ if is_pse0501 or (packet and packet.response.status == 403):
|
|
|
|
|
+ if attempt < 2:
|
|
|
|
|
+ self._log("[WARN] 检测到 PSE0501 或 HTTP 403 质询,通过新标签页访问首页绕过人机验证...")
|
|
|
|
|
+ self._bypass_cf_via_new_tab()
|
|
|
|
|
+ continue
|
|
|
|
|
+ if alert_msg:
|
|
|
|
|
+ raise BizLogicError(f"页面弹出提示: {alert_msg}")
|
|
|
|
|
+ err_msg = str(packet.response.body)[:256] if packet else "Forbidden"
|
|
|
|
|
+ raise PermissionDeniedError(f"HTTP 403: {err_msg}")
|
|
|
|
|
+
|
|
|
|
|
+ # 场景 2: 未收到响应数据包 (超时)
|
|
|
|
|
+ if not packet:
|
|
|
|
|
+ if attempt < 2:
|
|
|
|
|
+ self._log("[WARN] 未收到排期响应数据包,尝试通过新标签页绕过人机验证重试...")
|
|
|
|
|
+ self._bypass_cf_via_new_tab()
|
|
|
|
|
+ continue
|
|
|
if alert_msg:
|
|
if alert_msg:
|
|
|
raise BizLogicError(f"页面弹出提示: {alert_msg}")
|
|
raise BizLogicError(f"页面弹出提示: {alert_msg}")
|
|
|
raise BizLogicError("Timeout waiting for schedule API response")
|
|
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:
|
|
|
|
|
|
|
+ # 场景 3: 其他 HTTP 异常状态码 (如 429)
|
|
|
|
|
+ status_code = packet.response.status
|
|
|
|
|
+ body = packet.response.body
|
|
|
|
|
+ if isinstance(body, bytes):
|
|
|
|
|
+ body = body.decode("utf-8", errors="ignore")
|
|
|
err_text = str(body)[:512]
|
|
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:
|
|
if status_code == 429:
|
|
|
self.is_healthy = False
|
|
self.is_healthy = False
|
|
|
raise RateLimiteddError(f"HTTP 429: {err_text}")
|
|
raise RateLimiteddError(f"HTTP 429: {err_text}")
|
|
|
raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
|
|
raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
|
|
|
|
|
|
|
|
|
|
+ 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}")
|
|
|
|
|
+
|
|
|
# 6. 解析返回的数据
|
|
# 6. 解析返回的数据
|
|
|
available_dates = []
|
|
available_dates = []
|
|
|
data = body if isinstance(body, dict) else None
|
|
data = body if isinstance(body, dict) else None
|