ita_plugin.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. import time
  2. import json
  3. import random
  4. import socket
  5. import uuid
  6. import shutil
  7. import re
  8. import os
  9. import base64
  10. from datetime import datetime
  11. from typing import List, Dict, Optional, Any, Callable
  12. from urllib.parse import urlencode, urlparse
  13. # DrissionPage 核心
  14. from DrissionPage import ChromiumPage, ChromiumOptions
  15. from vs_plg import IVSPlg
  16. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  17. from toolkit.proxy_tunnel import ProxyTunnel
  18. from toolkit.vs_cloud_api import VSCloudApi
  19. from utils.mouse import HumanMouse
  20. from utils.keyboard import HumanKeyboard
  21. from utils.fingerprint_utils import FingerprintGenerator
  22. class BrowserResponse:
  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: return {}
  33. try: self._json = json.loads(self.text)
  34. except: self._json = {}
  35. return self._json
  36. # ==========================================
  37. # 2. ItaPlugin 核心逻辑
  38. # ==========================================
  39. class ItaPlugin(IVSPlg):
  40. def __init__(self, group_id: str):
  41. self.group_id = group_id
  42. self.config: Optional[VSPlgConfig] = None
  43. self.free_config: Dict[str, Any] = {}
  44. self.is_healthy = True
  45. self.logger = None
  46. self.page: Optional[ChromiumPage] = None
  47. # Prenotami 特有配置
  48. self._service_id = 0
  49. self._host = 'https://prenotami.esteri.it'
  50. # --- [核心修改] 并发隔离与资源管理 ---
  51. # 生成唯一实例 ID
  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. # 定义子目录:代理插件目录 & 浏览器用户数据目录
  55. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  56. # 确保根目录存在 (子目录由具体逻辑创建)
  57. if not os.path.exists(self.root_workspace):
  58. os.makedirs(self.root_workspace)
  59. # 持有隧道实例
  60. self.tunnel = None
  61. self.session_create_time: float = 0
  62. def set_log(self, logger: Callable[[str], None]) -> None:
  63. self.logger = logger
  64. def _log(self, message):
  65. if self.logger:
  66. self.logger(f'[ItaPlugin] [{self.group_id}] {message}')
  67. else:
  68. print(f'[ItaPlugin] [{self.group_id}] {message}')
  69. def set_config(self, config: VSPlgConfig):
  70. self.config = config
  71. self.free_config = config.free_config or {}
  72. # Service ID (e.g., 1321 for Ireland, 5059 for Guangzhou)
  73. self._service_id = self.free_config.get('service_id', 0)
  74. def keep_alive(self):
  75. pass
  76. def health_check(self) -> bool:
  77. if not self.is_healthy or not self.page:
  78. return False
  79. try:
  80. if not self.page.run_js("return 1;"):
  81. return False
  82. except:
  83. return False
  84. if self.config.session_max_life > 0:
  85. if time.time() - self.session_create_time > self.config.session_max_life:
  86. self._log("Session expired.")
  87. return False
  88. return True
  89. # -------------------------------------------------------------
  90. # 1. Create Session (Login)
  91. # -------------------------------------------------------------
  92. def create_session(self):
  93. """
  94. 全浏览器登录流程:
  95. 1. 启动浏览器
  96. 2. 解决 ReCaptcha
  97. 3. 登录并维持 Session
  98. """
  99. self._log(f"Initializing Session (ID: {self.instance_id})...")
  100. co = ChromiumOptions()
  101. def get_free_port():
  102. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  103. s.bind(('', 0))
  104. return s.getsockname()[1]
  105. debug_port = get_free_port()
  106. self._log(f"Assigned Debug Port: {debug_port}")
  107. co.set_user_data_path(self.user_data_path)
  108. chrome_path = os.getenv("CHROME_BIN")
  109. if chrome_path and os.path.exists(chrome_path):
  110. co.set_paths(browser_path=chrome_path)
  111. if self.config.proxy and self.config.proxy.ip:
  112. p = self.config.proxy
  113. if p.username and p.password:
  114. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  115. self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
  116. local_proxy = self.tunnel.start()
  117. self._log(f"Tunnel started at {local_proxy}")
  118. co.set_argument(f'--proxy-server={local_proxy}')
  119. else:
  120. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  121. co.set_argument(f'--proxy-server={proxy_str}')
  122. else:
  123. self._log("[WARN] No proxy configured!")
  124. fingerprint_gen = FingerprintGenerator()
  125. specific_fp = fingerprint_gen.generate(self.config.account.username)
  126. self._log(f'browser fingerprint={specific_fp}')
  127. co.headless(False)
  128. co.set_argument('--no-sandbox')
  129. co.set_argument('--disable-gpu')
  130. co.set_argument('--disable-dev-shm-usage')
  131. co.set_argument('--window-size=1920,1080')
  132. co.set_argument('--disable-blink-features=AutomationControlled')
  133. co.set_argument(f"--fingerprint={specific_fp.get('seed')}")
  134. co.set_argument(f"--fingerprint-platform={specific_fp.get('platform')}")
  135. co.set_argument(f"--fingerprint-brand={specific_fp.get('brand')}")
  136. try:
  137. self.page = ChromiumPage(co)
  138. login_url = f"{self._host}/Home"
  139. self._log(f"Navigating to {login_url}")
  140. self.page.get(login_url)
  141. self._log("Init humanize tools...")
  142. self.mouse = HumanMouse(self.page, debug=True)
  143. self.keyboard = HumanKeyboard(self.page)
  144. self._log("Random mouse start position...")
  145. viewport_width = self.page.rect.viewport_size[0]
  146. viewport_height = self.page.rect.viewport_size[1]
  147. init_x = random.randint(10, viewport_width - 10)
  148. init_y = random.randint(10, viewport_height - 10)
  149. self.mouse.move(init_x, init_y)
  150. # 等待登录框
  151. if not self.page.wait.ele_displayed('#login-email', timeout=20):
  152. raise BizLogicError("Login page not loaded")
  153. # 填充用户名密码
  154. self.mouse.human_click_ele(self.page.ele('#login-email'))
  155. self.keyboard.type_text(self.config.account.username)
  156. self.mouse.human_click_ele(self.page.ele('#login-password'))
  157. self.keyboard.type_text(self.config.account.password)
  158. # 先定位
  159. self._log("Locating Login button...")
  160. login_btn = self.page.ele('#captcha-trigger')
  161. self.mouse.human_click_ele(login_btn)
  162. self._log("Login button clicked.")
  163. # 等待 URL 变化或特定元素出现
  164. # 成功通常跳转到 /UserArea, 失败则留在 /Home
  165. end_time = time.time() + 45
  166. login_success = False
  167. while time.time() < end_time:
  168. time.sleep(1)
  169. curr_url = self.page.url
  170. # 成功特征
  171. if "/UserArea" in curr_url or "/Services" in curr_url:
  172. login_success = True
  173. break
  174. # 失败特征
  175. if self.page.ele('.validation-summary-errors') or self.page.ele('.field-validation-error'):
  176. err_text = self.page.ele('.validation-summary-errors').text if self.page.ele('.validation-summary-errors') else "Unknown validation error"
  177. raise PermissionDeniedError(f"Login Failed: {err_text}")
  178. # 检查是否有弹窗错误
  179. if "Home" in curr_url and self.page.ele('#logoutForm'):
  180. # 有时候虽然在 Home 但出现了 Logout 按钮,也算成功
  181. login_success = True
  182. break
  183. if not login_success:
  184. # 截图保留现场
  185. # self.page.get_screenshot(path="login_fail.jpg")
  186. raise BizLogicError("Login Failed: Timeout waiting for redirect (Captcha score too low?)")
  187. self._log("Login Successful.")
  188. self.session_create_time = time.time()
  189. except Exception as e:
  190. self._log(f"Create Session Failed: {e}")
  191. self.cleanup()
  192. raise e
  193. # -------------------------------------------------------------
  194. # 2. Query Availability
  195. # -------------------------------------------------------------
  196. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  197. res = VSQueryResult()
  198. res.success = False
  199. res.availability_status = AvailabilityStatus.NoneAvailable
  200. if not self._service_id:
  201. raise BizLogicError("Service ID not configured")
  202. # 1. 检查 Slot 是否可用 (Check Availability Endpoint)
  203. check_url = f"{self._host}/Services/Booking/{self._service_id}"
  204. # 使用 Fetch 发起检查请求
  205. resp = self._perform_request("GET", check_url, headers={
  206. "Referer": f"{self._host}/Services",
  207. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  208. })
  209. # 302 跳转处理逻辑
  210. if resp.status_code == 200:
  211. # 200 表示进入了预约页,有号
  212. self._log("Slot Check: 200 OK (Availability Detected)")
  213. pass
  214. elif "BookingCalendar" in resp.url: # 或者是被重定向到了 Calendar
  215. self._log("Slot Check: Redirected to Calendar (Availability Detected)")
  216. pass
  217. else:
  218. # 被重定向回 Home 或 Service,说明没号或 Session 过期
  219. if "Home" in resp.url or "Login" in resp.url:
  220. self.is_healthy = False
  221. raise SessionExpiredOrInvalidError("Session expired during query")
  222. self._log("Slot Check: No availability (Redirected back)")
  223. return res
  224. # 2. 查询月份 (Query Month)
  225. # 默认查询当月,或者配置的月份
  226. tar_dates = self.free_config.get("target_dates", [])
  227. if not tar_dates:
  228. # 默认查下个月
  229. next_month = datetime.now().replace(day=28) + datetime.timedelta(days=4)
  230. tar_dates = [next_month.strftime("%Y-%m-%d")]
  231. all_slots = []
  232. # Prenotami 需要先 retrieve server info
  233. self._perform_request("GET", f"{self._host}/BookingCalendar/RetrieveServerInfo")
  234. for date_str in tar_dates:
  235. # 构造月份格式 2026-01-05 -> 2026-01-01 (API 需要)
  236. try:
  237. dt = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
  238. except:
  239. try:
  240. dt = datetime.strptime(date_str, "%Y-%m-%d")
  241. except:
  242. dt = datetime.now()
  243. # API 需要格式: 2025-11-05T... 格式的字符串作为 selectedDay
  244. # 实际上 RetrieveCalendarAvailability 只需要由前端日历控件触发的格式
  245. # 查询日历 API
  246. cal_url = f"{self._host}/BookingCalendar/RetrieveCalendarAvailability"
  247. cal_payload = {
  248. "_Servizio": str(self._service_id),
  249. "selectedDay": date_str # 原样传配置里的 ISO 串
  250. }
  251. resp_cal = self._perform_request("POST", cal_url, json_data=cal_payload)
  252. if resp_cal.status_code != 200: continue
  253. # 解析有效日期
  254. valid_days = self._parse_valid_days(resp_cal.text)
  255. self._log(f"Valid days for {date_str}: {valid_days}")
  256. if valid_dates:
  257. res.success = True
  258. res.availability_status = AvailabilityStatus.Available
  259. earliest_date = valid_dates[0]
  260. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  261. res.earliest_date = earliest_dt
  262. for day in valid_days:
  263. # 查询具体 Slot
  264. slot_url = f"{self._host}/BookingCalendar/RetrieveTimeSlots"
  265. slot_payload = {
  266. "selectedDay": day, # YYYY-MM-DD
  267. "idService": str(self._service_id)
  268. }
  269. resp_slot = self._perform_request("POST", slot_url, json_data=slot_payload)
  270. time_slots = self._parse_time_slots(resp_slot.text)
  271. ts_list = []
  272. if time_slots:
  273. # 转换结构
  274. for ts in time_slots:
  275. # ts: {'id': 123, 'start': '10:00', 'end': '10:30', 'remain': 1}
  276. ts_list.append(TimeSlot(
  277. time=f"{ts['start']} - {ts['end']}",
  278. label=str(ts['id']) # 将 ID 存入 label 以便 book 使用
  279. ))
  280. res.availability.append(DateAvailability(date=datetime.strptime(day, "%d-%m-%Y"), times=ts_list))
  281. return res
  282. # -------------------------------------------------------------
  283. # 3. Book
  284. # -------------------------------------------------------------
  285. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  286. res = VSBookResult()
  287. res.success = False
  288. if not slot_info.availability:
  289. raise NotFoundError("No slots to book")
  290. target_dt = slot_info.availability[0].date
  291. target_date = target_dt.strftime("%Y-%m-%d")
  292. # 取第一个时间段
  293. target_slot = slot_info.availability[0].times[0]
  294. slot_id = target_slot.label # 我们在 query 里把 ID 存在了 label
  295. slot_text = target_slot.time # "10:00 - 10:30"
  296. # 1. 获取 OTP (GenerateOTP)
  297. self._log("Requesting OTP...")
  298. otp_url = f"{self._host}/BookingCalendar/GenerateOTP?ServiceID={self._service_id}"
  299. self._perform_request("POST", otp_url)
  300. # 2. 等待并读取邮件
  301. self._log("Waiting for email code...")
  302. time.sleep(10) # 稍微等一下发信
  303. email_account = self.config.account.email
  304. # 使用 CloudAPI 读取 (假设已配置)
  305. otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
  306. if not otp_code:
  307. raise BizLogicError("Failed to retrieve OTP code")
  308. self._log(f"Got OTP: {otp_code}")
  309. # 3. 提交详细信息 (Fill User Info)
  310. # 这是最复杂的一步,涉及文件上传 (Multipart)
  311. self._log("Submitting User Details & Files...")
  312. # 准备文件 (转 Base64 传给 JS)
  313. passport_pdf_path = user_inputs.get('passport_pdf_path')
  314. irp_pdf_path = user_inputs.get('irp_pdf_path')
  315. def file_to_b64(path):
  316. if not path or not os.path.exists(path): return ""
  317. with open(path, "rb") as f:
  318. return base64.b64encode(f.read()).decode('utf-8')
  319. ppt_b64 = file_to_b64(passport_pdf_path)
  320. irp_b64 = file_to_b64(irp_pdf_path)
  321. # 构造 JS FormData 提交脚本
  322. # 注意:这里需要根据 Service ID (Dublin/Canton) 动态调整字段 ID
  323. # 下面以 Dublin (1321) 的字段为例,如果是 Canton 需要修改 _Id 和 _TipoDatoAddizionale
  324. # 为了通用性,这里演示 Dublin 的结构,请根据实际 Service ID 调整 mapping
  325. # 假设是 Dublin (根据提供的源码分析)
  326. boundary = '----WebKitFormBoundaryRandomString'
  327. submit_url = f"{self._host}/Services/Booking/{self._service_id}"
  328. # 注入 JS 执行
  329. js_submit = f"""
  330. const url = "{submit_url}";
  331. const fd = new FormData();
  332. // 基础字段
  333. fd.append('ServizioDescrizione', 'D Visa Application');
  334. fd.append('MessaggioRassicuranteWaitingList', 'True');
  335. fd.append('isWaitingListEnabled', 'False');
  336. fd.append('IDServizioConsolare', '35');
  337. fd.append('IDServizioErogato', '{self._service_id}');
  338. fd.append('IdTipoPrenotazione', '1'); // Single
  339. fd.append('NumMaxAccompagnatori', '3');
  340. fd.append('NumAccompagnatoriSelected', '0');
  341. // 动态字段 (Dublin 示例)
  342. // [0] Other citizenship -> User Input
  343. fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
  344. fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
  345. fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
  346. fd.append('DatiAddizionaliPrenotante[0]._Id', '61738');
  347. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
  348. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
  349. // [1] Full address -> User Input
  350. fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
  351. fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
  352. fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
  353. fd.append('DatiAddizionaliPrenotante[1]._Id', '61739');
  354. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
  355. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
  356. // [2] Passport Num
  357. fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
  358. fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
  359. fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
  360. fd.append('DatiAddizionaliPrenotante[2]._Id', '61740');
  361. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
  362. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
  363. // [3] Reason (Select)
  364. fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
  365. fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
  366. fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
  367. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
  368. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
  369. fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42'); // 42 = Tourism? Need verify
  370. // OTP
  371. fd.append('otp-input', '{otp_code}');
  372. fd.append('PrivacyCheck', 'true');
  373. // 文件处理 (Base64 -> Blob -> FormData)
  374. // 注意:这里假设页面上有文件上传的对应 ID,或者我们直接硬编码 FormData
  375. // 原始抓包并未显示文件字段名,通常是 File_0, File_1
  376. // 我们需要将 base64 转 blob
  377. async function addFile(b64, name, filename) {{
  378. if(!b64) return;
  379. const res = await fetch(`data:application/pdf;base64,${{b64}}`);
  380. const blob = await res.blob();
  381. fd.append(name, blob, filename);
  382. }}
  383. // 并行处理文件
  384. await Promise.all([
  385. addFile('{ppt_b64}', 'File_0', 'passport.pdf'), // 假设 File_0 是护照
  386. addFile('{irp_b64}', 'File_1', 'irp.pdf') // 假设 File_1 是 IRP
  387. ]);
  388. // 发送 POST
  389. return fetch(url, {{
  390. method: 'POST',
  391. body: fd
  392. }}).then(async r => {{
  393. return {{ status: r.status, url: r.url, text: await r.text() }};
  394. }}).catch(e => {{ return {{ status: 0, text: e.toString() }}; }});
  395. """
  396. result_dict = self.page.run_js(js_submit)
  397. resp = BrowserResponse(result_dict)
  398. if resp.status_code == 302 or "BookingCalendar" in resp.url:
  399. self._log("User Info Submitted Successfully.")
  400. else:
  401. self._log(f"User Info Submit Failed: {resp.text[:100]}")
  402. # 如果 OTP 错误,页面会返回特定错误信息
  403. if "Codice errato" in resp.text:
  404. raise BizLogicError("Invalid OTP Code")
  405. return res # Fail
  406. # 4. 最终确认预约 (InsertNewBooking)
  407. self._log("Finalizing Booking...")
  408. final_url = f"{self._host}/BookingCalendar/InsertNewBooking"
  409. final_payload = {
  410. "idCalendarioGiornaliero": slot_id,
  411. "selectedDay": target_date,
  412. "selectedHour": slot_text # "10:00 - 10:30(2)"
  413. }
  414. # 这里用 Form-UrlEncoded
  415. resp_final = self._perform_request("POST", final_url, data=final_payload)
  416. if resp_final.status_code == 200:
  417. self._log("Booking Confirmed!")
  418. res.success = True
  419. res.book_date = target_date
  420. res.book_time = slot_text
  421. else:
  422. self._log(f"Final Booking Failed: {resp_final.status_code}")
  423. return res
  424. # -------------------------------------------------------------
  425. # 4. Helpers
  426. # -------------------------------------------------------------
  427. def _get_proxy_url(self):
  428. # 构造代理
  429. proxy_url = ""
  430. if self.config.proxy.ip:
  431. s = self.config.proxy
  432. if s.username:
  433. proxy_url = f"{s.proto}://{s.username}:{s.password}@{s.ip}:{s.port}"
  434. else:
  435. proxy_url = f"{s.proto}://{s.ip}:{s.port}"
  436. return proxy_url
  437. def _solve_and_inject_prenotami_captcha(self):
  438. """
  439. 专门处理 Prenotami 的 ReCaptcha Enterprise
  440. """
  441. self._log("Solving ReCaptcha Enterprise (Action: LOGIN)...")
  442. api_token = self.free_config.get("capsolver_key", "")
  443. if not api_token:
  444. raise BizLogicError("Capsolver Key is required for Prenotami")
  445. # 从 HTML 源码中提取的信息
  446. site_key = "6LdkwrIqAAAAAC4NX-g_j7lEx9vh1rg94ZL2cFfY"
  447. page_url = self.page.url
  448. # 注意:Prenotami 的这个 Key 其实是混合模式,
  449. # 虽然它是 V3 (Enterprise),但很多打码平台用 V2 接口也能解,或者必须用 V3 Enterprise 接口
  450. # 建议先尝试 ReCaptchaV3EnterpriseTaskProxyLess
  451. # 修正为最标准的 V3 Enterprise 配置
  452. rc_params = {
  453. "type": "ReCaptchaV3EnterpriseTaskProxyless",
  454. "page": page_url,
  455. "siteKey": site_key,
  456. "action": "LOGIN", # 关键参数
  457. "minScore": 0.7, # 要求高分
  458. "apiToken": api_token,
  459. # "proxy": self._get_proxy_url()
  460. }
  461. g_token = self._solve_recaptcha(rc_params)
  462. self._log(f"Captcha Solved. Token length: {len(g_token)}")
  463. hook_js = f"""
  464. // 1. 填充隐藏域 (双重保险)
  465. var input = document.getElementById('g-recaptcha-response');
  466. if(input) {{
  467. input.value = "{g_token}";
  468. }}
  469. // 2. 劫持 grecaptcha.execute 和 grecaptcha.enterprise.execute
  470. // 无论网页用哪个版本,都拦截下来
  471. var mockExecute = function() {{
  472. console.log("Recaptcha execution intercepted!");
  473. return Promise.resolve("{g_token}");
  474. }};
  475. if (window.grecaptcha) {{
  476. window.grecaptcha.execute = mockExecute;
  477. if (window.grecaptcha.enterprise) {{
  478. window.grecaptcha.enterprise.execute = mockExecute;
  479. }}
  480. }}
  481. """
  482. self._log("Injecting ReCaptcha Hook...")
  483. self.page.run_js(hook_js)
  484. def _perform_request(self, method, url, headers=None, data=None, json_data=None):
  485. """JS Fetch Wrapper"""
  486. if not self.page: raise BizLogicError("Browser not init")
  487. fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
  488. if json_data:
  489. fetch_opts['body'] = json.dumps(json_data)
  490. fetch_opts['headers']['Content-Type'] = 'application/json; charset=UTF-8'
  491. elif data:
  492. if isinstance(data, dict):
  493. from urllib.parse import urlencode
  494. fetch_opts['body'] = urlencode(data)
  495. fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  496. else:
  497. fetch_opts['body'] = data
  498. js = f"""
  499. return fetch("{url}", {json.dumps(fetch_opts)})
  500. .then(async r => {{
  501. const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
  502. return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
  503. }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
  504. """
  505. return BrowserResponse(self.page.run_js(js, timeout=60)) # 文件上传可能较慢,给60s
  506. def _solve_recaptcha(self, params) -> str:
  507. """
  508. 调用 YesCaptcha API 识别
  509. """
  510. client_key = params.get("apiToken")
  511. # 1. 选择任务类型
  512. # 根据文档:RecaptchaV3TaskProxylessM1S7 强制 0.7 分,适合登录
  513. task_type = "RecaptchaV3TaskProxyless" # 默认
  514. if params.get("minScore") == 0.7:
  515. task_type = "RecaptchaV3TaskProxylessM1S7"
  516. elif params.get("minScore") == 0.9:
  517. task_type = "RecaptchaV3TaskProxylessM1S9"
  518. # 2. 构造创建任务请求
  519. create_url = "https://api.yescaptcha.com/createTask"
  520. create_data = {
  521. "clientKey": client_key,
  522. "task": {
  523. "type": task_type,
  524. "websiteURL": params.get("page"),
  525. "websiteKey": params.get("siteKey"),
  526. "pageAction": params.get("action") # YesCaptcha 要求的字段名是 pageAction
  527. }
  528. }
  529. import requests as req
  530. try:
  531. # 发送创建任务请求
  532. r = req.post(create_url, json=create_data, timeout=20)
  533. if r.status_code != 200:
  534. raise BizLogicError(f"YesCaptcha Create Failed: {r.text}")
  535. res_json = r.json()
  536. if res_json.get("errorId") != 0:
  537. raise BizLogicError(f"YesCaptcha Error: {res_json.get('errorDescription')}")
  538. task_id = res_json.get("taskId")
  539. if not task_id:
  540. raise BizLogicError("YesCaptcha returned no taskId")
  541. # 3. 轮询获取结果
  542. result_url = "https://api.yescaptcha.com/getTaskResult"
  543. for _ in range(30): # 最多等 60-90秒
  544. time.sleep(3)
  545. r = req.post(result_url, json={"clientKey": client_key, "taskId": task_id}, timeout=20)
  546. d = r.json()
  547. # 识别中
  548. if d.get("status") == "processing":
  549. continue
  550. # 识别成功
  551. if d.get("status") == "ready":
  552. solution = d.get("solution", {})
  553. token = solution.get("gRecaptchaResponse")
  554. if token:
  555. return token
  556. else:
  557. raise BizLogicError("YesCaptcha ready but no token found")
  558. # 识别失败
  559. if d.get("errorId") != 0:
  560. raise BizLogicError(f"YesCaptcha Task Failed: {d.get('errorDescription')}")
  561. except Exception as e:
  562. raise BizLogicError(f"Captcha Solver Exception: {e}")
  563. raise BizLogicError("YesCaptcha timeout")
  564. def _parse_valid_days(self, text):
  565. # 提取 DateLibere (YYYY-MM-DD)
  566. # 格式: {"DateLibere":"22/10/2024 00:00:00","SlotLiberi":1,"SlotRimanenti":1}
  567. # 原始正则: r'{"DateLibere":"(.*?)","SlotLiberi":\d+,"SlotRimanenti":(-?\d+)}'
  568. days = []
  569. try:
  570. matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
  571. for d_str, rem in matches:
  572. if int(rem) != -1:
  573. # 22/10/2024 -> 2024-10-22
  574. dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
  575. days.append(dt.strftime("%Y-%m-%d"))
  576. except: pass
  577. return days
  578. def _parse_time_slots(self, text):
  579. # 提取 IDCalendarioServizioGiornaliero, StartTime, EndTime, Remain
  580. slots = []
  581. try:
  582. # 原始逻辑比较复杂,这里简化正则
  583. # 查找 SlotRimanenti > 0 的记录
  584. # 关键是 IDCalendarioServizioGiornaliero
  585. raw_list = json.loads(text)
  586. # Prenotami 返回的是一个 JSON 列表字符串
  587. for item in raw_list:
  588. remain = item.get('SlotRimanenti', -1)
  589. if remain > 0:
  590. start = item['OrarioInizioFascia']
  591. end = item['OrarioFineFascia']
  592. s_time = f"{start['Hours']:02d}:{start['Minutes']:02d}"
  593. e_time = f"{end['Hours']:02d}:{end['Minutes']:02d}"
  594. slots.append({
  595. 'id': item['IDCalendarioServizioGiornaliero'],
  596. 'start': s_time,
  597. 'end': e_time,
  598. 'remain': remain
  599. })
  600. except: pass
  601. return slots
  602. # --- 资源清理核心方法 ---
  603. def cleanup(self):
  604. """
  605. 销毁浏览器并彻底删除临时文件
  606. """
  607. # 1. 关闭浏览器
  608. if self.page:
  609. try:
  610. self.page.quit() # 这会关闭 Chrome 进程
  611. except Exception:
  612. pass # 忽略已关闭的错误
  613. self.page = None
  614. # 2. 删除文件
  615. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  616. if os.path.exists(self.root_workspace):
  617. for _ in range(3):
  618. try:
  619. time.sleep(0.2)
  620. shutil.rmtree(self.root_workspace, ignore_errors=True)
  621. break
  622. except Exception as e:
  623. # 如果删除失败(通常是Windows文件占用),重试
  624. self._log(f"Cleanup retry: {e}")
  625. time.sleep(0.5)
  626. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  627. if os.path.exists(self.root_workspace):
  628. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  629. # 3. [新增] 关闭代理隧道
  630. if self.tunnel:
  631. try: self.tunnel.stop()
  632. except: pass
  633. self.tunnel = None
  634. def __del__(self):
  635. """
  636. 析构函数:当对象被垃圾回收时自动调用
  637. """
  638. self.cleanup()