ita_plugin.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 concurrent.futures import ThreadPoolExecutor
  11. from datetime import datetime
  12. from typing import List, Dict, Optional, Any, Callable
  13. from urllib.parse import urlencode, urlparse
  14. from DrissionPage import ChromiumPage, ChromiumOptions
  15. import configure
  16. from vs_plg import IVSPlg
  17. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str
  18. from toolkit.mihomo_tunnel import MihomoTunnel
  19. from toolkit.vs_cloud_api import VSCloudApi
  20. from utils.mouse import HumanMouse
  21. from utils.keyboard import HumanKeyboard
  22. from utils.fingerprint_utils import FingerprintGenerator
  23. class BrowserResponse:
  24. def __init__(self, result_dict):
  25. result_dict = result_dict or {}
  26. self.status_code = result_dict.get('status', 0)
  27. self.text = result_dict.get('body', '')
  28. self.headers = result_dict.get('headers', {})
  29. self.url = result_dict.get('url', '')
  30. self._json = None
  31. def json(self):
  32. if self._json is None:
  33. if not self.text: return {}
  34. try: self._json = json.loads(self.text)
  35. except: self._json = {}
  36. return self._json
  37. # ==========================================
  38. # 2. ItaPlugin 核心逻辑
  39. # ==========================================
  40. class ItaPlugin(IVSPlg):
  41. name = "ita_plugin"
  42. version = "1.0.0"
  43. description = "意大利Prenot@Mi领事预约插件 (支持拟人化交互与多领区调度)"
  44. def __init__(self, group_id: str):
  45. self.group_id = group_id
  46. self.config: Optional[VSPlgConfig] = None
  47. self.free_config: Dict[str, Any] = {}
  48. self.is_healthy = True
  49. self.logger = None
  50. self.page: Optional[ChromiumPage] = None
  51. # Prenotami 特有配置
  52. self._service_id = 0
  53. self.ita_url = 'https://prenotami.esteri.it'
  54. self.instance_id = uuid.uuid4().hex[:8]
  55. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  56. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  57. if not os.path.exists(self.root_workspace):
  58. os.makedirs(self.root_workspace)
  59. self.tunnel = None
  60. self.session_create_time: float = 0
  61. def set_log(self, logger: Callable[[str], None]) -> None:
  62. self.logger = logger
  63. def _log(self, message):
  64. if self.logger:
  65. self.logger(f'[ItaPlugin] [{self.group_id}] {message}')
  66. else:
  67. print(f'[ItaPlugin] [{self.group_id}] {message}')
  68. def set_config(self, config: VSPlgConfig):
  69. self.config = config
  70. self.free_config = config.free_config or {}
  71. # Service ID (e.g., 1321 for Ireland, 5059 for Guangzhou)
  72. self._service_id = self.free_config.get('service_id', 0)
  73. def keep_alive(self):
  74. pass
  75. def health_check(self) -> bool:
  76. if not self.is_healthy or not self.page:
  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. if time.time() - self.session_create_time > self.config.session_max_life:
  85. self._log("Session expired.")
  86. return False
  87. return True
  88. def create_session(self):
  89. """
  90. 全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
  91. """
  92. self._log(f"Initializing Session (ID: {self.instance_id})...")
  93. co = ChromiumOptions()
  94. def get_free_port():
  95. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  96. s.bind(('', 0))
  97. return s.getsockname()[1]
  98. debug_port = get_free_port()
  99. self._log(f"Assigned Debug Port: {debug_port}")
  100. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  101. co.set_local_port(debug_port)
  102. co.set_user_data_path(self.user_data_path)
  103. chrome_path = configure.CHROME_PATH
  104. if not chrome_path:
  105. chrome_path = os.getenv("CHROME_BIN")
  106. if chrome_path and os.path.exists(chrome_path):
  107. co.set_paths(browser_path=chrome_path)
  108. if self.config.proxy and self.config.proxy.ip:
  109. p = self.config.proxy
  110. if p.username and p.password:
  111. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  112. exit_node = {
  113. "name": "ExitNode",
  114. "type": p.proto,
  115. "server": p.ip,
  116. "port": p.port,
  117. "username": p.username,
  118. "password": p.password
  119. }
  120. relay_node = None
  121. if configure.MIHOMO_RELAY_NODES:
  122. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  123. mihomo_path = configure.MIHOMO_BIN_PATH
  124. if not mihomo_path:
  125. mihomo_path = os.getenv("MIHOMO_BIN")
  126. if not mihomo_path:
  127. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  128. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  129. local_proxy = self.tunnel.start()
  130. self._log(f"Tunnel started at {local_proxy}")
  131. co.set_argument(f'--proxy-server={local_proxy}')
  132. else:
  133. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  134. co.set_argument(f'--proxy-server={proxy_str}')
  135. else:
  136. self._log("[WARN] No proxy configured!")
  137. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  138. fp_seed = specific_fp.get("seed")
  139. fp_platform = specific_fp.get("platform")
  140. fp_brand = specific_fp.get("brand")
  141. self._log(f'browser fingerprint seed={fp_seed}')
  142. co.headless(False)
  143. co.set_argument('--no-sandbox')
  144. co.set_argument('--disable-dev-shm-usage')
  145. co.set_argument('--window-size=1920,1080')
  146. co.set_argument('--disable-blink-features=AutomationControlled')
  147. co.set_argument(f"--fingerprint={fp_seed}")
  148. co.set_argument(f"--fingerprint-platform={fp_platform}")
  149. co.set_argument(f"--fingerprint-brand={fp_brand}")
  150. self.page = ChromiumPage(co)
  151. if self.config.debug:
  152. self.page.get('https://example.com')
  153. js_script = """
  154. function getFingerprint() {
  155. let webglVendor = 'Unknown';
  156. let webglRenderer = 'Unknown';
  157. try {
  158. let canvas = document.createElement('canvas');
  159. let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  160. if (gl) {
  161. let debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
  162. if (debugInfo) {
  163. webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
  164. webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
  165. }
  166. }
  167. } catch(e) {}
  168. return {
  169. "User-Agent": navigator.userAgent,
  170. "Platform": navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
  171. "Brands": navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand).join(', ') : 'Not Supported',
  172. "CPU Cores": navigator.hardwareConcurrency,
  173. "Language": navigator.language,
  174. "Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
  175. "WebGL Vendor": webglVendor,
  176. "WebGL Renderer": webglRenderer
  177. };
  178. }
  179. return getFingerprint();
  180. """
  181. fp_data = self.page.run_js(js_script)
  182. self._log("================ 预检浏览器指纹数据 ================")
  183. self._log(json.dumps(fp_data, indent=4, ensure_ascii=False))
  184. self._log("====================================================")
  185. self.page = ChromiumPage(co)
  186. ita_url = self.ita_url
  187. self._log(f"Navigating to {ita_url}")
  188. self.page.get(ita_url)
  189. self._log("Init humanize tools...")
  190. self.mouse = HumanMouse(self.page, debug=True)
  191. self.keyboard = HumanKeyboard(self.page)
  192. self._log("Random mouse start position...")
  193. viewport_width = self.page.rect.viewport_size[0]
  194. viewport_height = self.page.rect.viewport_size[1]
  195. init_x = random.randint(10, viewport_width - 10)
  196. init_y = random.randint(10, viewport_height - 10)
  197. self.mouse.move(init_x, init_y)
  198. switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2')
  199. self.mouse.human_click_ele(switch_en_btn)
  200. self.page.wait.load_start()
  201. time.sleep(5)
  202. max_steps = 15
  203. stuck_counter = 0
  204. last_url = ""
  205. session_created = False
  206. has_submitted_login = False
  207. username = self.config.account.username
  208. password = self.config.account.password
  209. for step in range(max_steps):
  210. self.page.wait.doc_loaded()
  211. time.sleep(1)
  212. current_url = self.page.url
  213. current_title = self.page.title.lower()
  214. current_html_content = self.page.html
  215. self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
  216. # --- [异常处理与反爬对抗层] ---
  217. if current_url == last_url:
  218. stuck_counter += 1
  219. else:
  220. last_url = current_url
  221. stuck_counter = 0
  222. if stuck_counter >= 3:
  223. self._log("[WARN] Page stucked, try to refresh...")
  224. self.page.refresh()
  225. self._random_sleep(5, 8)
  226. stuck_counter = 0
  227. continue
  228. server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable", "error 1020"]
  229. if any(err in current_html_content for err in server_error_indicators):
  230. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  231. self.page.refresh()
  232. self._random_sleep(10, 15)
  233. continue
  234. # Cloudflare 拦截
  235. cloudflare_blocked_indicators = [
  236. "Sorry, you have been blocked",
  237. "You are being rate limited",
  238. "Cloudflare Ray ID"
  239. ]
  240. if any(indicator in current_html_content for indicator in cloudflare_blocked_indicators):
  241. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  242. # 遇到五秒盾先绕盾 (保留你原有的逻辑)
  243. if "just a moment" in current_title or "cloudflare" in current_title:
  244. # 假设你有 cf_bypasser 实例
  245. # if not cf_bypasser.bypass(max_retry=3): continue
  246. self._log("[State] CF 5-second shield detected. Waiting...")
  247. time.sleep(5)
  248. continue
  249. # 状态 0: 成功到达目标预约页面 (Target Page)
  250. if "/Services" in current_url and self.page.ele('.app-menu', timeout=1):
  251. self._log("🎉 Successfully reached the Booking Services page! Session created successfully!")
  252. self.session_create_time = time.time()
  253. session_created = True
  254. break
  255. # 状态 1: 登录前的初始首页
  256. elif self.page.ele('#pingid-button', timeout=1):
  257. self._log("[State] Initial Landing Page detected. Clicking login button...")
  258. login_btn = self.page.ele('#pingid-button')
  259. self.mouse.human_click_ele(login_btn)
  260. self._log("Redirecting to PingID...")
  261. self._random_sleep(3, 5) # 替代 time.sleep(5)
  262. continue
  263. # 状态 2: 真正的表单登录页 (PingID)
  264. elif self.page.ele('@name=callback_1', timeout=1):
  265. self._log("[State] PingID Login Form detected. Submitting credentials...")
  266. self._log("Entering username...")
  267. user_input = self.page.ele('@name=callback_1')
  268. self.mouse.human_click_ele(user_input)
  269. user_input.input(username, clear=True)
  270. time.sleep(1) # 模拟人手停顿
  271. self._log("Entering password...")
  272. pwd_input = self.page.ele('@type=password')
  273. self.mouse.human_click_ele(pwd_input)
  274. pwd_input.input(password, clear=True)
  275. time.sleep(1)
  276. self._log("Clicking submit login button...")
  277. submit_btn = self.page.ele('tag:button@type=submit')
  278. self.mouse.human_click_ele(submit_btn)
  279. has_submitted_login = True
  280. self._log("Login form submitted. Waiting for dashboard to load...")
  281. self._random_sleep(5, 7)
  282. continue
  283. # 状态 3: 登录成功后的主控制台 (导航栏页面)
  284. elif self.page.ele('.app-menu', timeout=1):
  285. self._log("[State] Dashboard Menu detected.")
  286. switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2', timeout=0.5)
  287. if switch_en_btn:
  288. self._log("Found 'English' language switch button. Clicking to change language...")
  289. self.mouse.human_click_ele(switch_en_btn)
  290. self._random_sleep(4, 6)
  291. continue
  292. # 动作 B: 如果没有英文切换按钮(说明已经是英文或不存在),则查找并点击 Book 按钮
  293. book_btn = self.page.ele('@href=/Services', timeout=0.5)
  294. if book_btn:
  295. self._log("Found 'Book' menu element. Clicking to proceed to reservation...")
  296. self.mouse.human_click_ele(book_btn)
  297. self._random_sleep(4, 6)
  298. continue
  299. self._log("[WARN] On Dashboard, but neither 'English' nor 'Book' button was found. Waiting...")
  300. time.sleep(2)
  301. continue
  302. else:
  303. self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
  304. time.sleep(2)
  305. if not session_created:
  306. raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
  307. # -------------------------------------------------------------
  308. # 2. Query Availability
  309. # -------------------------------------------------------------
  310. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  311. res = VSQueryResult()
  312. res.success = False
  313. res.availability_status = AvailabilityStatus.NoneAvailable
  314. # 假设要预约的服务和到访原因
  315. TARGET_SERVICE = "National and Schengen Visas"
  316. REASON_FOR_VISIT = "Tourism" # 对应 value 42 的选项文本
  317. # ==========================================
  318. # 步骤 1:在服务列表中寻找并点击目标服务的 Book
  319. # ==========================================
  320. self._log("Waiting for service list to load...")
  321. self.page.wait.eles_loaded('@aria-controls=dataTableServices', timeout=10)
  322. self._log(f"Searching for [{TARGET_SERVICE}] Book button...")
  323. # 使用 XPath:找包含 TARGET_SERVICE 文本的行(tr),再找该行里包含 Book 的超链接(a)
  324. target_book_btn_xpath = f'xpath://tr[contains(., "{TARGET_SERVICE}")]//a[contains(text(), "Book")]'
  325. book_btn = self.page.ele(target_book_btn_xpath)
  326. if not book_btn:
  327. self._log(f"Target [{TARGET_SERVICE}] Book button not found, currently no slots available.")
  328. # 这里可以根据你的逻辑 return 或者 raise Exception
  329. else:
  330. self.mouse.human_click_ele(book_btn)
  331. self.page.wait.load_start()
  332. time.sleep(3)
  333. # ==========================================
  334. # 步骤 2:填写预约表单
  335. # ==========================================
  336. self._log("Waiting for booking form to load...")
  337. self.page.wait.eles_loaded('#bookingForm', timeout=10)
  338. self._log("Selecting booking type & reason...")
  339. typeofbooking_ddl = self.page.ele('#typeofbookingddl')
  340. # DrissionPage select 方法直接按文本选中,会自动触发网页的 JS 联动
  341. typeofbooking_ddl.select('Individual booking')
  342. time.sleep(1)
  343. reason_ddl = self.page.ele('#ddls_0')
  344. reason_ddl.select(REASON_FOR_VISIT)
  345. time.sleep(1)
  346. notes_input = self.page.ele('#BookingNotes')
  347. notes_input.clear()
  348. notes_input.input('N/A') # 选填,填入 N/A 或者留空
  349. time.sleep(1)
  350. # ==========================================
  351. # 步骤 3:处理 OTP 验证码
  352. # ==========================================
  353. self._log("Sending OTP code...")
  354. otp_send_btn = self.page.ele('#otp-send')
  355. self.mouse.human_click_ele(otp_send_btn)
  356. # 这是一个 AJAX 请求,会转圈圈。我们需要等待成功提示出现
  357. self.page.wait.ele_displayed('#IdOtpSent', timeout=15) # 等待绿字 "New code sent!" 显示
  358. self._log("OTP code sent successfully.")
  359. otp_input = self.page.ele('#otp-input')
  360. self.mouse.human_click_ele(otp_input)
  361. otp_input.input('123456')
  362. time.sleep(1)
  363. # ==========================================
  364. # 步骤 4:勾选隐私政策并提交
  365. # ==========================================
  366. privacy_checkbox = self.page.ele('#PrivacyCheck')
  367. # 判断一下如果没勾上才去点,防止重复点击取消了
  368. if not privacy_checkbox.states.is_checked:
  369. self.mouse.human_click_ele(privacy_checkbox)
  370. time.sleep(1)
  371. self._log("Submitting forward form...")
  372. forward_btn = self.page.ele('#btnAvanti')
  373. self.mouse.human_click_ele(forward_btn)
  374. # 提交后页面会跳转,等待加载开始
  375. self.page.wait.load_start()
  376. self._log(f"Form submitted. Current page: {self.page.url}")
  377. time.sleep(5)
  378. valid_dates = []
  379. if valid_dates:
  380. res.success = True
  381. res.availability_status = AvailabilityStatus.Available
  382. earliest_date = valid_dates[0]
  383. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  384. res.earliest_date = earliest_dt
  385. for day in valid_days:
  386. # 查询具体 Slot
  387. slot_url = f"{self._host}/BookingCalendar/RetrieveTimeSlots"
  388. slot_payload = {
  389. "selectedDay": day, # YYYY-MM-DD
  390. "idService": str(self._service_id)
  391. }
  392. resp_slot = self._perform_request("POST", slot_url, json_data=slot_payload)
  393. time_slots = self._parse_time_slots(resp_slot.text)
  394. ts_list = []
  395. if time_slots:
  396. # 转换结构
  397. for ts in time_slots:
  398. # ts: {'id': 123, 'start': '10:00', 'end': '10:30', 'remain': 1}
  399. ts_list.append(TimeSlot(
  400. time=f"{ts['start']} - {ts['end']}",
  401. label=str(ts['id']) # 将 ID 存入 label 以便 book 使用
  402. ))
  403. res.availability.append(DateAvailability(date=datetime.strptime(day, "%d-%m-%Y"), times=ts_list))
  404. return res
  405. # -------------------------------------------------------------
  406. # 3. Book
  407. # -------------------------------------------------------------
  408. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  409. res = VSBookResult()
  410. res.success = False
  411. if not slot_info.availability:
  412. raise NotFoundError("No slots to book")
  413. target_dt = slot_info.availability[0].date
  414. target_date = target_dt.strftime("%Y-%m-%d")
  415. # 取第一个时间段
  416. target_slot = slot_info.availability[0].times[0]
  417. slot_id = target_slot.label # 我们在 query 里把 ID 存在了 label
  418. slot_text = target_slot.time # "10:00 - 10:30"
  419. # 1. 获取 OTP (GenerateOTP)
  420. self._log("Requesting OTP...")
  421. otp_url = f"{self._host}/BookingCalendar/GenerateOTP?ServiceID={self._service_id}"
  422. self._perform_request("POST", otp_url)
  423. # 2. 等待并读取邮件
  424. self._log("Waiting for email code...")
  425. time.sleep(10) # 稍微等一下发信
  426. email_account = self.config.account.email
  427. # 使用 CloudAPI 读取 (假设已配置)
  428. otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
  429. if not otp_code:
  430. raise BizLogicError("Failed to retrieve OTP code")
  431. self._log(f"Got OTP: {otp_code}")
  432. # 3. 提交详细信息 (Fill User Info)
  433. # 这是最复杂的一步,涉及文件上传 (Multipart)
  434. self._log("Submitting User Details & Files...")
  435. # 准备文件 (转 Base64 传给 JS)
  436. passport_pdf_path = user_inputs.get('passport_pdf_path')
  437. irp_pdf_path = user_inputs.get('irp_pdf_path')
  438. def file_to_b64(path):
  439. if not path or not os.path.exists(path): return ""
  440. with open(path, "rb") as f:
  441. return base64.b64encode(f.read()).decode('utf-8')
  442. ppt_b64 = file_to_b64(passport_pdf_path)
  443. irp_b64 = file_to_b64(irp_pdf_path)
  444. # 构造 JS FormData 提交脚本
  445. # 注意:这里需要根据 Service ID (Dublin/Canton) 动态调整字段 ID
  446. # 下面以 Dublin (1321) 的字段为例,如果是 Canton 需要修改 _Id 和 _TipoDatoAddizionale
  447. # 为了通用性,这里演示 Dublin 的结构,请根据实际 Service ID 调整 mapping
  448. # 假设是 Dublin (根据提供的源码分析)
  449. boundary = '----WebKitFormBoundaryRandomString'
  450. submit_url = f"{self._host}/Services/Booking/{self._service_id}"
  451. # 注入 JS 执行
  452. js_submit = f"""
  453. const url = "{submit_url}";
  454. const fd = new FormData();
  455. // 基础字段
  456. fd.append('ServizioDescrizione', 'D Visa Application');
  457. fd.append('MessaggioRassicuranteWaitingList', 'True');
  458. fd.append('isWaitingListEnabled', 'False');
  459. fd.append('IDServizioConsolare', '35');
  460. fd.append('IDServizioErogato', '{self._service_id}');
  461. fd.append('IdTipoPrenotazione', '1'); // Single
  462. fd.append('NumMaxAccompagnatori', '3');
  463. fd.append('NumAccompagnatoriSelected', '0');
  464. // 动态字段 (Dublin 示例)
  465. // [0] Other citizenship -> User Input
  466. fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
  467. fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
  468. fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
  469. fd.append('DatiAddizionaliPrenotante[0]._Id', '61738');
  470. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
  471. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
  472. // [1] Full address -> User Input
  473. fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
  474. fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
  475. fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
  476. fd.append('DatiAddizionaliPrenotante[1]._Id', '61739');
  477. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
  478. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
  479. // [2] Passport Num
  480. fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
  481. fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
  482. fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
  483. fd.append('DatiAddizionaliPrenotante[2]._Id', '61740');
  484. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
  485. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
  486. // [3] Reason (Select)
  487. fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
  488. fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
  489. fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
  490. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
  491. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
  492. fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42'); // 42 = Tourism? Need verify
  493. // OTP
  494. fd.append('otp-input', '{otp_code}');
  495. fd.append('PrivacyCheck', 'true');
  496. // 文件处理 (Base64 -> Blob -> FormData)
  497. // 注意:这里假设页面上有文件上传的对应 ID,或者我们直接硬编码 FormData
  498. // 原始抓包并未显示文件字段名,通常是 File_0, File_1
  499. // 我们需要将 base64 转 blob
  500. async function addFile(b64, name, filename) {{
  501. if(!b64) return;
  502. const res = await fetch(`data:application/pdf;base64,${{b64}}`);
  503. const blob = await res.blob();
  504. fd.append(name, blob, filename);
  505. }}
  506. // 并行处理文件
  507. await Promise.all([
  508. addFile('{ppt_b64}', 'File_0', 'passport.pdf'), // 假设 File_0 是护照
  509. addFile('{irp_b64}', 'File_1', 'irp.pdf') // 假设 File_1 是 IRP
  510. ]);
  511. // 发送 POST
  512. return fetch(url, {{
  513. method: 'POST',
  514. body: fd
  515. }}).then(async r => {{
  516. return {{ status: r.status, url: r.url, text: await r.text() }};
  517. }}).catch(e => {{ return {{ status: 0, text: e.toString() }}; }});
  518. """
  519. result_dict = self.page.run_js(js_submit)
  520. resp = BrowserResponse(result_dict)
  521. if resp.status_code == 302 or "BookingCalendar" in resp.url:
  522. self._log("User Info Submitted Successfully.")
  523. else:
  524. self._log(f"User Info Submit Failed: {resp.text[:100]}")
  525. # 如果 OTP 错误,页面会返回特定错误信息
  526. if "Codice errato" in resp.text:
  527. raise BizLogicError("Invalid OTP Code")
  528. return res # Fail
  529. # 4. 最终确认预约 (InsertNewBooking)
  530. self._log("Finalizing Booking...")
  531. final_url = f"{self._host}/BookingCalendar/InsertNewBooking"
  532. final_payload = {
  533. "idCalendarioGiornaliero": slot_id,
  534. "selectedDay": target_date,
  535. "selectedHour": slot_text # "10:00 - 10:30(2)"
  536. }
  537. # 这里用 Form-UrlEncoded
  538. resp_final = self._perform_request("POST", final_url, data=final_payload)
  539. if resp_final.status_code == 200:
  540. self._log("Booking Confirmed!")
  541. res.success = True
  542. res.book_date = target_date
  543. res.book_time = slot_text
  544. else:
  545. self._log(f"Final Booking Failed: {resp_final.status_code}")
  546. return res
  547. def _perform_request(self, method, url, headers=None, data=None, json_data=None):
  548. """JS Fetch Wrapper"""
  549. if not self.page: raise BizLogicError("Browser not init")
  550. fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
  551. if json_data:
  552. fetch_opts['body'] = json.dumps(json_data)
  553. fetch_opts['headers']['Content-Type'] = 'application/json; charset=UTF-8'
  554. elif data:
  555. if isinstance(data, dict):
  556. from urllib.parse import urlencode
  557. fetch_opts['body'] = urlencode(data)
  558. fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  559. else:
  560. fetch_opts['body'] = data
  561. js = f"""
  562. return fetch("{url}", {json.dumps(fetch_opts)})
  563. .then(async r => {{
  564. const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
  565. return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
  566. }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
  567. """
  568. return BrowserResponse(self.page.run_js(js, timeout=60)) # 文件上传可能较慢,给60s
  569. def _parse_valid_days(self, text):
  570. # 提取 DateLibere (YYYY-MM-DD)
  571. # 格式: {"DateLibere":"22/10/2024 00:00:00","SlotLiberi":1,"SlotRimanenti":1}
  572. # 原始正则: r'{"DateLibere":"(.*?)","SlotLiberi":\d+,"SlotRimanenti":(-?\d+)}'
  573. days = []
  574. try:
  575. matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
  576. for d_str, rem in matches:
  577. if int(rem) != -1:
  578. # 22/10/2024 -> 2024-10-22
  579. dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
  580. days.append(dt.strftime("%Y-%m-%d"))
  581. except: pass
  582. return days
  583. def _parse_time_slots(self, text):
  584. # 提取 IDCalendarioServizioGiornaliero, StartTime, EndTime, Remain
  585. slots = []
  586. try:
  587. # 原始逻辑比较复杂,这里简化正则
  588. # 查找 SlotRimanenti > 0 的记录
  589. # 关键是 IDCalendarioServizioGiornaliero
  590. raw_list = json.loads(text)
  591. # Prenotami 返回的是一个 JSON 列表字符串
  592. for item in raw_list:
  593. remain = item.get('SlotRimanenti', -1)
  594. if remain > 0:
  595. start = item['OrarioInizioFascia']
  596. end = item['OrarioFineFascia']
  597. s_time = f"{start['Hours']:02d}:{start['Minutes']:02d}"
  598. e_time = f"{end['Hours']:02d}:{end['Minutes']:02d}"
  599. slots.append({
  600. 'id': item['IDCalendarioServizioGiornaliero'],
  601. 'start': s_time,
  602. 'end': e_time,
  603. 'remain': remain
  604. })
  605. except: pass
  606. return slots
  607. # --- 资源清理核心方法 ---
  608. def cleanup(self):
  609. """
  610. 销毁浏览器并彻底删除临时文件
  611. """
  612. # 1. 关闭浏览器
  613. if self.page:
  614. try:
  615. self.page.quit() # 这会关闭 Chrome 进程
  616. except Exception:
  617. pass # 忽略已关闭的错误
  618. self.page = None
  619. # 2. 删除文件
  620. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  621. if os.path.exists(self.root_workspace):
  622. for _ in range(3):
  623. try:
  624. time.sleep(0.2)
  625. shutil.rmtree(self.root_workspace, ignore_errors=True)
  626. break
  627. except Exception as e:
  628. # 如果删除失败(通常是Windows文件占用),重试
  629. self._log(f"Cleanup retry: {e}")
  630. time.sleep(0.5)
  631. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  632. if os.path.exists(self.root_workspace):
  633. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  634. # 3. [新增] 关闭代理隧道
  635. if self.tunnel:
  636. try: self.tunnel.stop()
  637. except: pass
  638. self.tunnel = None
  639. def get_plugin_status(self) -> PluginStatus:
  640. account_name = self.config.account.username if self.config and self.config.account else ""
  641. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  642. current_url = ""
  643. if self.page:
  644. try:
  645. current_url = self.page.url
  646. except Exception:
  647. pass
  648. state = "running" if self.is_healthy else "unhealthy"
  649. return PluginStatus(
  650. instance_id=self.instance_id,
  651. is_healthy=self.is_healthy,
  652. state=state,
  653. current_url=current_url,
  654. account=account_name,
  655. proxy=proxy_info,
  656. session_age_sec=0,
  657. last_active_at=utc_now_str(),
  658. )
  659. def __del__(self):
  660. """
  661. 析构函数:当对象被垃圾回收时自动调用
  662. """
  663. self.cleanup()