tls_plugin.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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 = 15
  270. stuck_counter = 0
  271. last_url = ""
  272. session_created = False
  273. has_submitted_login = False
  274. 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']
  275. for step in range(max_steps):
  276. self.page.wait.doc_loaded()
  277. time.sleep(1)
  278. current_url = self.page.url
  279. current_title = self.page.title.lower()
  280. current_html_content = self.page.html
  281. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  282. if current_url == last_url:
  283. stuck_counter += 1
  284. else:
  285. last_url = current_url
  286. stuck_counter = 0
  287. # 在某个页面卡住3轮以上,直接重试
  288. if stuck_counter >= 3:
  289. self._log("[WARN] Page stucked, try to refresh...")
  290. self.page.refresh()
  291. self.page.wait.load_start(timeout=5)
  292. stuck_counter = 0
  293. continue
  294. server_error_indicators = [
  295. "502 Bad Gateway",
  296. "503 Service Temporarily Unavailable",
  297. ]
  298. # 网络出现故障,直接重试
  299. if any(err in current_html_content for err in server_error_indicators):
  300. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  301. time.sleep(2)
  302. self.page.refresh()
  303. self.page.wait.load_start(timeout=5)
  304. continue
  305. # 特征1: 必须是 <p> 标签,且包含指定文案 (绝对不会匹配到 <script> 标签里的字典)
  306. spa_error_p = self.page.ele('xpath://p[contains(text(), "It looks like something went wrong")]', timeout=0.1)
  307. # 特征2: 必须是 <div> 标签,且直接包含 "Error code:" 文本
  308. error_code_div = self.page.ele('xpath://div[contains(text(), "Error code:")]', timeout=0.1)
  309. if spa_error_p or error_code_div:
  310. extracted_code = "Unknown"
  311. if error_code_div:
  312. span_ele = error_code_div.ele('tag:span', timeout=0.1)
  313. if span_ele:
  314. extracted_code = span_ele.text
  315. self._log(f"[WARN] Frontend application error page detected (Error Code: {extracted_code}). Triggering fallback page refresh (Step: {step})...")
  316. time.sleep(2)
  317. self.page.refresh()
  318. self.page.wait.load_start(timeout=5)
  319. continue
  320. cloudflare_blocked_indicators = [
  321. "Sorry, you have been blocked" in current_html_content,
  322. "You are being rate limited" in current_html_content,
  323. "Cloudflare Ray ID" in current_html_content
  324. ]
  325. if any(cloudflare_blocked_indicators):
  326. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  327. # 遇到五秒盾先绕盾
  328. if "just a moment" in current_title:
  329. cf_bypasser.bypass(max_retry=3)
  330. time.sleep(3)
  331. continue
  332. if "waitting room" in current_title:
  333. cf_bypasser.handle_waiting_room()
  334. time.sleep(3)
  335. continue
  336. # 如果语言不匹配, 切换语言到英语
  337. matched_lang = next((lang for lang in other_langs if lang in current_url), None)
  338. if matched_lang:
  339. current_url = current_url.replace(matched_lang, 'en-us')
  340. self.page.get(current_url)
  341. self.page.wait.load_start(timeout=3)
  342. continue
  343. # 到达终极目标页面 (成功退出条件)
  344. if "appointment-booking" in current_url or self.page.ele('tag:button@text():Book your appointment', timeout=1):
  345. btn_selector = 'tag:button@text():Book your appointment'
  346. if self.page.wait.ele_displayed(btn_selector, timeout=10):
  347. self._handle_cookie_dialog()
  348. self.session_create_time = time.time()
  349. self._log("✅ Login & Navigation Success! Reached appointment-booking.")
  350. session_created = True
  351. break
  352. # 页面发生react渲染错误
  353. if 'a client-side exception has occurred while loading' in current_html_content:
  354. self.page.refresh()
  355. self.page.wait.load_start(timeout=3)
  356. continue
  357. # 改签的情况
  358. if '/workflow/application-summary' in current_url:
  359. change_btn_sel = 'tag:button@@text():Change'
  360. self.page.wait.ele_displayed(change_btn_sel, timeout=10)
  361. self.page.ele(change_btn_sel).click(by_js=True)
  362. confirm_btn_sel = 'tag:button@@text():Yes'
  363. self.page.wait.ele_displayed(confirm_btn_sel, timeout=5)
  364. self.page.ele(confirm_btn_sel).click(by_js=True)
  365. self.page.wait.load_start(timeout=5)
  366. continue
  367. # 遇到没有申请人的拦截页 (致命错误退出条件)
  368. no_applicant_indicators = [
  369. "Add a new applicant" in current_html_content,
  370. "You have not yet added an applicant" in current_html_content,
  371. "applicants-information" in current_url
  372. ]
  373. if any(no_applicant_indicators):
  374. raise BizLogicError(message="No applicant added. Cannot proceed to booking.")
  375. # 首页/登录入口页 -> 需要点击进入登录
  376. if tls_url in current_url:
  377. if self.page.ele("tag:a@@href:login", timeout=1) and not self.page.ele('tag:label@@text():Email', timeout=1):
  378. self._log("State: Login Portal. Clicking login link...")
  379. login_link = self.page.ele("tag:a@@href:login")
  380. self.mouse.human_click_ele(login_link)
  381. self.page.wait.load_start(timeout=3)
  382. continue
  383. if self.page.ele("tag:svg@@data-testid=user-button", timeout=1):
  384. self._log("State: Already login, logout now...")
  385. user_btn = self.page.ele("tag:svg@@data-testid=user-button")
  386. self.mouse.human_click_ele(user_btn)
  387. time.sleep(1.5)
  388. logout_btn = self.page.ele("#logout")
  389. self.mouse.human_click_ele(logout_btn)
  390. self.page.wait.load_start(timeout=3)
  391. self.page.get(tls_url)
  392. self.page.wait.load_start(timeout=3)
  393. continue
  394. # 真正的登录表单页
  395. if self.page.ele('tag:label@@text():Email', timeout=1) and not has_submitted_login:
  396. self._log("State: Login Form. Processing credentials and Captcha...")
  397. recaptchav2_token = ""
  398. if not captcha_future and (self.page.ele('.g-recaptcha') or self.page.ele('xpath://iframe[contains(@src, "recaptcha")]')):
  399. rec_iframe = self.page.ele('xpath://iframe[contains(@src, "recaptcha")]')
  400. rec_iframe_src = rec_iframe.attr('src')
  401. rec_parsed = urlparse(rec_iframe_src)
  402. rec_params = parse_qs(rec_parsed.query)
  403. rec_sitekey = rec_params.get("k", [None])[0]
  404. rec_size = rec_params.get("size", [None])[0]
  405. if 'normal' == rec_size:
  406. self._log(f"Found dynamic sitekey={rec_sitekey}. Starting async Captcha solver...")
  407. rc_params = {
  408. "type": "ReCaptchaV2TaskProxyLess",
  409. "page": current_url,
  410. "siteKey": rec_sitekey,
  411. "apiToken": self.free_config.get("capsolver_key", "")
  412. }
  413. captcha_future = captcha_executor.submit(self._solve_recaptcha, rc_params)
  414. username = self.config.account.username
  415. password = self.config.account.password
  416. input_ele = self.page.ele('tag:label@@text():Email').next()
  417. self.mouse.human_click_ele(input_ele)
  418. time.sleep(random.uniform(0.2, 0.6))
  419. self.keyboard.type_text(username, humanize=True)
  420. time.sleep(random.uniform(0.5, 1.2))
  421. input_ele = self.page.ele('tag:label@@text():Password').next()
  422. self.mouse.human_click_ele(input_ele)
  423. time.sleep(random.uniform(0.2, 0.6))
  424. self.keyboard.type_text(password, humanize=True)
  425. # 注入 Token
  426. if captcha_future:
  427. self._log("Waiting for background Captcha result...")
  428. try:
  429. # 设一个合理的超时,防止死锁
  430. recaptchav2_token = captcha_future.result(timeout=120)
  431. self._log("Background Captcha solved successfully!")
  432. except Exception as e:
  433. raise BizLogicError(f"Captcha solving failed or timed out: {e}")
  434. # 注入 Token
  435. if recaptchav2_token:
  436. inject_js = f"var g = document.getElementById('g-recaptcha-response'); if(g) {{ g.value = '{recaptchav2_token}'; }}"
  437. self.page.run_js(inject_js)
  438. time.sleep(random.uniform(0.5, 1.0))
  439. self._log("Submitting Login...")
  440. login_btn = self.page.ele('tag:button@@text():Login')
  441. self.mouse.human_click_ele(login_btn)
  442. has_submitted_login = True
  443. self.page.wait.load_start(timeout=5)
  444. continue
  445. # Travel Groups 页面
  446. if "travel-groups" in current_url:
  447. self._log("State: Travel Groups. Selecting targeted group...")
  448. groups = self._parse_travel_groups(current_html_content)
  449. location = self.free_config.get('location')
  450. self.travel_group = next((g for g in groups if location in g['location']), None)
  451. if not self.travel_group or not self.travel_group.get("submitted"):
  452. self._save_screenshot("group_not_found")
  453. raise NotFoundError(f"Group not found for {location}")
  454. formgroup_id = self.travel_group.get('group_number')
  455. btn_selector = f'tag:button@@name=formGroupId@@value={formgroup_id}'
  456. if self.page.wait.eles_loaded(btn_selector, timeout=10):
  457. buttons = self.page.eles(btn_selector)
  458. select_btn = next((btn for btn in reversed(buttons) if btn.rect.size[0] > 0 and btn.rect.size[1] > 0), None)
  459. if select_btn:
  460. time.sleep(random.uniform(0.5, 1.2))
  461. self.mouse.human_click_ele(select_btn)
  462. self.page.wait.load_start(timeout=3)
  463. continue
  464. else:
  465. self._log("[WARN] Select button found but not visible.")
  466. else:
  467. self._log(f"[WARN] Wait timeout for group button {formgroup_id}")
  468. # 中间过渡页,需点击 "Book Appointment" 继续往下走
  469. if self.page.ele('#book-appointment-btn', timeout=1):
  470. self._log("State: Intermediate Dashboard. Clicking Book Appointment button...")
  471. self.mouse.human_click_ele(self.page.ele('#book-appointment-btn'))
  472. self.page.wait.load_start(timeout=3)
  473. continue
  474. # 登录失败校验 或 未知加载状态
  475. if "login-actions" in current_url and has_submitted_login:
  476. self._log("Waiting on login-actions... (Might be authenticating or invalid credentials)")
  477. time.sleep(2)
  478. if self.page.ele('text:Invalid username or password', timeout=1): # 假设网页上有错误提示
  479. raise BizLogicError(message="Login Failed! Invalid credentials or Captcha rejected.")
  480. continue
  481. self._log("State: Transitioning or Unknown. Waiting 2 seconds...")
  482. time.sleep(2)
  483. # 如果处于某些特定的复杂页面且久久不动,尝试主动刷新
  484. if step > 0 and step % 4 == 0:
  485. self._log("[WARN] Unknown state persisted for too long. Attempting fallback refresh...")
  486. self.page.refresh()
  487. self.page.wait.load_start(timeout=3)
  488. if not session_created:
  489. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  490. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  491. res = VSQueryResult()
  492. res.success = False
  493. slots = []
  494. self._log(f"Executing silent JS fetch...")
  495. resp = self._perform_request("GET", self.page.url, retry_count=0)
  496. self._check_page_is_session_expired_or_invalid('Book your appointment', resp.text)
  497. slots = self._parse_appointment_slots(resp.text)
  498. if slots:
  499. res.success = True
  500. earliest_date = slots[0]["date"]
  501. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  502. res.availability_status = AvailabilityStatus.Available
  503. res.earliest_date = earliest_dt
  504. date_map: dict[datetime, list[TimeSlot]] = {}
  505. for s in slots:
  506. date_str = s["date"]
  507. dt = datetime.strptime(date_str, "%Y-%m-%d")
  508. date_map.setdefault(dt, []).append(
  509. TimeSlot(time=s["time"], label=str(s.get("label", "")))
  510. )
  511. res.availability = [DateAvailability(date=d, times=slots) for d, slots in date_map.items()]
  512. self._log(f"Slot Found! earliest_date={earliest_date}, size={len(slots)}")
  513. else:
  514. self._log("No slots available.")
  515. res.success = False
  516. res.availability_status = AvailabilityStatus.NoneAvailable
  517. # TODO(TEST): 临时测试预约提交
  518. if configure.TLS_TEST_BOOK_AFTER_QUERY:
  519. test_date = "2026-06-10"
  520. test_time = "09:00"
  521. test_label = ""
  522. test_dt = datetime.strptime(test_date, "%Y-%m-%d")
  523. query_res = VSQueryResult()
  524. query_res.success = True
  525. query_res.availability_status = AvailabilityStatus.Available
  526. query_res.earliest_date = test_dt
  527. query_res.availability = [
  528. DateAvailability(
  529. date=test_dt,
  530. times=[TimeSlot(time=test_time, label=test_label)]
  531. )
  532. ]
  533. self._log(f"[TEST] using fixed June slot: {test_date} {test_time} {test_label}")
  534. test_userinput = {
  535. "support_pta": False,
  536. "expected_end_date": "2100-01-01",
  537. "expected_start_date": "2000-01-01"
  538. }
  539. try:
  540. self.book(query_res, test_userinput)
  541. except Exception as e:
  542. self._log(f"[TEST] book() after query failed: {e}")
  543. self.is_healthy = False
  544. return res
  545. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  546. res = VSBookResult()
  547. res.success = False
  548. exp_start = user_inputs.get('expected_start_date', '')
  549. exp_end = user_inputs.get('expected_end_date', '')
  550. support_pta = user_inputs.get('support_pta', True)
  551. target_labels = ['']
  552. if support_pta:
  553. target_labels.append('pta')
  554. available_dates_str =[
  555. da.date.strftime("%Y-%m-%d")
  556. for da in slot_info.availability if da.date
  557. ]
  558. valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
  559. if not valid_dates_list:
  560. raise NotFoundError(message="No dates match user constraints")
  561. all_possible_slots =[]
  562. for da in slot_info.availability:
  563. if not da.date:
  564. continue
  565. date_str = da.date.strftime("%Y-%m-%d")
  566. if date_str in valid_dates_list:
  567. for t in da.times:
  568. if t.label in target_labels:
  569. all_possible_slots.append({
  570. "date": date_str,
  571. "time_obj": t,
  572. "label": t.label
  573. })
  574. if not all_possible_slots:
  575. raise NotFoundError(message="No suitable slot found (after label filtering)")
  576. selected_slot = random.choice(all_possible_slots)
  577. selected_date = selected_slot["date"]
  578. selected_time = selected_slot["time_obj"]
  579. selected_label = selected_slot["label"]
  580. self._log(f"Found {len(all_possible_slots)} valid slots. selected slot: {selected_date} {selected_time.time} {selected_label}")
  581. self.page.listen.start('/workflow/appointment-booking', method='POST')
  582. js_update_form = f"""
  583. try {{
  584. const buttons = Array.from(document.querySelectorAll('button[type="submit"]'));
  585. const submitBtn = buttons.find(btn => {{
  586. return btn.textContent.trim().toLowerCase().includes('book your appointment');
  587. }});
  588. if (!submitBtn) return 'Submit button not found';
  589. const form = submitBtn.closest('form');
  590. if (!form) return 'Correct form not found';
  591. function setReactValue(input, value) {{
  592. if (!input) return;
  593. input.value = value;
  594. }}
  595. setReactValue(form.querySelector('input[name="date"]'), '{selected_date}');
  596. setReactValue(form.querySelector('input[name="time"]'), '{selected_time.time}');
  597. setReactValue(form.querySelector('input[name="appointmentLabel"]'), '{selected_label}');
  598. submitBtn.removeAttribute('disabled');
  599. submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  600. return 'form_updated';
  601. }} catch (e) {{
  602. return e.toString();
  603. }}
  604. """
  605. update_res = self.page.run_js(js_update_form)
  606. self._log(f"Form update triggered: {update_res}")
  607. if update_res != 'form_updated':
  608. raise BizLogicError(message=f"Failed to update form: {update_res}")
  609. submit_btn = self.page.ele('tag:button@@type=submit@@text():Book your appointment')
  610. if not submit_btn:
  611. raise BizLogicError(message="Submit button not found for mouse click")
  612. self._log("Moving mouse to submit button and clicking")
  613. self.mouse.human_click_ele(submit_btn)
  614. packet = self.page.listen.wait(timeout=10)
  615. if not packet:
  616. raise BizLogicError(message='Listening data failed')
  617. self.page.listen.stop()
  618. self._log(f"URL: {packet.url}")
  619. self._log(f"POST Body: {packet.request.postData}")
  620. self._log(f"POST Resp: {packet.response.body}")
  621. self._log("Waiting for Next.js to process the form submission...")
  622. for _ in range(10):
  623. try:
  624. current_page_url = self.page.url
  625. current_page_html = self.page.html
  626. appointment_confirmation_indicators = [
  627. "order-summary" in current_page_url,
  628. "partner-services" in current_page_url,
  629. "appointment-confirmation" in current_page_url,
  630. "Change my appointment" in current_page_html,
  631. "Book a new appointment" in current_page_html,
  632. ]
  633. if any(appointment_confirmation_indicators):
  634. self._log(f"✅ BOOKING SUCCESS! Redirected to: {current_page_url}")
  635. res.success = True
  636. res.label = selected_label
  637. res.book_date = selected_date
  638. res.book_time = selected_time.time
  639. self._save_screenshot("book_slot_success")
  640. break
  641. toast_selector = 'tag:div@role=alert'
  642. toast_ele = self.page.ele(toast_selector, timeout=0.5)
  643. if toast_ele:
  644. error_msg = toast_ele.text
  645. self._log(f"❌ BOOKING FAILED! Detected popup: {error_msg}")
  646. break
  647. time.sleep(0.5)
  648. except Exception:
  649. pass
  650. return res
  651. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  652. """
  653. 在浏览器上下文中注入 JS 执行 Fetch
  654. """
  655. if not self.page:
  656. raise BizLogicError("Browser not initialized")
  657. if params:
  658. from urllib.parse import urlencode
  659. if '?' in url:
  660. url += '&' + urlencode(params)
  661. else:
  662. url += '?' + urlencode(params)
  663. fetch_options = {
  664. "method": method.upper(),
  665. "headers": headers or {},
  666. "credentials": "include"
  667. }
  668. # Body 处理
  669. if json_data:
  670. fetch_options['body'] = json.dumps(json_data)
  671. fetch_options['headers']['Content-Type'] = 'application/json'
  672. elif data:
  673. if isinstance(data, dict):
  674. from urllib.parse import urlencode
  675. fetch_options['body'] = urlencode(data)
  676. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  677. else:
  678. fetch_options['body'] = data
  679. js_script = f"""
  680. const url = "{url}";
  681. const options = {json.dumps(fetch_options)};
  682. return fetch(url, options)
  683. .then(async response => {{
  684. const text = await response.text();
  685. const headers = {{}};
  686. response.headers.forEach((value, key) => headers[key] = value);
  687. return {{
  688. status: response.status,
  689. body: text,
  690. headers: headers,
  691. url: response.url
  692. }};
  693. }})
  694. .catch(error => {{
  695. return {{
  696. status: 0,
  697. body: error.toString(),
  698. headers: {{}},
  699. url: url
  700. }};
  701. }});
  702. """
  703. res_dict = self.page.run_js(js_script, timeout=30)
  704. resp = BrowserResponse(res_dict)
  705. if resp.status_code == 200:
  706. return resp
  707. elif resp.status_code == 401:
  708. self.is_healthy = False
  709. raise SessionExpiredOrInvalidError()
  710. # 将 403 和 429 合并,共享绕盾重试逻辑
  711. elif resp.status_code in (403, 429):
  712. if retry_count < 2:
  713. # 动态打印是 403 还是 429
  714. self._log(f"HTTP {resp.status_code} Detected. Cloudflare block or rate limit? Attempting refresh (Try {retry_count+1}/2)...")
  715. if self._refresh_firewall_session():
  716. self._log("Firewall session refreshed. Retrying request...")
  717. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  718. else:
  719. self._log("Failed to refresh firewall session.")
  720. # 如果重试 2 次仍然失败,或者刷新防火墙失败,则按原来的逻辑抛出各自的异常
  721. if resp.status_code == 403:
  722. raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
  723. else:
  724. self.is_healthy = False
  725. # 注意:保留了原代码中 RateLimiteddError 的拼写(双d)
  726. raise RateLimiteddError(f"HTTP 429: {resp.text[:100]}")
  727. else:
  728. if resp.status_code == 0:
  729. raise BizLogicError(f"Network Error: {resp.text}")
  730. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  731. def _refresh_firewall_session(self) -> bool:
  732. """
  733. 主动刷新页面以触发 Cloudflare 挑战并尝试通过
  734. """
  735. try:
  736. self._log("Refreshing page to trigger Cloudflare...")
  737. self.page.refresh()
  738. time.sleep(5)
  739. cf = CloudflareBypasser(self.page, log=self.config.debug)
  740. success = cf.bypass(max_retry=6)
  741. if success:
  742. title = self.page.title.lower()
  743. if "access denied" in title:
  744. return False
  745. time.sleep(2)
  746. return True
  747. return False
  748. except Exception as e:
  749. self._log(f"Error during firewall refresh: {e}")
  750. return False
  751. def _solve_recaptcha(self, params) -> str:
  752. """调用 VSCloudApi 解决 ReCaptcha"""
  753. key = params.get("apiToken")
  754. if not key:
  755. raise NotFoundError("Api-token required")
  756. submit_url = "https://api.capsolver.com/createTask"
  757. task = {
  758. "type": params.get("type"),
  759. "websiteURL": params.get("page"),
  760. "websiteKey": params.get("siteKey"),
  761. }
  762. if params.get("action"):
  763. task["pageAction"] = params.get("action")
  764. if params.get("proxy"):
  765. p = self.config.proxy
  766. task["proxyType"] = p.proto
  767. task["proxyAddress"] = p.ip
  768. task["proxyPort"] = p.port
  769. if p.username:
  770. task["proxyLogin"] = p.username
  771. task["proxyPassword"] = p.password
  772. payload = {"clientKey": key, "task": task}
  773. import requests as req
  774. r = req.post(submit_url, json=payload, timeout=20)
  775. if r.status_code != 200:
  776. raise BizLogicError(message="Failed to submit capsolver task")
  777. task_id = r.json().get("taskId")
  778. for _ in range(20):
  779. r = req.post("https://api.capsolver.com/getTaskResult", json={"clientKey": key, "taskId": task_id}, timeout=20)
  780. if r.status_code == 200:
  781. d = r.json()
  782. if d.get("status") == "ready":
  783. return d["solution"]["gRecaptchaResponse"]
  784. time.sleep(3)
  785. raise BizLogicError(message="Capsolver task timeout")
  786. def _parse_travel_groups(self, html_content) -> List[Dict]:
  787. groups = []
  788. js_pattern = r'\\"travelGroups\\":\s*(\[.*?\]),\\"availableCountriesToCreateGroups'
  789. js_match = re.search(js_pattern, html_content, re.DOTALL)
  790. if js_match:
  791. json_str = js_match.group(1).replace(r'\"', '"')
  792. data = json.loads(json_str)
  793. for g in data:
  794. groups.append({
  795. 'group_name': g.get('groupName'),
  796. 'group_number': g.get('formGroupId'),
  797. 'location': g.get('vacName'),
  798. 'submitted': g.get('submitted')
  799. })
  800. else:
  801. self._log('Parsed travel group page, but not found travelGroups')
  802. return groups
  803. def _parse_appointment_slots(self, html_content) -> List[Dict]:
  804. slots = []
  805. pattern = r'"availableAppointments\\":\s*(\[.*\]),\\"showFlexiAppointment'
  806. match = re.search(pattern, html_content, re.DOTALL)
  807. if match:
  808. json_str = match.group(1).replace(r'\"', '"')
  809. data = json.loads(json_str)
  810. for day in data:
  811. d_str = day.get('day')
  812. for s in day.get('slots', []):
  813. labels = s.get('labels', [])
  814. lbl = None
  815. if 'pta' in labels: lbl = 'pta'
  816. elif 'ptaw' in labels: lbl = 'ptaw'
  817. elif '' in labels: lbl = ''
  818. if lbl is not None:
  819. slots.append({
  820. 'date': d_str,
  821. 'time': s.get('time'),
  822. 'label': lbl
  823. })
  824. return slots
  825. def _handle_cookie_dialog(self, timeout: int = 3) -> bool:
  826. """
  827. 检测并处理 Osano Cookie 弹窗
  828. """
  829. try:
  830. dialog = self.page.ele('@aria-label=Cookie Consent Banner', timeout=timeout)
  831. if not dialog:
  832. return False
  833. target_btn = dialog.ele('tag:button@text():Save')
  834. if not target_btn:
  835. target_btn = dialog.ele('tag:button@text():Accept')
  836. if target_btn:
  837. self.mouse.human_click_ele(target_btn)
  838. self._log(f"Handle cookie window success")
  839. return True
  840. else:
  841. self._log(f"Found cookie window, but button not found")
  842. return False
  843. except Exception as e:
  844. self._log(f"Handle cookie window exception: {e}")
  845. return False
  846. def _check_page_is_session_expired_or_invalid(self, keyword, html: str) -> bool:
  847. if not html:
  848. self.is_healthy = False
  849. raise SessionExpiredOrInvalidError()
  850. html_lower = html.lower()
  851. if keyword.lower() not in html_lower:
  852. session_expire_or_invalid_indicators = [
  853. 'redirected automatically' in html_lower,
  854. 'login' in html_lower and 'password' in html_lower,
  855. 'session expired' in html_lower
  856. ]
  857. if any(session_expire_or_invalid_indicators):
  858. self.is_healthy = False
  859. raise SessionExpiredOrInvalidError()
  860. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  861. if not start_str or not end_str:
  862. return dates
  863. valid_dates = []
  864. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  865. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  866. for date_str in dates:
  867. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  868. if s_date <= curr_date <= e_date:
  869. valid_dates.append(date_str)
  870. random.shuffle(valid_dates)
  871. return valid_dates
  872. # --- 资源清理核心方法 ---
  873. def cleanup(self):
  874. """
  875. 销毁浏览器并彻底删除临时文件
  876. """
  877. if self.page:
  878. try:
  879. self.page.quit(force=True)
  880. except Exception:
  881. pass
  882. self.page = None
  883. if os.path.exists(self.root_workspace):
  884. for _ in range(3):
  885. try:
  886. time.sleep(0.2)
  887. shutil.rmtree(self.root_workspace, ignore_errors=True)
  888. break
  889. except Exception as e:
  890. self._log(f"Cleanup retry: {e}")
  891. time.sleep(0.5)
  892. if os.path.exists(self.root_workspace):
  893. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  894. if self.tunnel:
  895. try: self.tunnel.stop()
  896. except: pass
  897. self.tunnel = None
  898. def __del__(self):
  899. """
  900. 析构函数:当对象被垃圾回收时自动调用
  901. """
  902. self.cleanup()