import time import json import random import re import os import uuid from datetime import datetime from typing import List, Dict, Optional, Any, Callable from DrissionPage import ChromiumPage from vs_plg import IVSPlg from vs_types import ( VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str ) from utils.cloudflare_bypass_for_scraping import CloudflareBypasser from utils.mouse import HumanMouse from utils.keyboard import HumanKeyboard from utils.flow_engine import BaseFlow, on, guard, done, fatal from utils.plugin_utils import ( init_chromium_options, filter_dates_in_range, cleanup_browser_workspace, save_screenshot ) class UsaLoginFlow(BaseFlow): """ 基于 BaseFlow 注解状态机驱动的美签 USVisaScheduling 会话创建与自动导航流 """ def __init__(self, page, plugin: 'UsaPlugin', interval: float = 1.0): super().__init__( page=page, config=plugin.config, context={"plugin": plugin}, interval=interval, logger=plugin._log, cf_bypasser=CloudflareBypasser(page, log=True, logger=plugin._log), max_stuck_cycles=30 ) self.plugin = plugin self.login_submit_attempts = 0 self.last_login_submit_time = 0.0 # --- 异常守卫与自愈 (Priority 5~7) --- @guard(text="502 Bad Gateway", priority=5) @guard(text="503 Service Temporarily Unavailable", priority=5) def on_server_network_error(self): self.log("[WARN] 检测到服务器网络错误 (502/503),等待并刷新自愈...", level="warning") self.plugin._random_sleep(30, 40) self.page.refresh() try: self.page.wait.doc_loaded() except Exception: pass @guard(text="Sorry, you have been blocked", priority=6) @guard(text="You are being rate limited", priority=6) @guard(text="Cloudflare Ray ID", priority=6) @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.") def on_cloudflare_blocked(self): pass @guard(title="just a moment", 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) def on_cloudflare_turnstile_challenge(self): self.log("🛡️ 检测到 Cloudflare 5秒盾/Turnstile挑战,正在尝试穿透...") if self.cf_bypasser.bypass(max_retry=8): self.log("✅ Cloudflare 挑战通过!") self.plugin._random_sleep(2, 4) self.cf_bypasser.handle_waiting_room() else: self.log("[WARN] 本周期未完全通过 Cloudflare,将在下一周期继续尝试...") @guard(title="waitting room", priority=7) @guard(title="waiting room", priority=7) def on_cloudflare_waiting_room(self): self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...") self.cf_bypasser.handle_waiting_room() time.sleep(2) # --- 状态流转与表单处理 (Priority 35~50) --- @on(ele="#signInName", priority=50) def handle_login_form(self): # 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 # 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 password = self.plugin.config.account.password username_input = self.page.ele('#signInName') self.plugin.mouse.human_click_ele(username_input) username_input.clear() self.plugin.keyboard.type_text(username, humanize=True) self.plugin._random_sleep(2, 4) password_input = self.page.ele('#password') self.plugin.mouse.human_click_ele(password_input) password_input.clear() self.plugin.keyboard.type_text(password, humanize=True) self.plugin._random_sleep(2, 4) continue_btn = self.page.ele('#continue') if continue_btn: self.plugin.mouse.human_click_ele(continue_btn) self.last_login_submit_time = time.time() self.log("Login form submitted. Waiting for the next step to load...") self.plugin._random_sleep(10, 15) def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]: if not security: return None # 1. 列表格式: ["ans1", "ans2", "ans3"] if isinstance(security, list): idx = int(q_num) - 1 if 0 <= idx < len(security): return str(security[idx]) return None # 2. 字典格式 if isinstance(security, dict): # 极简键格式: {"1": "ans1", "2": "ans2"} 或 {1: "ans1", 2: "ans2"} if q_num in security: val = security[q_num] return str(val.get('a', '')) if isinstance(val, dict) else str(val) if q_num.isdigit() and int(q_num) in security: val = security[int(q_num)] return str(val.get('a', '')) if isinstance(val, dict) else str(val) # 旧版嵌套键格式: {"1_quest": {"a": "ans1"}} 或 {"1_quest": "ans1"} config_key = f"{q_num}_quest" if config_key in security: val = security[config_key] return str(val.get('a', '')) if isinstance(val, dict) else str(val) return None @on(ele="xpath://input[starts-with(@id, 'kba') and contains(@id, '_response')]", priority=45) def handle_kba_security_questions(self): self.log("[State] Security question verification detected. Filling in answers...") security = self.plugin.free_config.get('security') answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]') if not security: save_screenshot(self.page, self.plugin.instance_id, "kba_security_missing", logger=self.log) err_msg = "美签登录触发了 KBA 密保问题验证,但在 free_config 中未配置 'security' 答案,无法继续登录。" self.log(f"[ERROR] {err_msg}", level="error") raise BizLogicError(err_msg) for ans_ele in answer_eles: ele_id = ans_ele.attr('id') match = re.search(r'kba(\d+)_response', ele_id) if match: q_num = match.group(1) ans_text = self._extract_security_answer(security, q_num) if ans_text is None: save_screenshot(self.page, self.plugin.instance_id, f"kba_q{q_num}_missing", logger=self.log) err_msg = f"美签登录触发了第 {q_num} 道密保问题,但配置中未提供对应答案(当前配置: {security})。" self.log(f"[ERROR] {err_msg}", level="error") raise BizLogicError(err_msg) self.plugin.mouse.human_click_ele(ans_ele) ans_ele.clear() self.plugin.keyboard.type_text(ans_text, humanize=True) self.log(f"-> Found input {ele_id}, successfully filled in answer for question {q_num}.") continue_btn = self.page.ele('#continue') if continue_btn: self.plugin.mouse.human_click_ele(continue_btn) self.log("Security answers submitted. Waiting for redirection...") self.plugin._random_sleep(30, 40) @on(ele="#atlas-sidebar", priority=35) def handle_dashboard_sidebar(self): self.log("[State] At the main booking dashboard. Looking for navigation button...") # 1. 优先检查重新安排预约按钮 (#reschedule_appointment,针对已有预约账号的改约) reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5) if reschedule_btn: self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...") self.plugin.mouse.human_click_ele(reschedule_btn) self.plugin._random_sleep(15, 25) return # 2. 检查首次预约按钮 (#schedule_appointment) schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5) if schedule_btn: self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...") self.plugin.mouse.human_click_ele(schedule_btn) self.plugin._random_sleep(15, 25) return # 3. 检查动态注入的 admin_link 安排预约 admin_link = self.page.ele('#admin_link', timeout=0.5) if admin_link: self.log("Found '#admin_link' (安排预约), clicking to proceed...") self.plugin.mouse.human_click_ele(admin_link) self.plugin._random_sleep(15, 25) return # 4. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本匹配预约/改约的链接 fallback_link = ( 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(), "重新安排预约") or contains(text(), "Schedule") or contains(text(), "Reschedule")]', timeout=0.5) ) if fallback_link: self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...") self.plugin.mouse.human_click_ele(fallback_link) self.plugin._random_sleep(15, 25) return self.log("Not found schedule or reschedule button. The page may still be loading...") time.sleep(2) # --- 成功终态到达 (Priority 10) --- @on(ele="#post_select", priority=10) @done def on_reached_slot_search_page(self): self.plugin.session_create_time = time.time() self.log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!") class UsaPlugin(IVSPlg): name = "usa_plugin" version = "1.0.0" description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)" LOCATIONS = { "BEIJING": {"name": "BEIJING", "id": "106bf614-b0db-ec11-a7b4-001dd80234f6"}, "GUANGZHOU": {"name": "GUANGZHOU", "id": "a26af614-b0db-ec11-a7b4-001dd80234f6"}, "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"}, "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"}, "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"}, } def __init__(self, group_id: str): self.group_id = group_id self.config: Optional[VSPlgConfig] = None self.free_config: Dict[str, Any] = {} self.is_healthy = True self.logger = None self.mouse = None self.keyboard = None self.page: Optional[ChromiumPage] = None self.instance_id = uuid.uuid4().hex[:8] self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}")) self.user_data_path = os.path.join(self.root_workspace, "user_data") if not os.path.exists(self.root_workspace): os.makedirs(self.root_workspace) self.tunnel = None self.session_create_time: float = 0 def _log(self, message): if self.logger: self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}') else: print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}') def _random_sleep(self, min_sec=30, max_sec=60): """ 核心防限速控制:模拟人类阅读和操作的长时间停顿,确保网络请求间隔在30-60秒 """ sleep_time = random.uniform(min_sec, max_sec) self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...") time.sleep(sleep_time) def set_config(self, config: VSPlgConfig): """设置 API 的配置信息""" self.config = config self.free_config = config.free_config or {} def set_log(self, logger: Callable[[str], None]) -> None: """设置日志输出工具""" self.logger = logger def keep_alive(self): pass def health_check(self) -> bool: if not self.is_healthy: return False if self.page is None: return False 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;"): return False except Exception: return False if self.config.session_max_life > 0: current_time = time.time() elapsed_time = current_time - self.session_create_time if elapsed_time > self.config.session_max_life: self._log("Session expired.") return False 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: """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)""" self._log(f"Initializing Session (ID: {self.instance_id})...") self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}") co, self.tunnel = init_chromium_options( user_data_path=self.user_data_path, username_seed=self.config.account.username if self.config and self.config.account else None, proxy=self.config.proxy if self.config else None, headless=False, window_size="1920,1080", logger=self._log ) self.page = ChromiumPage(co) self._log("Init humanize tools...") self.mouse = HumanMouse(self.page, debug=False) self.keyboard = HumanKeyboard(self.page) viewport_width = self.page.rect.viewport_size[0] viewport_height = self.page.rect.viewport_size[1] init_x = random.randint(10, viewport_width - 10) init_y = random.randint(10, viewport_height - 10) self.mouse.move(init_x, init_y) usa_url = self.free_config.get('usa_url', '') if usa_url: self._log(f"Navigating: {usa_url}") self.page.get(usa_url) # 启动 UsaLoginFlow 注解流状态机 login_flow = UsaLoginFlow( self.page, plugin=self, interval=1.0 ) login_flow.run(max_steps=100, timeout=600.0) self.session_create_time = time.time() self._log("🎉 UsaLoginFlow completed successfully. Session created.") def query(self, apt_type: AppointmentType) -> VSQueryResult: """查询可用的签证预约信息""" self._log("Querying available slots...") res = VSQueryResult() res.success = False 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 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}") # 5. 等待拦截 API 响应 (设置超时时间) self._log("Waiting for schedule dates API response...") packet = self.page.listen.wait(timeout=20) self.page.listen.stop() # 检查是否有 alert 弹出(如“服务不可用”) alert_msg = None 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: 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: """进行预约操作""" res = VSBookResult() res.success = False exp_start = user_inputs.get('expected_date_start', '') exp_end = user_inputs.get('expected_date_end', '') available_dates_str = [ da.date.strftime("%Y-%m-%d") for da in slot_info.availability if da.date ] valid_dates_list = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True) if not valid_dates_list: raise NotFoundError(message="No dates match user constraints") selected_slot_date = random.choice(valid_dates_list) book_date_obj = datetime.strptime(selected_slot_date, "%Y-%m-%d").date() # jQuery UI Datepicker 月份是 0-11 target_day = str(book_date_obj.day) target_month = str(book_date_obj.month - 1) target_year = str(book_date_obj.year) self._log(f"Target booking date: {selected_slot_date}. Navigating calendar...") # 1. 适配不在当前日历的情况:通过下拉框选择年份和月份 year_select = self.page.ele('.ui-datepicker-year', timeout=10) # 查找年份下拉框 if year_select and year_select.value != target_year: self._log(f"Changing year to {target_year}") year_select.select.by_value(target_year) self._random_sleep(0.5, 1) month_select = self.page.ele('.ui-datepicker-month', timeout=10) # 查找月份下拉框 if month_select and month_select.value != target_month: self._log(f"Changing month to {target_month}") month_select.select.by_value(target_month) self._random_sleep(0.5, 1) # 2. 点击目标日期 self._log(f"Clicking date {selected_slot_date}...") target_cell_selector = f"xpath://td[@data-year='{target_year}' and @data-month='{target_month}']//a[text()='{target_day}']" target_date_cell = self.page.ele(target_cell_selector, timeout=10) if not target_date_cell: raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.") self.mouse.human_click_ele(target_date_cell) self._log("Waiting for available times to load...") self._random_sleep(3, 5) # 3. 等待并选择时间 self._log("Selecting earliest available time...") slot_time_selector = "css:#time_select input[name='schedule-entries']" first_time_radio = self.page.ele(slot_time_selector, timeout=15) if not first_time_radio: raise BizLogicError("Failed to load time slots after clicking date. Might be rate limited or slots gone.") selected_slot_time = first_time_radio.parent().text.strip() self.mouse.human_click_ele(first_time_radio) # 4. 点击提交 self._random_sleep(1, 2) self._log("Submitting booking...") submit_appointment_selector = "#submitbtn" submit_button = self.page.ele(submit_appointment_selector, timeout=10) self.mouse.human_click_ele(submit_button) self._log("Booking submitted successfully!") # 构造返回结果 res = VSBookResult() res.success = True res.book_date = selected_slot_date res.book_time = selected_slot_time res.account = self.config.account.username return res def cleanup(self): """销毁浏览器并彻底删除临时文件""" if getattr(self, "keep_browser_on_error", False): self._log("[DEBUG] keep_browser_on_error 生效,跳过浏览器清理并保留窗口供分析。") return cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log) self.page = None self.tunnel = None def get_plugin_status(self) -> PluginStatus: account_name = self.config.account.username if self.config and self.config.account else "" proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else "" current_url = "" if self.page: try: current_url = self.page.url except Exception: pass session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0 state = "running" if self.is_healthy else "unhealthy" return PluginStatus( instance_id=self.instance_id, is_healthy=self.is_healthy, state=state, current_url=current_url, account=account_name, proxy=proxy_info, session_age_sec=session_age, last_active_at=utc_now_str(), ) def __del__(self): """ 析构函数:当对象被垃圾回收时自动调用 """ self.cleanup()