tls_plugin.py 33 KB

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