tls_plugin.py 39 KB

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