tls_plugin.py 41 KB

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