usa_plugin.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import time
  2. import json
  3. import random
  4. import re
  5. import os
  6. import uuid
  7. import shutil
  8. import socket
  9. from datetime import date, datetime
  10. from typing import List, Dict, Optional, Any, Callable
  11. from urllib.parse import urljoin, urlparse, urlencode, parse_qs
  12. from concurrent.futures import ThreadPoolExecutor
  13. from DrissionPage import ChromiumPage, ChromiumOptions
  14. import configure
  15. from vs_plg import IVSPlg
  16. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  17. from toolkit.mihomo_tunnel import MihomoTunnel
  18. from utils.mouse import HumanMouse
  19. from utils.keyboard import HumanKeyboard
  20. from utils.fingerprint_utils import FingerprintGenerator
  21. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str
  22. class BrowserResponse:
  23. """模拟 requests.Response"""
  24. def __init__(self, result_dict):
  25. result_dict = result_dict or {}
  26. self.status_code = result_dict.get('status', 0)
  27. self.text = result_dict.get('body', '')
  28. self.headers = result_dict.get('headers', {})
  29. self.url = result_dict.get('url', '')
  30. self._json = None
  31. def json(self):
  32. if self._json is None:
  33. if not self.text:
  34. return {}
  35. try:
  36. self._json = json.loads(self.text)
  37. except:
  38. self._json = {}
  39. return self._json
  40. class UsaPlugin(IVSPlg):
  41. name = "usa_plugin"
  42. version = "1.0.0"
  43. description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)"
  44. LOCATIONS = {
  45. "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
  46. "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
  47. "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
  48. }
  49. def __init__(self, group_id: str):
  50. self.group_id = group_id
  51. self.config: Optional[VSPlgConfig] = None
  52. self.free_config: Dict[str, Any] = {}
  53. self.is_healthy = True
  54. self.logger = None
  55. self.mouse = None
  56. self.keyboard = None
  57. self.page: Optional[ChromiumPage] = None
  58. self.instance_id = uuid.uuid4().hex[:8]
  59. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  60. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  61. if not os.path.exists(self.root_workspace):
  62. os.makedirs(self.root_workspace)
  63. self.tunnel = None
  64. self.session_create_time: float = 0
  65. def _log(self, message):
  66. if self.logger:
  67. self.logger(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  68. else:
  69. print(f'[UsaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  70. def _random_sleep(self, min_sec=30, max_sec=60):
  71. """
  72. 核心防限速控制:模拟人类阅读和操作的长时间停顿,确保网络请求间隔在30-60秒
  73. """
  74. sleep_time = random.uniform(min_sec, max_sec)
  75. self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
  76. time.sleep(sleep_time)
  77. def _get_free_port(self):
  78. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  79. s.bind(('', 0))
  80. return s.getsockname()[1]
  81. def set_config(self, config: VSPlgConfig):
  82. """设置 API 的配置信息"""
  83. self.config = config
  84. self.free_config = config.free_config or {}
  85. def set_log(self, logger: Callable[[str], None]) -> None:
  86. """设置日志输出工具"""
  87. self.logger = logger
  88. def keep_alive(self):
  89. pass
  90. def health_check(self) -> bool:
  91. if not self.is_healthy:
  92. return False
  93. if self.page is None:
  94. return False
  95. try:
  96. if not self.page.run_js("return 1;"):
  97. return False
  98. except:
  99. return False
  100. if self.config.session_max_life > 0:
  101. current_time = time.time()
  102. elapsed_time = current_time - self.session_create_time
  103. if elapsed_time > self.config.session_max_life:
  104. self._log(f"Session expired.")
  105. return False
  106. return True
  107. def _save_screenshot(self, name_prefix):
  108. try:
  109. timestamp = int(time.time())
  110. filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
  111. save_path = os.path.join("data", filename)
  112. os.makedirs("data", exist_ok=True)
  113. self.page.get_screenshot(path=save_path, full_page=False)
  114. self._log(f"Screenshot saved to {save_path}")
  115. except Exception as e:
  116. self._log(f"Failed to save screenshot: {e}")
  117. def create_session(self) -> None:
  118. """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
  119. self._log(f"Initializing Session (ID: {self.instance_id})...")
  120. def get_free_port():
  121. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  122. s.bind(('', 0))
  123. return s.getsockname()[1]
  124. co = ChromiumOptions()
  125. debug_port = get_free_port()
  126. self._log(f"Assigned Debug Port: {debug_port}")
  127. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  128. co.set_local_port(debug_port)
  129. co.set_user_data_path(self.user_data_path)
  130. chrome_path = configure.CHROME_PATH
  131. if not chrome_path:
  132. chrome_path = os.getenv("CHROME_BIN")
  133. if chrome_path and os.path.exists(chrome_path):
  134. co.set_paths(browser_path=chrome_path)
  135. if self.config.proxy and self.config.proxy.ip:
  136. p = self.config.proxy
  137. if p.username and p.password:
  138. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  139. exit_node = {
  140. "name": "ExitNode",
  141. "type": p.proto,
  142. "server": p.ip,
  143. "port": p.port,
  144. "username": p.username,
  145. "password": p.password
  146. }
  147. relay_node = None
  148. if configure.MIHOMO_RELAY_NODES:
  149. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  150. mihomo_path = configure.MIHOMO_BIN_PATH
  151. if not mihomo_path:
  152. mihomo_path = os.getenv("MIHOMO_BIN")
  153. if not mihomo_path:
  154. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  155. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  156. local_proxy = self.tunnel.start()
  157. self._log(f"Tunnel started at {local_proxy}")
  158. co.set_argument(f'--proxy-server={local_proxy}')
  159. else:
  160. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  161. co.set_argument(f'--proxy-server={proxy_str}')
  162. else:
  163. self._log("[WARN] No proxy configured!")
  164. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  165. fp_seed = specific_fp.get("seed")
  166. fp_platform = specific_fp.get("platform")
  167. fp_brand = specific_fp.get("brand")
  168. self._log(f'browser fingerprint seed={fp_seed}')
  169. co.headless(False)
  170. co.set_argument('--no-sandbox')
  171. co.set_argument('--disable-dev-shm-usage')
  172. co.set_argument('--window-size=1920,1080')
  173. co.set_argument('--disable-blink-features=AutomationControlled')
  174. co.set_argument(f"--fingerprint={fp_seed}")
  175. co.set_argument(f"--fingerprint-platform={fp_platform}")
  176. co.set_argument(f"--fingerprint-brand={fp_brand}")
  177. self.page = ChromiumPage(co)
  178. # 获取基础 URL
  179. usa_url = self.free_config.get('usa_url', '')
  180. self._log(f"Navigating: {usa_url}")
  181. self.page.get(usa_url)
  182. self._random_sleep(3, 5)
  183. if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
  184. self._log(f'Block by cloudflare, try refresh...')
  185. self.page.refresh()
  186. self.page.wait.doc_loaded()
  187. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  188. if not cf_bypasser.bypass(max_retry=6):
  189. raise BizLogicError("Cloudflare bypass timeout")
  190. self._random_sleep(3, 5)
  191. cf_bypasser.handle_waiting_room()
  192. self._log("Init humanize tools...")
  193. self.mouse = HumanMouse(self.page, debug=False)
  194. self.keyboard = HumanKeyboard(self.page)
  195. viewport_width = self.page.rect.viewport_size[0]
  196. viewport_height = self.page.rect.viewport_size[1]
  197. init_x = random.randint(10, viewport_width - 10)
  198. init_y = random.randint(10, viewport_height - 10)
  199. self.mouse.move(init_x, init_y)
  200. username = self.config.account.username
  201. password = self.config.account.password
  202. security = self.free_config.get('security', {})
  203. max_steps = 15 # 由于状态多,步数可以稍微调大一点
  204. stuck_counter = 0
  205. last_url = ""
  206. session_created = False
  207. has_submitted_login = False
  208. for step in range(max_steps):
  209. self.page.wait.doc_loaded()
  210. time.sleep(1) # 这个用于等待页面DOM渲染,保留短时,因为不是发请求
  211. current_url = self.page.url
  212. current_title = self.page.title.lower()
  213. current_html_content = self.page.html
  214. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  215. # --- [异常处理层] ---
  216. if current_url == last_url:
  217. stuck_counter += 1
  218. else:
  219. last_url = current_url
  220. stuck_counter = 0
  221. if stuck_counter >= 3:
  222. self._log("[WARN] Page stucked, try to refresh...")
  223. self.page.refresh()
  224. self._random_sleep(30, 40)
  225. stuck_counter = 0
  226. continue
  227. # 网络出现故障,直接重试
  228. server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable"]
  229. if any(err in current_html_content for err in server_error_indicators):
  230. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  231. self.page.refresh()
  232. self._random_sleep(30, 40)
  233. continue
  234. cloudflare_blocked_indicators = [
  235. "Sorry, you have been blocked" in current_html_content,
  236. "You are being rate limited" in current_html_content,
  237. "Cloudflare Ray ID" in current_html_content
  238. ]
  239. if any(cloudflare_blocked_indicators):
  240. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  241. # 遇到五秒盾先绕盾
  242. if "just a moment" in current_title:
  243. if not cf_bypasser.bypass(max_retry=3):
  244. continue
  245. self._random_sleep(3, 5)
  246. cf_bypasser.handle_waiting_room()
  247. continue
  248. if self.page.ele('#post_select', timeout=1):
  249. self._log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")
  250. self.session_create_time = time.time()
  251. session_created = True
  252. break
  253. # 状态 2: 密保问题页面
  254. elif self.page.ele('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]', timeout=1):
  255. self._log("[State] Security question verification detected. Filling in answers...")
  256. answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
  257. for ans_ele in answer_eles:
  258. ele_id = ans_ele.attr('id')
  259. match = re.search(r'kba(\d+)_response', ele_id)
  260. if match:
  261. q_num = match.group(1)
  262. config_key = f"{q_num}_quest"
  263. q_data = security.get(config_key)
  264. ans_text = q_data.get('a')
  265. self.mouse.human_click_ele(ans_ele)
  266. self.keyboard.type_text(ans_text, humanize=True)
  267. self._log(f"-> Find input {ele_id}, successfully filled in the answer for question {q_num}.")
  268. continue_btn = self.page.ele('#continue')
  269. self.mouse.human_click_ele(continue_btn)
  270. self._log("Security answers submitted. Waiting for redirection...")
  271. self._random_sleep(30, 40)
  272. continue
  273. # 状态 1: 登录页面
  274. elif self.page.ele('#signInName', timeout=1):
  275. self._log("[State] Login page detected. Submitting credentials...")
  276. username_selector = '#signInName'
  277. username_input = self.page.ele(username_selector)
  278. self.mouse.human_click_ele(username_input)
  279. username_input.clear()
  280. self.keyboard.type_text(username, humanize=True)
  281. self._random_sleep(3, 5)
  282. password_selector = '#password'
  283. password_input = self.page.ele(password_selector)
  284. self.mouse.human_click_ele(password_input)
  285. password_input.clear()
  286. self.keyboard.type_text(password, humanize=True)
  287. self._random_sleep(3, 5)
  288. continue_btn_selector = '#continue'
  289. continue_btn = self.page.ele(continue_btn_selector)
  290. self.mouse.human_click_ele(continue_btn)
  291. has_submitted_login = True
  292. self._log("Login form submitted. Waiting for the next step to load...")
  293. self._random_sleep(30, 40)
  294. continue
  295. elif self.page.ele('#continue_application', timeout=1):
  296. schedule_btn = self.page.ele('#continue_application', timeout=0.5)
  297. self._log("Currently in first-time booking mode, clicking to proceed...")
  298. self.mouse.human_click_ele(schedule_btn)
  299. self._random_sleep(30, 40)
  300. # 状态 3: 预约主页(控制台) -> 选择首签或改签
  301. elif self.page.ele('#atlas-sidebar', timeout=1):
  302. self._log("[State] At the main booking dashboard. Looking for navigation button...")
  303. reschedule_btn_selector = '#reschedule_appointment'
  304. schedule_btn_selector = '#schedule_appointment'
  305. reschedule_btn = self.page.ele(reschedule_btn_selector, timeout=0.5)
  306. if reschedule_btn:
  307. self._log("Currently in rescheduling mode, clicking to proceed...")
  308. self.mouse.human_click_ele(reschedule_btn)
  309. self._random_sleep(30, 40)
  310. else:
  311. schedule_btn = self.page.ele(schedule_btn_selector, timeout=0.5)
  312. if schedule_btn:
  313. self._log("Currently in first-time booking mode, clicking to proceed...")
  314. self.mouse.human_click_ele(schedule_btn)
  315. self._random_sleep(30, 40)
  316. else:
  317. self._log("Not found schedule or reschedule button. The page may still be loading...")
  318. time.sleep(2)
  319. continue
  320. else:
  321. self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
  322. time.sleep(2)
  323. if not session_created:
  324. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  325. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  326. """查询可用的签证预约信息"""
  327. self._log("Querying available slots...")
  328. res = VSQueryResult()
  329. res.success = False
  330. self.page.refresh()
  331. if "just a moment" in self.page.title:
  332. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  333. if not cf_bypasser.bypass(max_retry=5):
  334. raise BizLogicError("Cloudflare bypass timeout")
  335. self._random_sleep(3, 5)
  336. cf_bypasser.handle_waiting_room()
  337. current_url = self.page.url.lower()
  338. if 'auth' in current_url or 'login' in current_url:
  339. self.is_healthy = False
  340. raise SessionExpiredOrInvalidError()
  341. applicant = self.free_config.get('applicant')
  342. location_name = self.free_config.get('location')
  343. location_id = self.LOCATIONS.get(location_name.upper(), {}).get('id')
  344. # 2. 等待页面元素
  345. self.page.ele(f"xpath://label[text()='{applicant}']", timeout=60)
  346. post_select = self.page.ele('#post_select', timeout=60)
  347. # ==================== 新增:网络监听逻辑 ====================
  348. # 开启监听目标 API
  349. target_api = 'get-family-consular-schedule-days'
  350. self.page.listen.start(target_api)
  351. # 3. 选择领事馆 (此操作会触发上述 API 的 AJAX 请求)
  352. self.page.ele(f"xpath://select[@id='post_select']/option[@value='{location_id}']", timeout=60)
  353. post_select.select.by_value(location_id)
  354. # 4. 等待拦截 API 响应 (设置超时时间)
  355. self._log("Waiting for schedule dates API response...")
  356. packet = self.page.listen.wait(timeout=30)
  357. self.page.listen.stop()
  358. if not packet:
  359. raise BizLogicError("Timeout waiting for schedule API response")
  360. status_code = packet.response.status
  361. raw_resp = packet.response.raw_body
  362. self._log(f"API Response Status: {status_code}")
  363. # 处理 HTTP 返回码不是200的情况
  364. if status_code != 200:
  365. if status_code == 403:
  366. raise PermissionDeniedError(f"HTTP 403: {raw_resp[:512]}")
  367. if status_code == 429:
  368. self.is_healthy = False
  369. raise RateLimiteddError(f"HTTP 429: {raw_resp[:512]}")
  370. raise BizLogicError(f"HTTP {status_code} error. resp={raw_resp[0:512]}")
  371. # 5. 解析返回的数据
  372. available_dates = []
  373. match = re.search(r'(\{.*\})', raw_resp, re.DOTALL)
  374. if match:
  375. json_str = match.group(1)
  376. data = json.loads(json_str)
  377. else:
  378. data = json.loads(raw_resp)
  379. schedule_days = data.get("ScheduleDays", [])
  380. if schedule_days:
  381. for day_obj in schedule_days:
  382. date_str = day_obj.get("Date")
  383. if date_str:
  384. available_dates.append(date_str)
  385. # 6. 处理最终结果 (保持与你原有返回结构一致)
  386. if available_dates:
  387. # 确保日期是有序的
  388. available_dates.sort()
  389. res.success = True
  390. res.availability_status = AvailabilityStatus.Available
  391. earliest_date = available_dates[0]
  392. res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
  393. res.availability = [
  394. DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
  395. for d in available_dates
  396. ]
  397. self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
  398. else:
  399. res.success = False
  400. res.availability_status = AvailabilityStatus.NoneAvailable
  401. self._log("No slots available.")
  402. return res
  403. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  404. """进行预约操作"""
  405. res = VSBookResult()
  406. res.success = False
  407. exp_start = user_inputs.get('expected_date_start', '')
  408. exp_end = user_inputs.get('expected_date_end', '')
  409. available_dates_str =[
  410. da.date.strftime("%Y-%m-%d")
  411. for da in slot_info.availability if da.date
  412. ]
  413. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  414. if not valid_dates_list:
  415. raise NotFoundError(message="No dates match user constraints")
  416. selected_slot_date = random.choice(valid_dates_list)
  417. book_date_obj = datetime.strptime(selected_slot_date, "%Y-%m-%d").date()
  418. # jQuery UI Datepicker 月份是 0-11
  419. target_day = str(book_date_obj.day)
  420. target_month = str(book_date_obj.month - 1)
  421. target_year = str(book_date_obj.year)
  422. self._log(f"Target booking date: {selected_slot_date}. Navigating calendar...")
  423. # 1. 适配不在当前日历的情况:通过下拉框选择年份和月份
  424. year_select = self.page.ele('.ui-datepicker-year', timeout=10) # 查找年份下拉框
  425. if year_select and year_select.value != target_year:
  426. self._log(f"Changing year to {target_year}")
  427. year_select.select.by_value(target_year)
  428. self._random_sleep(0.5, 1)
  429. month_select = self.page.ele('.ui-datepicker-month', timeout=10) # 查找月份下拉框
  430. if month_select and month_select.value != target_month:
  431. self._log(f"Changing month to {target_month}")
  432. month_select.select.by_value(target_month)
  433. self._random_sleep(0.5, 1)
  434. # 2. 点击目标日期
  435. self._log(f"Clicking date {selected_slot_date}...")
  436. target_cell_selector = f"xpath://td[@data-year='{target_year}' and @data-month='{target_month}']//a[text()='{target_day}']"
  437. target_date_cell = self.page.ele(target_cell_selector, timeout=10)
  438. if not target_date_cell:
  439. raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.")
  440. self.mouse.human_click_ele(target_date_cell)
  441. self._log("Waiting for available times to load...")
  442. self._random_sleep(3, 5)
  443. # 3. 等待并选择时间
  444. self._log("Selecting earliest available time...")
  445. slot_time_selector = "css:#time_select input[name='schedule-entries']"
  446. first_time_radio = self.page.ele(slot_time_selector, timeout=15)
  447. if not first_time_radio:
  448. raise BizLogicError("Failed to load time slots after clicking date. Might be rate limited or slots gone.")
  449. selected_slot_time = first_time_radio.parent().text.strip()
  450. self.mouse.human_click_ele(first_time_radio)
  451. # 4. 点击提交
  452. self._random_sleep(1, 2)
  453. self._log("Submitting booking...")
  454. submit_appointment_selector = "#submitbtn"
  455. submit_button = self.page.ele(submit_appointment_selector, timeout=10)
  456. self.mouse.human_click_ele(submit_button)
  457. self._log("Booking submitted successfully!")
  458. # 构造返回结果
  459. res = VSBookResult()
  460. res.success = True
  461. res.book_date = selected_slot_date
  462. res.book_time = selected_slot_time
  463. res.account = self.config.account.username
  464. return res
  465. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  466. if not start_str or not end_str:
  467. return dates
  468. valid_dates = []
  469. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  470. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  471. for date_str in dates:
  472. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  473. if s_date <= curr_date <= e_date:
  474. valid_dates.append(date_str)
  475. random.shuffle(valid_dates)
  476. return valid_dates
  477. # --- 资源清理核心方法 ---
  478. def cleanup(self):
  479. """
  480. 销毁浏览器并彻底删除临时文件
  481. """
  482. if self.page:
  483. try:
  484. self.page.quit(force=True)
  485. except Exception:
  486. pass
  487. self.page = None
  488. if os.path.exists(self.root_workspace):
  489. for _ in range(3):
  490. try:
  491. time.sleep(0.2)
  492. shutil.rmtree(self.root_workspace, ignore_errors=True)
  493. break
  494. except Exception as e:
  495. self._log(f"Cleanup retry: {e}")
  496. time.sleep(0.5)
  497. if os.path.exists(self.root_workspace):
  498. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  499. if self.tunnel:
  500. try: self.tunnel.stop()
  501. except: pass
  502. self.tunnel = None
  503. def get_plugin_status(self) -> PluginStatus:
  504. account_name = self.config.account.username if self.config and self.config.account else ""
  505. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  506. current_url = ""
  507. if self.page:
  508. try:
  509. current_url = self.page.url
  510. except Exception:
  511. pass
  512. session_age = int(time.time() - self.session_create_time) if hasattr(self, "session_create_time") and self.session_create_time > 0 else 0
  513. state = "running" if self.is_healthy else "unhealthy"
  514. return PluginStatus(
  515. instance_id=self.instance_id,
  516. is_healthy=self.is_healthy,
  517. state=state,
  518. current_url=current_url,
  519. account=account_name,
  520. proxy=proxy_info,
  521. session_age_sec=session_age,
  522. last_active_at=utc_now_str(),
  523. )
  524. def __del__(self):
  525. """
  526. 析构函数:当对象被垃圾回收时自动调用
  527. """
  528. self.cleanup()