tls_plugin.py 34 KB

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