ita_plugin.py 31 KB

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