tls_plugin.py 43 KB

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