tls_plugin.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  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 datetime
  10. from typing import List, Dict, Optional, Any, Callable
  11. from urllib.parse import urljoin, urlparse, urlencode, parse_qs
  12. # DrissionPage 核心
  13. from DrissionPage import ChromiumPage, ChromiumOptions
  14. from vs_plg import IVSPlg
  15. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  16. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  17. from toolkit.proxy_tunnel import ProxyTunnel
  18. from utils.mouse import HumanMouse
  19. from utils.keyboard import HumanKeyboard
  20. from utils.fingerprint_utils import FingerprintGenerator
  21. class BrowserResponse:
  22. """模拟 requests.Response"""
  23. def __init__(self, result_dict):
  24. result_dict = result_dict or {}
  25. self.status_code = result_dict.get('status', 0)
  26. self.text = result_dict.get('body', '')
  27. self.headers = result_dict.get('headers', {})
  28. self.url = result_dict.get('url', '')
  29. self._json = None
  30. def json(self):
  31. if self._json is None:
  32. if not self.text:
  33. return {}
  34. try:
  35. self._json = json.loads(self.text)
  36. except:
  37. self._json = {}
  38. return self._json
  39. class TlsPlugin(IVSPlg):
  40. """
  41. TLSContact 签证预约插件 (DrissionPage 版)
  42. """
  43. def __init__(self, group_id: str):
  44. self.group_id = group_id
  45. self.config: Optional[VSPlgConfig] = None
  46. self.free_config: Dict[str, Any] = {}
  47. self.is_healthy = True
  48. self.logger = None
  49. self.mouse = None
  50. self.keyboard = None
  51. self.page: Optional[ChromiumPage] = None
  52. self.travel_group: Optional[Dict] = None
  53. self.instance_id = uuid.uuid4().hex[:8]
  54. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  55. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  56. if not os.path.exists(self.root_workspace):
  57. os.makedirs(self.root_workspace)
  58. self.tunnel = None
  59. self.session_create_time: float = 0
  60. def get_group_id(self) -> str:
  61. return self.group_id
  62. def set_log(self, logger: Callable[[str], None]):
  63. self.logger = logger
  64. def _log(self, message):
  65. if self.logger:
  66. self.logger(f'[TlsPlugin] [{self.group_id}] {message}')
  67. else:
  68. print(f'[TlsPlugin] [{self.group_id}] {message}')
  69. def set_config(self, config: VSPlgConfig):
  70. self.config = config
  71. self.free_config = config.free_config or {}
  72. def keep_alive(self):
  73. try:
  74. resp = self._perform_request("GET", self.page.url, retry_count=1)
  75. self._check_page_is_session_expired_or_invalid('Book your appointment', html = resp.text)
  76. except SessionExpiredOrInvalidError as e:
  77. self.is_healthy = False
  78. except Exception as e:
  79. pass
  80. def health_check(self) -> bool:
  81. if not self.is_healthy:
  82. return False
  83. if self.page is None:
  84. return False
  85. try:
  86. if not self.page.run_js("return 1;"):
  87. return False
  88. except:
  89. return False
  90. if self.config.session_max_life > 0:
  91. current_time = time.time()
  92. elapsed_time = current_time - self.session_create_time
  93. if elapsed_time > self.config.session_max_life:
  94. self._log(f"Session expired.")
  95. return False
  96. return True
  97. def _save_screenshot(self, name_prefix):
  98. try:
  99. timestamp = int(time.time())
  100. filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
  101. save_path = os.path.join("data", filename)
  102. os.makedirs("data", exist_ok=True)
  103. self.page.get_screenshot(path=save_path, full_page=False)
  104. self._log(f"Screenshot saved to {save_path}")
  105. except Exception as e:
  106. self._log(f"Failed to save screenshot: {e}")
  107. def create_session(self):
  108. """
  109. 全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
  110. """
  111. self._log(f"Initializing Session (ID: {self.instance_id})...")
  112. co = ChromiumOptions()
  113. def get_free_port():
  114. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  115. s.bind(('', 0))
  116. return s.getsockname()[1]
  117. debug_port = get_free_port()
  118. self._log(f"Assigned Debug Port: {debug_port}")
  119. co.set_local_port(debug_port)
  120. co.set_user_data_path(self.user_data_path)
  121. chrome_path = os.getenv("CHROME_BIN")
  122. if chrome_path and os.path.exists(chrome_path):
  123. co.set_paths(browser_path=chrome_path)
  124. if self.config.proxy and self.config.proxy.ip:
  125. p = self.config.proxy
  126. if p.username and p.password:
  127. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  128. self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
  129. local_proxy = self.tunnel.start()
  130. self._log(f"Tunnel started at {local_proxy}")
  131. co.set_argument(f'--proxy-server={local_proxy}')
  132. else:
  133. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  134. co.set_argument(f'--proxy-server={proxy_str}')
  135. else:
  136. self._log("[WARN] No proxy configured!")
  137. fingerprint_gen = FingerprintGenerator()
  138. specific_fp = fingerprint_gen.generate(self.config.account.username)
  139. self._log(f'browser fingerprint={specific_fp}')
  140. co.headless(False)
  141. co.set_argument('--no-sandbox')
  142. co.set_argument('--disable-dev-shm-usage')
  143. co.set_argument('--window-size=1920,1080')
  144. co.set_argument('--disable-blink-features=AutomationControlled')
  145. co.set_argument('--ignore-gpu-blocklist')
  146. co.set_argument('--enable-webgl')
  147. co.set_argument('--use-gl=angle')
  148. co.set_argument('--use-angle=swiftshader')
  149. co.set_argument(f"--fingerprint={specific_fp.get('seed')}")
  150. co.set_argument(f"--fingerprint-platform={specific_fp.get('platform')}")
  151. co.set_argument(f"--fingerprint-brand={specific_fp.get('brand')}")
  152. try:
  153. self.page = ChromiumPage(co)
  154. # --- 预检指纹信息 ---
  155. if self.config.debug:
  156. self.page.get('https://example.com')
  157. js_script = """
  158. function getFingerprint() {
  159. let webglVendor = 'Unknown';
  160. let webglRenderer = 'Unknown';
  161. try {
  162. let canvas = document.createElement('canvas');
  163. let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  164. if (gl) {
  165. let debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
  166. if (debugInfo) {
  167. webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
  168. webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
  169. }
  170. }
  171. } catch(e) {}
  172. return {
  173. "User-Agent": navigator.userAgent,
  174. "Platform": navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
  175. "Brands": navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand).join(', ') : 'Not Supported',
  176. "CPU Cores": navigator.hardwareConcurrency,
  177. "Language": navigator.language,
  178. "Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
  179. "WebGL Vendor": webglVendor,
  180. "WebGL Renderer": webglRenderer
  181. };
  182. }
  183. return getFingerprint();
  184. """
  185. fp_data = self.page.run_js(js_script)
  186. self._log("================ 预检浏览器指纹数据 ================")
  187. self._log(json.dumps(fp_data, indent=4, ensure_ascii=False))
  188. self._log("====================================================")
  189. # --- 初始化访问与过盾 ---
  190. tls_url = self.free_config.get('tls_url', '')
  191. self._log(f"Navigating: {tls_url}")
  192. self.page.get(tls_url)
  193. time.sleep(5)
  194. cf_bypasser = CloudflareBypasser(self.page, log=True)
  195. if not cf_bypasser.bypass(max_retry=15):
  196. raise BizLogicError("Cloudflare bypass timeout")
  197. time.sleep(3)
  198. cf_bypasser.handle_waiting_room()
  199. # --- 初始化人类行为模拟工具 ---
  200. self._log("Init humanize tools...")
  201. self.mouse = HumanMouse(self.page, debug=True)
  202. self.keyboard = HumanKeyboard(self.page)
  203. viewport_width = self.page.rect.viewport_size[0]
  204. viewport_height = self.page.rect.viewport_size[1]
  205. init_x = random.randint(10, viewport_width - 10)
  206. init_y = random.randint(10, viewport_height - 10)
  207. self.mouse.move(init_x, init_y)
  208. max_steps = 20
  209. session_created = False
  210. has_submitted_login = False
  211. for step in range(max_steps):
  212. self.page.wait.load_start()
  213. current_url = self.page.url
  214. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  215. # 状态 1:到达终极目标页面 (成功退出条件)
  216. if "appointment-booking" in current_url or self.page.ele('tag:button@text():Book your appointment', timeout=1):
  217. btn_selector = 'tag:button@text():Book your appointment'
  218. if self.page.wait.ele_displayed(btn_selector, timeout=10):
  219. self.session_create_time = time.time()
  220. self._log("✅ Login & Navigation Success! Reached appointment-booking.")
  221. session_created = True
  222. break
  223. # 状态 2:遇到没有申请人的拦截页 (致命错误退出条件)
  224. no_applicant_indicators = [
  225. "Add a new applicant" in self.page.html,
  226. "You have not yet added an applicant" in self.page.html,
  227. "applicants-information" in current_url
  228. ]
  229. if any(no_applicant_indicators):
  230. raise BizLogicError(message="No applicant added. Cannot proceed to booking.")
  231. # 状态 3:首页/登录入口页 -> 需要点击进入登录
  232. if self.page.ele("tag:a@@href:login", timeout=1) and not self.page.ele('tag:label@@text():Email', timeout=1):
  233. self._log("State: Login Portal. Clicking login link...")
  234. login_link = self.page.ele("tag:a@@href:login")
  235. self.mouse.human_click_ele(login_link)
  236. time.sleep(3)
  237. continue
  238. # 状态 4:真正的登录表单页
  239. if self.page.ele('tag:label@@text():Email', timeout=1) and not has_submitted_login:
  240. self._log("State: Login Form. Processing credentials and Captcha...")
  241. recaptchav2_token = ""
  242. if self.page.ele('.g-recaptcha') or self.page.ele('xpath://iframe[contains(@src, "recaptcha")]'):
  243. rec_iframe = self.page.ele('xpath://iframe[contains(@src, "recaptcha")]')
  244. rec_iframe_src = rec_iframe.attr('src')
  245. rec_parsed = urlparse(rec_iframe_src)
  246. rec_params = parse_qs(rec_parsed.query)
  247. rec_sitekey = rec_params.get("k", [None])[0]
  248. rec_size = rec_params.get("size", [None])[0]
  249. if 'normal' == rec_size:
  250. self._log(f"Solving ReCaptcha sitekey={rec_sitekey}...")
  251. rc_params = {
  252. "type": "ReCaptchaV2TaskProxyLess",
  253. "page": current_url,
  254. "siteKey": rec_sitekey,
  255. "apiToken": self.free_config.get("capsolver_key", "")
  256. }
  257. recaptchav2_token = self._solve_recaptcha(rc_params)
  258. username = self.config.account.username
  259. password = self.config.account.password
  260. input_ele = self.page.ele('tag:label@@text():Email').next()
  261. self.mouse.human_click_ele(input_ele)
  262. time.sleep(random.uniform(0.2, 0.6))
  263. self.keyboard.type_text(username, humanize=True)
  264. time.sleep(random.uniform(0.5, 1.2))
  265. input_ele = self.page.ele('tag:label@@text():Password').next()
  266. self.mouse.human_click_ele(input_ele)
  267. time.sleep(random.uniform(0.2, 0.6))
  268. self.keyboard.type_text(password, humanize=True)
  269. # 注入 Token
  270. if recaptchav2_token:
  271. inject_js = f"var g = document.getElementById('g-recaptcha-response'); if(g) {{ g.value = '{recaptchav2_token}'; }}"
  272. self.page.run_js(inject_js)
  273. time.sleep(random.uniform(0.5, 1.0))
  274. self._log("Submitting Login...")
  275. login_btn = self.page.ele('tag:button@@text():Login')
  276. self.mouse.human_click_ele(login_btn)
  277. has_submitted_login = True
  278. time.sleep(3)
  279. continue
  280. # 状态 5:Travel Groups 页面
  281. if "travel-groups" in current_url:
  282. self._log("State: Travel Groups. Selecting targeted group...")
  283. groups = self._parse_travel_groups(self.page.html)
  284. location = self.free_config.get('location')
  285. self.travel_group = next((g for g in groups if location in g['location']), None)
  286. if not self.travel_group or not self.travel_group.get("submitted"):
  287. self._save_screenshot("group_not_found")
  288. raise NotFoundError(f"Group not found for {location}")
  289. formgroup_id = self.travel_group.get('group_number')
  290. btn_selector = f'tag:button@@name=formGroupId@@value={formgroup_id}'
  291. if self.page.wait.eles_loaded(btn_selector, timeout=10):
  292. buttons = self.page.eles(btn_selector)
  293. select_btn = next((btn for btn in reversed(buttons) if btn.rect.size[0] > 0 and btn.rect.size[1] > 0), None)
  294. if select_btn:
  295. time.sleep(random.uniform(0.5, 1.2))
  296. self.mouse.human_click_ele(select_btn)
  297. time.sleep(3)
  298. continue
  299. else:
  300. self._log("[WARN] Select button found but not visible.")
  301. else:
  302. self._log(f"[WARN] Wait timeout for group button {formgroup_id}")
  303. # 状态 6:中间过渡页,需点击 "Book Appointment" 继续往下走
  304. if self.page.ele('#book-appointment-btn', timeout=1):
  305. self._log("State: Intermediate Dashboard. Clicking Book Appointment button...")
  306. self.mouse.human_click_ele(self.page.ele('#book-appointment-btn'))
  307. time.sleep(3)
  308. continue
  309. # 状态 7:登录失败校验 或 未知加载状态
  310. if "login-actions" in current_url and has_submitted_login:
  311. self._log("Waiting on login-actions... (Might be authenticating or invalid credentials)")
  312. time.sleep(2)
  313. if self.page.ele('text:Invalid username or password', timeout=1): # 假设网页上有错误提示
  314. raise BizLogicError(message="Login Failed! Invalid credentials or Captcha rejected.")
  315. continue
  316. # 兜底:未匹配到明确状态,等待页面渲染或重定向
  317. self._log("State: Transitioning or Unknown. Waiting 2 seconds...")
  318. time.sleep(2)
  319. # 如果循环耗尽还没到达目标
  320. if not session_created:
  321. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  322. except Exception as e:
  323. self._log(f"Session Create Error: {e}")
  324. if self.config.debug:
  325. self._save_screenshot("create_session_except")
  326. self.cleanup()
  327. raise e
  328. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  329. res = VSQueryResult()
  330. res.success = False
  331. interest_month = self.free_config.get("interest_month", time.strftime("%m-%Y"))
  332. target_date_obj = datetime.strptime(interest_month, "%m-%Y")
  333. target_month_text = target_date_obj.strftime("%B %Y")
  334. target_year = target_date_obj.year
  335. target_month_num = target_date_obj.month
  336. slots = []
  337. current_selected_ele = self.page.ele('@data-testid=btn-current-month-available')
  338. current_month_text = current_selected_ele.text.strip() if current_selected_ele else ""
  339. is_on_target_month = (current_month_text.lower() == target_month_text.lower())
  340. if not is_on_target_month:
  341. self._log(f"Current is '{current_month_text}', navigating to '{target_month_text}'...")
  342. reached_target = False
  343. for step in range(12):
  344. current_ele = self.page.ele('@data-testid=btn-current-month-available', timeout=2)
  345. if current_ele and current_ele.text.strip().lower() == target_month_text.lower():
  346. self._log(f"✅ Successfully navigated to target month: '{target_month_text}'!")
  347. reached_target = True
  348. break
  349. next_btn = self.page.ele('@data-testid=btn-next-month-available', timeout=2)
  350. if next_btn and next_btn.tag.lower() == 'button':
  351. self._log(f"Clicking next month: {next_btn.text.strip()} ...")
  352. next_btn.click(by_js=True)
  353. time.sleep(2.5)
  354. else:
  355. self._log("⚠️ Reached the end of the calendar or 'Next Month' is disabled.")
  356. break
  357. if not reached_target:
  358. self._log(f"❌ Could not navigate to target month: {target_month_text}. Stop parsing.")
  359. res.success = False
  360. res.availability_status = AvailabilityStatus.NoneAvailable
  361. return res
  362. self._log("Extracting slots from DOM using robust data-testid features...")
  363. slots = self._scan_dom_for_slots(target_year, target_month_num)
  364. else:
  365. self._log(f"Already on '{target_month_text}'. Executing silent JS fetch...")
  366. resp = self._perform_request("GET", self.page.url, retry_count=1)
  367. self._check_page_is_session_expired_or_invalid('Book your appointment', resp.text)
  368. slots = self._parse_appointment_slots(resp.text)
  369. if slots:
  370. res.success = True
  371. earliest_date = slots[0]["date"]
  372. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  373. res.availability_status = AvailabilityStatus.Available
  374. res.earliest_date = earliest_dt
  375. date_map: dict[datetime, list[TimeSlot]] = {}
  376. for s in slots:
  377. date_str = s["date"]
  378. dt = datetime.strptime(date_str, "%Y-%m-%d")
  379. date_map.setdefault(dt, []).append(
  380. TimeSlot(time=s["time"], label=str(s.get("label", "")))
  381. )
  382. res.availability = [DateAvailability(date=d, times=slots) for d, slots in date_map.items()]
  383. self._log(f"Slot Found! -> {slots}")
  384. else:
  385. self._log("No slots available.")
  386. res.success = False
  387. res.availability_status = AvailabilityStatus.NoneAvailable
  388. return res
  389. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  390. res = VSBookResult()
  391. res.success = False
  392. exp_start = user_inputs.get('expected_start_date', '')
  393. exp_end = user_inputs.get('expected_end_date', '')
  394. support_pta = user_inputs.get('support_pta', True)
  395. target_labels = ['']
  396. if support_pta:
  397. target_labels.append('pta')
  398. available_dates_str =[
  399. da.date.strftime("%Y-%m-%d")
  400. for da in slot_info.availability if da.date
  401. ]
  402. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  403. if not valid_dates_list:
  404. raise NotFoundError(message="No dates match user constraints")
  405. all_possible_slots =[]
  406. for da in slot_info.availability:
  407. if not da.date:
  408. continue
  409. date_str = da.date.strftime("%Y-%m-%d")
  410. if date_str in valid_dates_list:
  411. for t in da.times:
  412. if t.label in target_labels:
  413. all_possible_slots.append({
  414. "date": date_str,
  415. "time_obj": t,
  416. "label": t.label
  417. })
  418. if not all_possible_slots:
  419. raise NotFoundError(message="No suitable slot found (after label filtering)")
  420. selected_slot = random.choice(all_possible_slots)
  421. selected_date = selected_slot["date"]
  422. selected_time = selected_slot["time_obj"]
  423. selected_label = selected_slot["label"]
  424. self._log(f"Found {len(all_possible_slots)} valid slots. selected slot: {selected_date} {selected_time.time} {selected_label}")
  425. # ================== 新增:随机选择预订模式 ==================
  426. book_mode = random.choice([1, 2])
  427. self._log(f"Using booking mode: {book_mode}")
  428. if book_mode == 1:
  429. rand_x = random.randint(300, 800)
  430. rand_y = random.randint(400, 700)
  431. self._log(f"Mode 1: Moving mouse to ({rand_x}, {rand_y}) and clicking, select slot")
  432. self.mouse.click(rand_x, rand_y, humanize=True)
  433. js_update_form = f"""
  434. try {{
  435. const buttons = Array.from(document.querySelectorAll('button[type="submit"]'));
  436. const submitBtn = buttons.find(btn => {{
  437. return btn.textContent.trim().toLowerCase().includes('book your appointment');
  438. }});
  439. if (!submitBtn) return 'Submit button not found';
  440. const form = submitBtn.closest('form');
  441. if (!form) return 'Correct form not found';
  442. function setReactValue(input, value) {{
  443. if (!input) return;
  444. input.value = value;
  445. input.dispatchEvent(new Event('input', {{ bubbles: true }}));
  446. input.dispatchEvent(new Event('change', {{ bubbles: true }}));
  447. }}
  448. setReactValue(form.querySelector('input[name="date"]'), '{selected_date}');
  449. setReactValue(form.querySelector('input[name="time"]'), '{selected_time.time}');
  450. setReactValue(form.querySelector('input[name="appointmentLabel"]'), '{selected_label}');
  451. submitBtn.removeAttribute('disabled');
  452. submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  453. return 'form_updated';
  454. }} catch (e) {{
  455. return e.toString();
  456. }}
  457. """
  458. update_res = self.page.run_js(js_update_form)
  459. self._log(f"Mode 1: Form update triggered: {update_res}")
  460. if update_res != 'form_updated':
  461. raise BizLogicError(message=f"Failed to update form in Mode 1: {update_res}")
  462. submit_btn = self.page.ele('tag:button@@type=submit@@text():Book your appointment')
  463. if not submit_btn:
  464. raise BizLogicError(message="Submit button not found for mouse click")
  465. self._log("Mode 1: Moving mouse to submit button and clicking")
  466. self.mouse.human_click_ele(submit_btn)
  467. inject_res = 'clicked'
  468. else:
  469. js_inject_and_click = f"""
  470. try {{
  471. const buttons = Array.from(document.querySelectorAll('button[type="submit"]'));
  472. const submitBtn = buttons.find(btn => {{
  473. return btn.textContent.trim().toLowerCase().includes('book your appointment');
  474. }});
  475. if (!submitBtn) return 'Submit button not found';
  476. const form = submitBtn.closest('form');
  477. if (!form) return 'Correct form not found';
  478. function setReactValue(input, value) {{
  479. if (!input) return;
  480. input.value = value;
  481. input.dispatchEvent(new Event('input', {{ bubbles: true }}));
  482. input.dispatchEvent(new Event('change', {{ bubbles: true }}));
  483. }}
  484. setReactValue(form.querySelector('input[name="date"]'), '{selected_date}');
  485. setReactValue(form.querySelector('input[name="time"]'), '{selected_time.time}');
  486. setReactValue(form.querySelector('input[name="appointmentLabel"]'), '{selected_label}');
  487. submitBtn.removeAttribute('disabled');
  488. submitBtn.click();
  489. return 'clicked';
  490. }} catch (e) {{
  491. return e.toString();
  492. }}
  493. """
  494. inject_res = self.page.run_js(js_inject_and_click)
  495. self._log(f"Mode 2: Form submission triggered: {inject_res}")
  496. if inject_res != 'clicked':
  497. raise BizLogicError(message="Failed to inject form or click the submit button")
  498. self._log("Waiting for Next.js to process the form submission...")
  499. for _ in range(10):
  500. try:
  501. current_page_url = self.page.url
  502. current_page_html = self.page.html
  503. appointment_confirmation_indicators = [
  504. "order-summary" in current_page_url,
  505. "partner-services" in current_page_url,
  506. "appointment-confirmation" in current_page_url,
  507. "Change my appointment" in current_page_html,
  508. "Book a new appointment" in current_page_html,
  509. ]
  510. if any(appointment_confirmation_indicators):
  511. self._log(f"✅ BOOKING SUCCESS! Redirected to: {current_page_url}")
  512. res.success = True
  513. res.label = selected_label
  514. res.book_date = selected_date
  515. res.book_time = selected_time.time
  516. self._save_screenshot("book_slot_success")
  517. break
  518. toast_selector = 'tag:div@role=alert'
  519. toast_ele = self.page.ele(toast_selector, timeout=0.5)
  520. if toast_ele:
  521. error_msg = toast_ele.text
  522. self._log(f"❌ BOOKING FAILED! Detected popup: {error_msg}")
  523. break
  524. time.sleep(0.5)
  525. except Exception:
  526. pass
  527. return res
  528. def _scan_dom_for_slots(self, target_year: int, target_month_num: int) -> list[dict]:
  529. """
  530. DOM-based slot scanning — 结合区块结构与类名/属性推断标签
  531. """
  532. slots = []
  533. day_blocks_xpath = '//div[p and div//button[contains(@data-testid, "slot")]]'
  534. day_blocks = self.page.eles(f'xpath:{day_blocks_xpath}')
  535. for block in day_blocks:
  536. p_ele = block.ele('tag:p')
  537. if not p_ele: continue
  538. day_match = re.search(r'\d+', p_ele.text)
  539. if not day_match: continue
  540. day_str = day_match.group()
  541. full_date = f"{target_year}-{target_month_num:02d}-{int(day_str):02d}"
  542. btn_selectors = [
  543. 'xpath:.//button[starts-with(@data-testid, "btn-available-slot")]',
  544. 'xpath:.//button[contains(@class, "available")]',
  545. 'xpath:.//div[contains(@class, "time-slot") and not(contains(@class, "unavailable"))]'
  546. ]
  547. available_elements = []
  548. for sel in btn_selectors:
  549. elements = block.eles(sel)
  550. if elements:
  551. available_elements.extend(elements)
  552. break
  553. seen_times = set()
  554. for el in available_elements:
  555. classes = (el.attr("class") or "").lower()
  556. test_id = (el.attr("data-testid") or "").lower()
  557. combined_attrs = f"{classes} {test_id}"
  558. if "disabled" in combined_attrs or "unavailable" in combined_attrs:
  559. continue
  560. time_match = re.search(r'\d{2}:\d{2}', el.html)
  561. if not time_match: continue
  562. time_str = time_match.group()
  563. if time_str in seen_times:
  564. continue
  565. seen_times.add(time_str)
  566. label = ''
  567. if 'prime' in combined_attrs and 'weekend' in combined_attrs:
  568. label = 'ptaw'
  569. elif 'prime' in combined_attrs or 'premium' in combined_attrs:
  570. label = 'pta'
  571. elif any(k in combined_attrs for k in ['regular', 'standard', 'default']):
  572. label = ''
  573. else:
  574. label = ''
  575. slots.append({
  576. 'date': full_date,
  577. 'time': time_str,
  578. 'label': label,
  579. 'source': 'dom'
  580. })
  581. return slots
  582. def _get_proxy_url(self):
  583. # 构造代理
  584. proxy_url = ""
  585. if self.config.proxy.ip:
  586. s = self.config.proxy
  587. if s.username:
  588. proxy_url = f"{s.proto}://{s.username}:{s.password}@{s.ip}:{s.port}"
  589. else:
  590. proxy_url = f"{s.proto}://{s.ip}:{s.port}"
  591. return proxy_url
  592. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  593. """
  594. 在浏览器上下文中注入 JS 执行 Fetch
  595. """
  596. if not self.page:
  597. raise BizLogicError("Browser not initialized")
  598. if params:
  599. from urllib.parse import urlencode
  600. if '?' in url:
  601. url += '&' + urlencode(params)
  602. else:
  603. url += '?' + urlencode(params)
  604. fetch_options = {
  605. "method": method.upper(),
  606. "headers": headers or {},
  607. "credentials": "include"
  608. }
  609. # Body 处理
  610. if json_data:
  611. fetch_options['body'] = json.dumps(json_data)
  612. fetch_options['headers']['Content-Type'] = 'application/json'
  613. elif data:
  614. if isinstance(data, dict):
  615. from urllib.parse import urlencode
  616. fetch_options['body'] = urlencode(data)
  617. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  618. else:
  619. fetch_options['body'] = data
  620. js_script = f"""
  621. const url = "{url}";
  622. const options = {json.dumps(fetch_options)};
  623. return fetch(url, options)
  624. .then(async response => {{
  625. const text = await response.text();
  626. const headers = {{}};
  627. response.headers.forEach((value, key) => headers[key] = value);
  628. return {{
  629. status: response.status,
  630. body: text,
  631. headers: headers,
  632. url: response.url
  633. }};
  634. }})
  635. .catch(error => {{
  636. return {{
  637. status: 0,
  638. body: error.toString(),
  639. headers: {{}},
  640. url: url
  641. }};
  642. }});
  643. """
  644. res_dict = self.page.run_js(js_script, timeout=30)
  645. resp = BrowserResponse(res_dict)
  646. if resp.status_code == 200:
  647. return resp
  648. elif resp.status_code == 401:
  649. self.is_healthy = False
  650. raise SessionExpiredOrInvalidError()
  651. elif resp.status_code == 403:
  652. if retry_count < 2:
  653. self._log(f"HTTP 403 Detected. Cloudflare session expired? Attempting refresh (Try {retry_count+1}/2)...")
  654. if self._refresh_firewall_session():
  655. self._log("Firewall session refreshed. Retrying request...")
  656. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  657. else:
  658. self._log("Failed to refresh firewall session.")
  659. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  660. elif resp.status_code == 429:
  661. self.is_healthy = False
  662. raise RateLimiteddError()
  663. else:
  664. if resp.status_code == 0:
  665. raise BizLogicError(f"Network Error: {resp.text}")
  666. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  667. def _refresh_firewall_session(self) -> bool:
  668. """
  669. 主动刷新页面以触发 Cloudflare 挑战并尝试通过
  670. """
  671. try:
  672. # 1. 刷新当前页面 (通常 Dashboard 页)
  673. # 这会强制浏览器重新进行 HTTP 请求,从而触发 Cloudflare 拦截页
  674. self._log("Refreshing page to trigger Cloudflare...")
  675. self.page.refresh()
  676. # 2. 调用 CloudflareBypasser
  677. cf = CloudflareBypasser(self.page, log=self.config.debug)
  678. # 3. 尝试过盾 (尝试次数稍多一点,因为此时可能网络不稳定)
  679. success = cf.bypass(max_retry=10)
  680. if success:
  681. # 再次确认页面是否正常加载 (非 403 页面)
  682. title = self.page.title.lower()
  683. if "access denied" in title:
  684. return False
  685. # 等待 DOM 稍微稳定
  686. time.sleep(2)
  687. return True
  688. return False
  689. except Exception as e:
  690. self._log(f"Error during firewall refresh: {e}")
  691. return False
  692. def _solve_recaptcha(self, params) -> str:
  693. """调用 VSCloudApi 解决 ReCaptcha"""
  694. key = params.get("apiToken")
  695. if not key: raise NotFoundError("Api-token required")
  696. submit_url = "https://api.capsolver.com/createTask"
  697. task = {
  698. "type": params.get("type"),
  699. "websiteURL": params.get("page"),
  700. "websiteKey": params.get("siteKey"),
  701. }
  702. if params.get("action"):
  703. task["pageAction"] = params.get("action")
  704. # if params.get("proxy"):
  705. # p = urlparse(params.get("proxy"))
  706. # task["proxyType"] = p.proto
  707. # task["proxyAddress"] = p.hostname
  708. # task["proxyPort"] = p.port
  709. # if p.username:
  710. # task["proxyLogin"] = p.username
  711. # task["proxyPassword"] = p.password
  712. # 注意:使用 DrissionPage 后,通常是 ProxyLess 模式
  713. # 除非你想让 Capsolver 也用同样的代理(通常不需要,除非风控极严)
  714. payload = {"clientKey": key, "task": task}
  715. import requests as req # 局部引用,避免混淆
  716. r = req.post(submit_url, json=payload, timeout=20)
  717. if r.status_code != 200:
  718. raise BizLogicError(message="Failed to submit capsolver task")
  719. task_id = r.json().get("taskId")
  720. for _ in range(20):
  721. r = req.post("https://api.capsolver.com/getTaskResult", json={"clientKey": key, "taskId": task_id}, timeout=20)
  722. if r.status_code == 200:
  723. d = r.json()
  724. if d.get("status") == "ready":
  725. return d["solution"]["gRecaptchaResponse"]
  726. time.sleep(3)
  727. raise BizLogicError(message="Capsolver task timeout")
  728. def _parse_travel_groups(self, html_content) -> List[Dict]:
  729. groups = []
  730. js_pattern = r'\\"travelGroups\\":\s*(\[.*?\]),\\"availableCountriesToCreateGroups'
  731. js_match = re.search(js_pattern, html_content, re.DOTALL)
  732. if js_match:
  733. json_str = js_match.group(1).replace(r'\"', '"')
  734. data = json.loads(json_str)
  735. for g in data:
  736. groups.append({
  737. 'group_name': g.get('groupName'),
  738. 'group_number': g.get('formGroupId'),
  739. 'location': g.get('vacName'),
  740. 'submitted': g.get('submitted')
  741. })
  742. else:
  743. self._log('Parsed travel group page, but not found travelGroups')
  744. return groups
  745. def _parse_appointment_slots(self, html_content) -> List[Dict]:
  746. slots = []
  747. pattern = r'"availableAppointments\\":\s*(\[.*\]),\\"showFlexiAppointment'
  748. match = re.search(pattern, html_content, re.DOTALL)
  749. if match:
  750. json_str = match.group(1).replace(r'\"', '"')
  751. data = json.loads(json_str)
  752. for day in data:
  753. d_str = day.get('day')
  754. for s in day.get('slots', []):
  755. labels = s.get('labels', [])
  756. lbl = ""
  757. # 简化逻辑:TLS label 列表
  758. if 'pta' in labels: lbl = 'pta'
  759. elif 'ptaw' in labels: lbl = 'ptaw'
  760. elif '' in labels or not labels: lbl = ''
  761. slots.append({
  762. 'date': d_str,
  763. 'time': s.get('time'),
  764. 'label': lbl
  765. })
  766. return slots
  767. def _check_page_is_session_expired_or_invalid(self, keyword, html: str) -> bool:
  768. if not html:
  769. self.is_healthy = False
  770. raise SessionExpiredOrInvalidError()
  771. html_lower = html.lower()
  772. if keyword.lower() not in html_lower:
  773. session_expire_or_invalid_indicators = [
  774. 'redirected automatically' in html_lower,
  775. 'login' in html_lower and 'password' in html_lower,
  776. 'session expired' in html_lower
  777. ]
  778. if any(session_expire_or_invalid_indicators):
  779. self.is_healthy = False
  780. raise SessionExpiredOrInvalidError()
  781. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  782. if not start_str or not end_str:
  783. return dates
  784. valid_dates = []
  785. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  786. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  787. for date_str in dates:
  788. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  789. if s_date <= curr_date <= e_date:
  790. valid_dates.append(date_str)
  791. random.shuffle(valid_dates)
  792. return valid_dates
  793. # --- 资源清理核心方法 ---
  794. def cleanup(self):
  795. """
  796. 销毁浏览器并彻底删除临时文件
  797. """
  798. # 1. 关闭浏览器
  799. if self.page:
  800. try:
  801. self.page.quit() # 这会关闭 Chrome 进程
  802. except Exception:
  803. pass # 忽略已关闭的错误
  804. self.page = None
  805. # 2. 删除文件
  806. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  807. if os.path.exists(self.root_workspace):
  808. for _ in range(3):
  809. try:
  810. time.sleep(0.2)
  811. shutil.rmtree(self.root_workspace, ignore_errors=True)
  812. break
  813. except Exception as e:
  814. # 如果删除失败(通常是Windows文件占用),重试
  815. self._log(f"Cleanup retry: {e}")
  816. time.sleep(0.5)
  817. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  818. if os.path.exists(self.root_workspace):
  819. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  820. # 3. [新增] 关闭代理隧道
  821. if self.tunnel:
  822. try: self.tunnel.stop()
  823. except: pass
  824. self.tunnel = None
  825. def __del__(self):
  826. """
  827. 析构函数:当对象被垃圾回收时自动调用
  828. """
  829. self.cleanup()