tls_plugin.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. from concurrent.futures import ThreadPoolExecutor
  13. from DrissionPage import ChromiumPage, ChromiumOptions
  14. import configure
  15. from vs_plg import IVSPlg
  16. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  17. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  18. from toolkit.mihomo_tunnel import MihomoTunnel
  19. from utils.mouse import HumanMouse, MOUSE_PROFILES
  20. from utils.keyboard import HumanKeyboard
  21. from utils.fingerprint_utils import FingerprintGenerator
  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 TlsPlugin(IVSPlg):
  41. """
  42. TLSContact 签证预约插件 (DrissionPage 版)
  43. """
  44. def __init__(self, group_id: str):
  45. self.group_id = group_id
  46. self.config: Optional[VSPlgConfig] = None
  47. self.free_config: Dict[str, Any] = {}
  48. self.is_healthy = True
  49. self.logger = None
  50. self.mouse = None
  51. self.keyboard = None
  52. self.page: Optional[ChromiumPage] = None
  53. self.travel_group: Optional[Dict] = None
  54. self.instance_id = uuid.uuid4().hex[:8]
  55. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  56. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  57. if not os.path.exists(self.root_workspace):
  58. os.makedirs(self.root_workspace)
  59. self.is_busy = False
  60. self.tunnel = None
  61. self.session_create_time: float = 0
  62. def get_group_id(self) -> str:
  63. return self.group_id
  64. def set_log(self, logger: Callable[[str], None]):
  65. self.logger = logger
  66. def _log(self, message):
  67. if self.logger:
  68. self.logger(f'[TlsPlugin] [{self.group_id}] {message}')
  69. else:
  70. print(f'[TlsPlugin] [{self.group_id}] {message}')
  71. def set_config(self, config: VSPlgConfig):
  72. self.config = config
  73. self.free_config = config.free_config or {}
  74. def keep_alive(self):
  75. try:
  76. self.page.refresh()
  77. self.page.wait.load_start(timeout=2)
  78. self.page.wait.doc_loaded()
  79. time.sleep(random.uniform(1, 3))
  80. self._check_page_is_session_expired_or_invalid('Book your appointment', html = self.page.html)
  81. self.simulate_random_human_mouse_move()
  82. except SessionExpiredOrInvalidError as e:
  83. self.is_healthy = False
  84. except Exception as e:
  85. self._log(f"Unexpected error in keep_alive: {e}")
  86. def simulate_random_human_mouse_move(self, min_x=100, max_x=800, min_y=100, max_y=800, min_points=1, max_points=2):
  87. """
  88. 在指定区域内模拟人类随机移动鼠标并点击数次。
  89. :param min_x: X坐标最小范围
  90. :param max_x: X坐标最大范围
  91. :param min_y: Y坐标最小范围
  92. :param max_y: Y坐标最大范围
  93. :param min_point: 随便移动的最少次数
  94. :param max_point: 随便移动的最多次数
  95. """
  96. move_cnt = random.randint(min_points, max_points)
  97. self._log(f"Starting random human simulation: will move {move_cnt} times in the area.")
  98. for i in range(move_cnt):
  99. rand_x = random.randint(min_x, max_x)
  100. rand_y = random.randint(min_y, max_y)
  101. self._log(f"[{i+1}/{move_cnt}] Moving mouse to ({rand_x}, {rand_y})")
  102. self.mouse.move(rand_x, rand_y, humanize=True)
  103. self._log("Random human move simulation completed.")
  104. def health_check(self) -> bool:
  105. if self.is_busy:
  106. return True
  107. if not self.is_healthy:
  108. return False
  109. if self.page is None:
  110. return False
  111. try:
  112. if not self.page.run_js("return 1;"):
  113. return False
  114. except:
  115. return False
  116. if self.config.session_max_life > 0:
  117. current_time = time.time()
  118. elapsed_time = current_time - self.session_create_time
  119. if elapsed_time > self.config.session_max_life:
  120. self._log(f"Session expired.")
  121. return False
  122. return True
  123. def _save_screenshot(self, name_prefix):
  124. try:
  125. timestamp = int(time.time())
  126. filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
  127. save_path = os.path.join("data", filename)
  128. os.makedirs("data", exist_ok=True)
  129. self.page.get_screenshot(path=save_path, full_page=False)
  130. self._log(f"Screenshot saved to {save_path}")
  131. except Exception as e:
  132. self._log(f"Failed to save screenshot: {e}")
  133. def create_session(self):
  134. """
  135. 全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
  136. """
  137. self._log(f"Initializing Session (ID: {self.instance_id})...")
  138. captcha_future = None
  139. captcha_executor = ThreadPoolExecutor(max_workers=1)
  140. login_captcha_cfg = self.free_config.get("login_captcha", {})
  141. if login_captcha_cfg.get('solve_advance'):
  142. login_page = login_captcha_cfg.get("page_url")
  143. site_key = login_captcha_cfg.get("site_key")
  144. task_type = login_captcha_cfg.get("task")
  145. self._log(f"🚀 Early starting background Captcha solve for sitekey={site_key}")
  146. rc_params = {
  147. "type": task_type,
  148. "page": login_page,
  149. "siteKey": site_key,
  150. "apiToken": self.free_config.get("capsolver_key", "")
  151. }
  152. captcha_future = captcha_executor.submit(self._solve_recaptcha, rc_params)
  153. co = ChromiumOptions()
  154. def get_free_port():
  155. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  156. s.bind(('', 0))
  157. return s.getsockname()[1]
  158. debug_port = get_free_port()
  159. self._log(f"Assigned Debug Port: {debug_port}")
  160. co.set_local_port(debug_port)
  161. co.set_user_data_path(self.user_data_path)
  162. chrome_path = configure.CHROME_PATH
  163. if not chrome_path:
  164. chrome_path = os.getenv("CHROME_BIN")
  165. if chrome_path and os.path.exists(chrome_path):
  166. co.set_paths(browser_path=chrome_path)
  167. if self.config.proxy and self.config.proxy.ip:
  168. p = self.config.proxy
  169. self._log(f'Current proxy id={p.id}')
  170. if p.username and p.password:
  171. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  172. exit_node = {
  173. "name": "ExitNode",
  174. "type": p.proto,
  175. "server": p.ip,
  176. "port": p.port,
  177. "username": p.username,
  178. "password": p.password
  179. }
  180. relay_node = None
  181. if configure.MIHOMO_RELAY_NODES:
  182. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  183. mihomo_path = configure.MIHOMO_BIN_PATH
  184. if not mihomo_path:
  185. mihomo_path = os.getenv("MIHOMO_BIN")
  186. if not mihomo_path:
  187. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  188. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  189. local_proxy = self.tunnel.start()
  190. self._log(f"Tunnel started at {local_proxy}")
  191. co.set_argument(f'--proxy-server={local_proxy}')
  192. else:
  193. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  194. co.set_argument(f'--proxy-server={proxy_str}')
  195. else:
  196. self._log("[WARN] No proxy configured!")
  197. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  198. fp_seed = specific_fp.get("seed")
  199. fp_platform = specific_fp.get("platform")
  200. fp_brand = specific_fp.get("brand")
  201. self._log(f'browser fingerprint seed={fp_seed}')
  202. co.headless(False)
  203. co.set_argument('--no-sandbox')
  204. co.set_argument('--disable-dev-shm-usage')
  205. co.set_argument('--window-size=1920,1080')
  206. co.set_argument('--disable-blink-features=AutomationControlled')
  207. # co.set_argument('--ignore-gpu-blocklist')
  208. # co.set_argument('--enable-webgl')
  209. # co.set_argument('--use-gl=angle')
  210. # co.set_argument('--use-angle=swiftshader')
  211. co.set_argument(f"--fingerprint={fp_seed}")
  212. co.set_argument(f"--fingerprint-platform={fp_platform}")
  213. co.set_argument(f"--fingerprint-brand={fp_brand}")
  214. try:
  215. self.page = ChromiumPage(co)
  216. # --- 预检指纹信息 ---
  217. if self.config.debug:
  218. self.page.get('https://example.com')
  219. js_script = """
  220. function getFingerprint() {
  221. let webglVendor = 'Unknown';
  222. let webglRenderer = 'Unknown';
  223. try {
  224. let canvas = document.createElement('canvas');
  225. let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  226. if (gl) {
  227. let debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
  228. if (debugInfo) {
  229. webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
  230. webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
  231. }
  232. }
  233. } catch(e) {}
  234. return {
  235. "User-Agent": navigator.userAgent,
  236. "Platform": navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
  237. "Brands": navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand).join(', ') : 'Not Supported',
  238. "CPU Cores": navigator.hardwareConcurrency,
  239. "Language": navigator.language,
  240. "Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
  241. "WebGL Vendor": webglVendor,
  242. "WebGL Renderer": webglRenderer
  243. };
  244. }
  245. return getFingerprint();
  246. """
  247. fp_data = self.page.run_js(js_script)
  248. self._log("================ 预检浏览器指纹数据 ================")
  249. self._log(json.dumps(fp_data, indent=4, ensure_ascii=False))
  250. self._log("====================================================")
  251. # --- 初始化访问与过盾 ---
  252. tls_url = self.free_config.get('tls_url', '')
  253. self._log(f"Navigating: {tls_url}")
  254. self.page.get(tls_url)
  255. time.sleep(5)
  256. if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
  257. self._log(f'Block by cloudflare, try refresh...')
  258. self.page.refresh()
  259. self.page.wait.load_start(timeout=2)
  260. self.page.wait.doc_loaded()
  261. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  262. if not cf_bypasser.bypass(max_retry=6):
  263. raise BizLogicError("Cloudflare bypass timeout")
  264. time.sleep(3)
  265. cf_bypasser.handle_waiting_room()
  266. self._log("Init humanize tools...")
  267. profile_name = random.choice(list(MOUSE_PROFILES.keys()))
  268. self._log(f"[HumanMouse] current mouse profiles: {profile_name}")
  269. self.mouse = HumanMouse(self.page, timing=MOUSE_PROFILES[profile_name], debug=self.config.debug)
  270. self.keyboard = HumanKeyboard(self.page)
  271. viewport_width = self.page.rect.viewport_size[0]
  272. viewport_height = self.page.rect.viewport_size[1]
  273. init_x = random.randint(10, viewport_width - 10)
  274. init_y = random.randint(10, viewport_height - 10)
  275. self.mouse.move(init_x, init_y)
  276. max_steps = 10
  277. session_created = False
  278. has_submitted_login = False
  279. other_langs = ['fr-fr', 'ar-ar', 'cb-ph', 'id-id', 'km-kh', 'mk-mk', 'ru-ru', 'sq-al', 'th-th', 'tl-ph', 'uz-uz', 'vi-vn', 'zh-cn', 'hy-am', 'zh-hk']
  280. for step in range(max_steps):
  281. self.page.wait.doc_loaded()
  282. time.sleep(1)
  283. current_url = self.page.url
  284. current_title = self.page.title.lower()
  285. current_html_content = self.page.html
  286. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  287. cloudflare_blocked_indicators = [
  288. "Sorry, you have been blocked" in current_html_content,
  289. "You are being rate limited" in current_html_content,
  290. "Cloudflare Ray ID" in current_html_content
  291. ]
  292. if any(cloudflare_blocked_indicators):
  293. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  294. # 遇到五秒盾先绕盾
  295. if "just a moment" in current_title:
  296. cf_bypasser.bypass(max_retry=3)
  297. time.sleep(3)
  298. continue
  299. # 如果语言不匹配, 切换语言到英语
  300. matched_lang = next((lang for lang in other_langs if lang in current_url), None)
  301. if matched_lang:
  302. current_url = current_url.replace(matched_lang, 'en-us')
  303. self.page.get(current_url)
  304. self.page.wait.load_start(timeout=3)
  305. continue
  306. # 到达终极目标页面 (成功退出条件)
  307. if "appointment-booking" in current_url or self.page.ele('tag:button@text():Book your appointment', timeout=1):
  308. btn_selector = 'tag:button@text():Book your appointment'
  309. if self.page.wait.ele_displayed(btn_selector, timeout=10):
  310. self._handle_cookie_dialog()
  311. self.session_create_time = time.time()
  312. self._log("✅ Login & Navigation Success! Reached appointment-booking.")
  313. session_created = True
  314. break
  315. # 页面发生react渲染错误
  316. if 'a client-side exception has occurred while loading' in current_html_content:
  317. self.page.refresh()
  318. self.page.wait.load_start(timeout=3)
  319. continue
  320. # 遇到没有申请人的拦截页 (致命错误退出条件)
  321. no_applicant_indicators = [
  322. "Add a new applicant" in current_html_content,
  323. "You have not yet added an applicant" in current_html_content,
  324. "applicants-information" in current_url
  325. ]
  326. if any(no_applicant_indicators):
  327. raise BizLogicError(message="No applicant added. Cannot proceed to booking.")
  328. # 首页/登录入口页 -> 需要点击进入登录
  329. if current_url == tls_url:
  330. if self.page.ele("tag:a@@href:login", timeout=1) and not self.page.ele('tag:label@@text():Email', timeout=1):
  331. self._log("State: Login Portal. Clicking login link...")
  332. login_link = self.page.ele("tag:a@@href:login")
  333. self.mouse.human_click_ele(login_link)
  334. self.page.wait.load_start(timeout=3)
  335. continue
  336. if self.page.ele("tag:svg@@data-testid=user-button", timeout=1):
  337. self._log("State: Already login, logout now...")
  338. user_btn = self.page.ele("tag:svg@@data-testid=user-button")
  339. self.mouse.human_click_ele(user_btn)
  340. time.sleep(1.5)
  341. logout_btn = self.page.ele("#logout")
  342. self.mouse.human_click_ele(logout_btn)
  343. self.page.wait.load_start(timeout=3)
  344. self.page.get(tls_url)
  345. self.page.wait.load_start(timeout=3)
  346. continue
  347. # 真正的登录表单页
  348. if self.page.ele('tag:label@@text():Email', timeout=1) and not has_submitted_login:
  349. self._log("State: Login Form. Processing credentials and Captcha...")
  350. recaptchav2_token = ""
  351. if not captcha_future and (self.page.ele('.g-recaptcha') or self.page.ele('xpath://iframe[contains(@src, "recaptcha")]')):
  352. rec_iframe = self.page.ele('xpath://iframe[contains(@src, "recaptcha")]')
  353. rec_iframe_src = rec_iframe.attr('src')
  354. rec_parsed = urlparse(rec_iframe_src)
  355. rec_params = parse_qs(rec_parsed.query)
  356. rec_sitekey = rec_params.get("k", [None])[0]
  357. rec_size = rec_params.get("size", [None])[0]
  358. if 'normal' == rec_size:
  359. self._log(f"Found dynamic sitekey={rec_sitekey}. Starting async Captcha solver...")
  360. rc_params = {
  361. "type": "ReCaptchaV2TaskProxyLess",
  362. "page": current_url,
  363. "siteKey": rec_sitekey,
  364. "apiToken": self.free_config.get("capsolver_key", "")
  365. }
  366. captcha_future = captcha_executor.submit(self._solve_recaptcha, rc_params)
  367. username = self.config.account.username
  368. password = self.config.account.password
  369. input_ele = self.page.ele('tag:label@@text():Email').next()
  370. self.mouse.human_click_ele(input_ele)
  371. time.sleep(random.uniform(0.2, 0.6))
  372. self.keyboard.type_text(username, humanize=True)
  373. time.sleep(random.uniform(0.5, 1.2))
  374. input_ele = self.page.ele('tag:label@@text():Password').next()
  375. self.mouse.human_click_ele(input_ele)
  376. time.sleep(random.uniform(0.2, 0.6))
  377. self.keyboard.type_text(password, humanize=True)
  378. # 注入 Token
  379. if captcha_future:
  380. self._log("Waiting for background Captcha result...")
  381. try:
  382. # 设一个合理的超时,防止死锁
  383. recaptchav2_token = captcha_future.result(timeout=120)
  384. self._log("Background Captcha solved successfully!")
  385. except Exception as e:
  386. raise BizLogicError(f"Captcha solving failed or timed out: {e}")
  387. # 注入 Token
  388. if recaptchav2_token:
  389. inject_js = f"var g = document.getElementById('g-recaptcha-response'); if(g) {{ g.value = '{recaptchav2_token}'; }}"
  390. self.page.run_js(inject_js)
  391. time.sleep(random.uniform(0.5, 1.0))
  392. self._log("Submitting Login...")
  393. login_btn = self.page.ele('tag:button@@text():Login')
  394. self.mouse.human_click_ele(login_btn)
  395. has_submitted_login = True
  396. self.page.wait.load_start(timeout=5)
  397. continue
  398. # Travel Groups 页面
  399. if "travel-groups" in current_url:
  400. self._log("State: Travel Groups. Selecting targeted group...")
  401. groups = self._parse_travel_groups(current_html_content)
  402. location = self.free_config.get('location')
  403. self.travel_group = next((g for g in groups if location in g['location']), None)
  404. if not self.travel_group or not self.travel_group.get("submitted"):
  405. self._save_screenshot("group_not_found")
  406. raise NotFoundError(f"Group not found for {location}")
  407. formgroup_id = self.travel_group.get('group_number')
  408. btn_selector = f'tag:button@@name=formGroupId@@value={formgroup_id}'
  409. if self.page.wait.eles_loaded(btn_selector, timeout=10):
  410. buttons = self.page.eles(btn_selector)
  411. select_btn = next((btn for btn in reversed(buttons) if btn.rect.size[0] > 0 and btn.rect.size[1] > 0), None)
  412. if select_btn:
  413. time.sleep(random.uniform(0.5, 1.2))
  414. self.mouse.human_click_ele(select_btn)
  415. self.page.wait.load_start(timeout=3)
  416. continue
  417. else:
  418. self._log("[WARN] Select button found but not visible.")
  419. else:
  420. self._log(f"[WARN] Wait timeout for group button {formgroup_id}")
  421. # 中间过渡页,需点击 "Book Appointment" 继续往下走
  422. if self.page.ele('#book-appointment-btn', timeout=1):
  423. self._log("State: Intermediate Dashboard. Clicking Book Appointment button...")
  424. self.mouse.human_click_ele(self.page.ele('#book-appointment-btn'))
  425. self.page.wait.load_start(timeout=3)
  426. continue
  427. # 登录失败校验 或 未知加载状态
  428. if "login-actions" in current_url and has_submitted_login:
  429. self._log("Waiting on login-actions... (Might be authenticating or invalid credentials)")
  430. time.sleep(2)
  431. if self.page.ele('text:Invalid username or password', timeout=1): # 假设网页上有错误提示
  432. raise BizLogicError(message="Login Failed! Invalid credentials or Captcha rejected.")
  433. continue
  434. self._log("State: Transitioning or Unknown. Waiting 2 seconds...")
  435. time.sleep(2)
  436. if not session_created:
  437. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  438. except Exception as e:
  439. self._log(f"Session Create Error: {e}")
  440. if self.config.debug:
  441. self._save_screenshot("create_session_except")
  442. self.cleanup()
  443. raise e
  444. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  445. res = VSQueryResult()
  446. res.success = False
  447. self.is_busy = True
  448. try:
  449. slots = []
  450. self._log(f"Executing silent JS fetch...")
  451. resp = self._perform_request("GET", self.page.url, retry_count=0)
  452. self._check_page_is_session_expired_or_invalid('Book your appointment', resp.text)
  453. slots = self._parse_appointment_slots(resp.text)
  454. if slots:
  455. res.success = True
  456. earliest_date = slots[0]["date"]
  457. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  458. res.availability_status = AvailabilityStatus.Available
  459. res.earliest_date = earliest_dt
  460. date_map: dict[datetime, list[TimeSlot]] = {}
  461. for s in slots:
  462. date_str = s["date"]
  463. dt = datetime.strptime(date_str, "%Y-%m-%d")
  464. date_map.setdefault(dt, []).append(
  465. TimeSlot(time=s["time"], label=str(s.get("label", "")))
  466. )
  467. res.availability = [DateAvailability(date=d, times=slots) for d, slots in date_map.items()]
  468. self._log(f"Slot Found! size={len(slots)}")
  469. else:
  470. self._log("No slots available.")
  471. res.success = False
  472. res.availability_status = AvailabilityStatus.NoneAvailable
  473. # TODO(TEST): 临时测试预约提交
  474. if configure.TLS_TEST_BOOK_AFTER_QUERY:
  475. test_date = "2026-06-10"
  476. test_time = "09:00"
  477. test_label = ""
  478. test_dt = datetime.strptime(test_date, "%Y-%m-%d")
  479. query_res = VSQueryResult()
  480. query_res.success = True
  481. query_res.availability_status = AvailabilityStatus.Available
  482. query_res.earliest_date = test_dt
  483. query_res.availability = [
  484. DateAvailability(
  485. date=test_dt,
  486. times=[TimeSlot(time=test_time, label=test_label)]
  487. )
  488. ]
  489. self._log(f"[TEST] using fixed June slot: {test_date} {test_time} {test_label}")
  490. test_userinput = {
  491. "support_pta": False,
  492. "expected_end_date": "2100-01-01",
  493. "expected_start_date": "2000-01-01"
  494. }
  495. try:
  496. self.book(query_res, test_userinput)
  497. except Exception as e:
  498. self._log(f"[TEST] book() after query failed: {e}")
  499. self.is_healthy = False
  500. finally:
  501. self.is_busy = False
  502. return res
  503. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  504. res = VSBookResult()
  505. res.success = False
  506. exp_start = user_inputs.get('expected_start_date', '')
  507. exp_end = user_inputs.get('expected_end_date', '')
  508. support_pta = user_inputs.get('support_pta', True)
  509. target_labels = ['']
  510. if support_pta:
  511. target_labels.append('pta')
  512. available_dates_str =[
  513. da.date.strftime("%Y-%m-%d")
  514. for da in slot_info.availability if da.date
  515. ]
  516. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  517. if not valid_dates_list:
  518. raise NotFoundError(message="No dates match user constraints")
  519. all_possible_slots =[]
  520. for da in slot_info.availability:
  521. if not da.date:
  522. continue
  523. date_str = da.date.strftime("%Y-%m-%d")
  524. if date_str in valid_dates_list:
  525. for t in da.times:
  526. if t.label in target_labels:
  527. all_possible_slots.append({
  528. "date": date_str,
  529. "time_obj": t,
  530. "label": t.label
  531. })
  532. if not all_possible_slots:
  533. raise NotFoundError(message="No suitable slot found (after label filtering)")
  534. selected_slot = random.choice(all_possible_slots)
  535. selected_date = selected_slot["date"]
  536. selected_time = selected_slot["time_obj"]
  537. selected_label = selected_slot["label"]
  538. self._log(f"Found {len(all_possible_slots)} valid slots. selected slot: {selected_date} {selected_time.time} {selected_label}")
  539. self.page.listen.start('/workflow/appointment-booking', method='POST')
  540. js_update_form = f"""
  541. try {{
  542. const buttons = Array.from(document.querySelectorAll('button[type="submit"]'));
  543. const submitBtn = buttons.find(btn => {{
  544. return btn.textContent.trim().toLowerCase().includes('book your appointment');
  545. }});
  546. if (!submitBtn) return 'Submit button not found';
  547. const form = submitBtn.closest('form');
  548. if (!form) return 'Correct form not found';
  549. function setReactValue(input, value) {{
  550. if (!input) return;
  551. input.value = value;
  552. }}
  553. setReactValue(form.querySelector('input[name="date"]'), '{selected_date}');
  554. setReactValue(form.querySelector('input[name="time"]'), '{selected_time.time}');
  555. setReactValue(form.querySelector('input[name="appointmentLabel"]'), '{selected_label}');
  556. submitBtn.removeAttribute('disabled');
  557. submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  558. return 'form_updated';
  559. }} catch (e) {{
  560. return e.toString();
  561. }}
  562. """
  563. update_res = self.page.run_js(js_update_form)
  564. self._log(f"Form update triggered: {update_res}")
  565. if update_res != 'form_updated':
  566. raise BizLogicError(message=f"Failed to update form: {update_res}")
  567. submit_btn = self.page.ele('tag:button@@type=submit@@text():Book your appointment')
  568. if not submit_btn:
  569. raise BizLogicError(message="Submit button not found for mouse click")
  570. self._log("Moving mouse to submit button and clicking")
  571. self.mouse.human_click_ele(submit_btn)
  572. packet = self.page.listen.wait(timeout=10)
  573. if not packet:
  574. raise BizLogicError(message='Listening data failed')
  575. self.page.listen.stop()
  576. self._log(f"URL: {packet.url}")
  577. self._log(f"POST Body: {packet.request.postData}")
  578. self._log(f"POST Resp: {packet.response.body}")
  579. self._log("Waiting for Next.js to process the form submission...")
  580. for _ in range(10):
  581. try:
  582. current_page_url = self.page.url
  583. current_page_html = self.page.html
  584. appointment_confirmation_indicators = [
  585. "order-summary" in current_page_url,
  586. "partner-services" in current_page_url,
  587. "appointment-confirmation" in current_page_url,
  588. "Change my appointment" in current_page_html,
  589. "Book a new appointment" in current_page_html,
  590. ]
  591. if any(appointment_confirmation_indicators):
  592. self._log(f"✅ BOOKING SUCCESS! Redirected to: {current_page_url}")
  593. res.success = True
  594. res.label = selected_label
  595. res.book_date = selected_date
  596. res.book_time = selected_time.time
  597. self._save_screenshot("book_slot_success")
  598. break
  599. toast_selector = 'tag:div@role=alert'
  600. toast_ele = self.page.ele(toast_selector, timeout=0.5)
  601. if toast_ele:
  602. error_msg = toast_ele.text
  603. self._log(f"❌ BOOKING FAILED! Detected popup: {error_msg}")
  604. break
  605. time.sleep(0.5)
  606. except Exception:
  607. pass
  608. return res
  609. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  610. """
  611. 在浏览器上下文中注入 JS 执行 Fetch
  612. """
  613. if not self.page:
  614. raise BizLogicError("Browser not initialized")
  615. if params:
  616. from urllib.parse import urlencode
  617. if '?' in url:
  618. url += '&' + urlencode(params)
  619. else:
  620. url += '?' + urlencode(params)
  621. fetch_options = {
  622. "method": method.upper(),
  623. "headers": headers or {},
  624. "credentials": "include"
  625. }
  626. # Body 处理
  627. if json_data:
  628. fetch_options['body'] = json.dumps(json_data)
  629. fetch_options['headers']['Content-Type'] = 'application/json'
  630. elif data:
  631. if isinstance(data, dict):
  632. from urllib.parse import urlencode
  633. fetch_options['body'] = urlencode(data)
  634. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  635. else:
  636. fetch_options['body'] = data
  637. js_script = f"""
  638. const url = "{url}";
  639. const options = {json.dumps(fetch_options)};
  640. return fetch(url, options)
  641. .then(async response => {{
  642. const text = await response.text();
  643. const headers = {{}};
  644. response.headers.forEach((value, key) => headers[key] = value);
  645. return {{
  646. status: response.status,
  647. body: text,
  648. headers: headers,
  649. url: response.url
  650. }};
  651. }})
  652. .catch(error => {{
  653. return {{
  654. status: 0,
  655. body: error.toString(),
  656. headers: {{}},
  657. url: url
  658. }};
  659. }});
  660. """
  661. res_dict = self.page.run_js(js_script, timeout=30)
  662. resp = BrowserResponse(res_dict)
  663. if resp.status_code == 200:
  664. return resp
  665. elif resp.status_code == 401:
  666. self.is_healthy = False
  667. raise SessionExpiredOrInvalidError()
  668. elif resp.status_code == 403:
  669. if retry_count < 2:
  670. self._log(f"HTTP 403 Detected. Cloudflare session expired? Attempting refresh (Try {retry_count+1}/2)...")
  671. if self._refresh_firewall_session():
  672. self._log("Firewall session refreshed. Retrying request...")
  673. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  674. else:
  675. self._log("Failed to refresh firewall session.")
  676. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  677. elif resp.status_code == 429:
  678. self.is_healthy = False
  679. raise RateLimiteddError()
  680. else:
  681. if resp.status_code == 0:
  682. raise BizLogicError(f"Network Error: {resp.text}")
  683. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  684. def _refresh_firewall_session(self) -> bool:
  685. """
  686. 主动刷新页面以触发 Cloudflare 挑战并尝试通过
  687. """
  688. try:
  689. self._log("Refreshing page to trigger Cloudflare...")
  690. self.page.refresh()
  691. time.sleep(5)
  692. cf = CloudflareBypasser(self.page, log=self.config.debug)
  693. success = cf.bypass(max_retry=6)
  694. if success:
  695. title = self.page.title.lower()
  696. if "access denied" in title:
  697. return False
  698. time.sleep(2)
  699. return True
  700. return False
  701. except Exception as e:
  702. self._log(f"Error during firewall refresh: {e}")
  703. return False
  704. def _solve_recaptcha(self, params) -> str:
  705. """调用 VSCloudApi 解决 ReCaptcha"""
  706. key = params.get("apiToken")
  707. if not key:
  708. raise NotFoundError("Api-token required")
  709. submit_url = "https://api.capsolver.com/createTask"
  710. task = {
  711. "type": params.get("type"),
  712. "websiteURL": params.get("page"),
  713. "websiteKey": params.get("siteKey"),
  714. }
  715. if params.get("action"):
  716. task["pageAction"] = params.get("action")
  717. if params.get("proxy"):
  718. p = self.config.proxy
  719. task["proxyType"] = p.proto
  720. task["proxyAddress"] = p.ip
  721. task["proxyPort"] = p.port
  722. if p.username:
  723. task["proxyLogin"] = p.username
  724. task["proxyPassword"] = p.password
  725. payload = {"clientKey": key, "task": task}
  726. import requests as req
  727. r = req.post(submit_url, json=payload, timeout=20)
  728. if r.status_code != 200:
  729. raise BizLogicError(message="Failed to submit capsolver task")
  730. task_id = r.json().get("taskId")
  731. for _ in range(20):
  732. r = req.post("https://api.capsolver.com/getTaskResult", json={"clientKey": key, "taskId": task_id}, timeout=20)
  733. if r.status_code == 200:
  734. d = r.json()
  735. if d.get("status") == "ready":
  736. return d["solution"]["gRecaptchaResponse"]
  737. time.sleep(3)
  738. raise BizLogicError(message="Capsolver task timeout")
  739. def _parse_travel_groups(self, html_content) -> List[Dict]:
  740. groups = []
  741. js_pattern = r'\\"travelGroups\\":\s*(\[.*?\]),\\"availableCountriesToCreateGroups'
  742. js_match = re.search(js_pattern, html_content, re.DOTALL)
  743. if js_match:
  744. json_str = js_match.group(1).replace(r'\"', '"')
  745. data = json.loads(json_str)
  746. for g in data:
  747. groups.append({
  748. 'group_name': g.get('groupName'),
  749. 'group_number': g.get('formGroupId'),
  750. 'location': g.get('vacName'),
  751. 'submitted': g.get('submitted')
  752. })
  753. else:
  754. self._log('Parsed travel group page, but not found travelGroups')
  755. return groups
  756. def _parse_appointment_slots(self, html_content) -> List[Dict]:
  757. slots = []
  758. pattern = r'"availableAppointments\\":\s*(\[.*\]),\\"showFlexiAppointment'
  759. match = re.search(pattern, html_content, re.DOTALL)
  760. if match:
  761. json_str = match.group(1).replace(r'\"', '"')
  762. data = json.loads(json_str)
  763. for day in data:
  764. d_str = day.get('day')
  765. for s in day.get('slots', []):
  766. labels = s.get('labels', [])
  767. lbl = None
  768. if 'pta' in labels: lbl = 'pta'
  769. elif 'ptaw' in labels: lbl = 'ptaw'
  770. elif '' in labels: lbl = ''
  771. if lbl is not None:
  772. slots.append({
  773. 'date': d_str,
  774. 'time': s.get('time'),
  775. 'label': lbl
  776. })
  777. return slots
  778. def _handle_cookie_dialog(self, timeout: int = 3) -> bool:
  779. """
  780. 检测并处理 Osano Cookie 弹窗
  781. """
  782. try:
  783. dialog = self.page.ele('@aria-label=Cookie Consent Banner', timeout=timeout)
  784. if not dialog:
  785. return False
  786. target_btn = dialog.ele('tag:button@text():Save')
  787. if target_btn:
  788. self.mouse.human_click_ele(target_btn)
  789. self._log(f"Handle cookie window success")
  790. return True
  791. else:
  792. self._log(f"Found cookie window, but button not found")
  793. return False
  794. except Exception as e:
  795. self._log(f"Handle cookie window exception: {e}")
  796. return False
  797. def _check_page_is_session_expired_or_invalid(self, keyword, html: str) -> bool:
  798. if not html:
  799. self.is_healthy = False
  800. raise SessionExpiredOrInvalidError()
  801. html_lower = html.lower()
  802. if keyword.lower() not in html_lower:
  803. session_expire_or_invalid_indicators = [
  804. 'redirected automatically' in html_lower,
  805. 'login' in html_lower and 'password' in html_lower,
  806. 'session expired' in html_lower
  807. ]
  808. if any(session_expire_or_invalid_indicators):
  809. self.is_healthy = False
  810. raise SessionExpiredOrInvalidError()
  811. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  812. if not start_str or not end_str:
  813. return dates
  814. valid_dates = []
  815. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  816. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  817. for date_str in dates:
  818. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  819. if s_date <= curr_date <= e_date:
  820. valid_dates.append(date_str)
  821. random.shuffle(valid_dates)
  822. return valid_dates
  823. # --- 资源清理核心方法 ---
  824. def cleanup(self):
  825. """
  826. 销毁浏览器并彻底删除临时文件
  827. """
  828. if self.page:
  829. try:
  830. self.page.quit(force=True)
  831. except Exception:
  832. pass
  833. self.page = None
  834. if os.path.exists(self.root_workspace):
  835. for _ in range(3):
  836. try:
  837. time.sleep(0.2)
  838. shutil.rmtree(self.root_workspace, ignore_errors=True)
  839. break
  840. except Exception as e:
  841. self._log(f"Cleanup retry: {e}")
  842. time.sleep(0.5)
  843. if os.path.exists(self.root_workspace):
  844. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  845. if self.tunnel:
  846. try: self.tunnel.stop()
  847. except: pass
  848. self.tunnel = None
  849. def __del__(self):
  850. """
  851. 析构函数:当对象被垃圾回收时自动调用
  852. """
  853. self.cleanup()