ita_plugin.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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. print("正在输入账号...")
  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. print("正在输入密码...")
  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. print("正在点击登录按钮...")
  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. print("等待服务列表加载...")
  321. self.page.wait.eles_loaded('@aria-controls=dataTableServices', timeout=10)
  322. print(f"正在查找 [{TARGET_SERVICE}] 的 Book 按钮...")
  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. print(f"未找到 {TARGET_SERVICE} 的 Book 按钮,可能当前无号,程序退出。")
  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. print("等待预约表单加载...")
  337. self.page.wait.eles_loaded('#bookingForm', timeout=10)
  338. print("1. 选择预约类型...")
  339. typeofbooking_ddl = self.page.ele('#typeofbookingddl')
  340. # DrissionPage select 方法直接按文本选中,会自动触发网页的 JS 联动
  341. typeofbooking_ddl.select('Individual booking')
  342. time.sleep(1)
  343. print("2. 选择到访原因...")
  344. reason_ddl = self.page.ele('#ddls_0')
  345. reason_ddl.select(REASON_FOR_VISIT)
  346. time.sleep(1)
  347. print("3. 填写备注...")
  348. notes_input = self.page.ele('#BookingNotes')
  349. notes_input.clear()
  350. notes_input.input('N/A') # 选填,填入 N/A 或者留空
  351. time.sleep(1)
  352. # ==========================================
  353. # 步骤 3:处理 OTP 验证码
  354. # ==========================================
  355. print("4. 点击发送 OTP 验证码...")
  356. otp_send_btn = self.page.ele('#otp-send')
  357. self.mouse.human_click_ele(otp_send_btn)
  358. # 这是一个 AJAX 请求,会转圈圈。我们需要等待成功提示出现
  359. print("等待验证码发送成功的提示...")
  360. self.page.wait.ele_displayed('#IdOtpSent', timeout=15) # 等待绿字 "New code sent!" 显示
  361. print("验证码已发送!")
  362. print("5. 填写默认验证码 123456 ...")
  363. otp_input = self.page.ele('#otp-input')
  364. self.mouse.human_click_ele(otp_input)
  365. otp_input.input('123456')
  366. time.sleep(1)
  367. # ==========================================
  368. # 步骤 4:勾选隐私政策并提交
  369. # ==========================================
  370. print("6. 勾选隐私政策...")
  371. privacy_checkbox = self.page.ele('#PrivacyCheck')
  372. # 判断一下如果没勾上才去点,防止重复点击取消了
  373. if not privacy_checkbox.states.is_checked:
  374. self.mouse.human_click_ele(privacy_checkbox)
  375. time.sleep(1)
  376. print("7. 点击 Forward 提交表单...")
  377. forward_btn = self.page.ele('#btnAvanti')
  378. self.mouse.human_click_ele(forward_btn)
  379. # 提交后页面会跳转,等待加载开始
  380. self.page.wait.load_start()
  381. print("表单已提交!当前页面:", self.page.url)
  382. time.sleep(5)
  383. valid_dates = []
  384. if valid_dates:
  385. res.success = True
  386. res.availability_status = AvailabilityStatus.Available
  387. earliest_date = valid_dates[0]
  388. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  389. res.earliest_date = earliest_dt
  390. for day in valid_days:
  391. # 查询具体 Slot
  392. slot_url = f"{self._host}/BookingCalendar/RetrieveTimeSlots"
  393. slot_payload = {
  394. "selectedDay": day, # YYYY-MM-DD
  395. "idService": str(self._service_id)
  396. }
  397. resp_slot = self._perform_request("POST", slot_url, json_data=slot_payload)
  398. time_slots = self._parse_time_slots(resp_slot.text)
  399. ts_list = []
  400. if time_slots:
  401. # 转换结构
  402. for ts in time_slots:
  403. # ts: {'id': 123, 'start': '10:00', 'end': '10:30', 'remain': 1}
  404. ts_list.append(TimeSlot(
  405. time=f"{ts['start']} - {ts['end']}",
  406. label=str(ts['id']) # 将 ID 存入 label 以便 book 使用
  407. ))
  408. res.availability.append(DateAvailability(date=datetime.strptime(day, "%d-%m-%Y"), times=ts_list))
  409. return res
  410. # -------------------------------------------------------------
  411. # 3. Book
  412. # -------------------------------------------------------------
  413. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  414. res = VSBookResult()
  415. res.success = False
  416. if not slot_info.availability:
  417. raise NotFoundError("No slots to book")
  418. target_dt = slot_info.availability[0].date
  419. target_date = target_dt.strftime("%Y-%m-%d")
  420. # 取第一个时间段
  421. target_slot = slot_info.availability[0].times[0]
  422. slot_id = target_slot.label # 我们在 query 里把 ID 存在了 label
  423. slot_text = target_slot.time # "10:00 - 10:30"
  424. # 1. 获取 OTP (GenerateOTP)
  425. self._log("Requesting OTP...")
  426. otp_url = f"{self._host}/BookingCalendar/GenerateOTP?ServiceID={self._service_id}"
  427. self._perform_request("POST", otp_url)
  428. # 2. 等待并读取邮件
  429. self._log("Waiting for email code...")
  430. time.sleep(10) # 稍微等一下发信
  431. email_account = self.config.account.email
  432. # 使用 CloudAPI 读取 (假设已配置)
  433. otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
  434. if not otp_code:
  435. raise BizLogicError("Failed to retrieve OTP code")
  436. self._log(f"Got OTP: {otp_code}")
  437. # 3. 提交详细信息 (Fill User Info)
  438. # 这是最复杂的一步,涉及文件上传 (Multipart)
  439. self._log("Submitting User Details & Files...")
  440. # 准备文件 (转 Base64 传给 JS)
  441. passport_pdf_path = user_inputs.get('passport_pdf_path')
  442. irp_pdf_path = user_inputs.get('irp_pdf_path')
  443. def file_to_b64(path):
  444. if not path or not os.path.exists(path): return ""
  445. with open(path, "rb") as f:
  446. return base64.b64encode(f.read()).decode('utf-8')
  447. ppt_b64 = file_to_b64(passport_pdf_path)
  448. irp_b64 = file_to_b64(irp_pdf_path)
  449. # 构造 JS FormData 提交脚本
  450. # 注意:这里需要根据 Service ID (Dublin/Canton) 动态调整字段 ID
  451. # 下面以 Dublin (1321) 的字段为例,如果是 Canton 需要修改 _Id 和 _TipoDatoAddizionale
  452. # 为了通用性,这里演示 Dublin 的结构,请根据实际 Service ID 调整 mapping
  453. # 假设是 Dublin (根据提供的源码分析)
  454. boundary = '----WebKitFormBoundaryRandomString'
  455. submit_url = f"{self._host}/Services/Booking/{self._service_id}"
  456. # 注入 JS 执行
  457. js_submit = f"""
  458. const url = "{submit_url}";
  459. const fd = new FormData();
  460. // 基础字段
  461. fd.append('ServizioDescrizione', 'D Visa Application');
  462. fd.append('MessaggioRassicuranteWaitingList', 'True');
  463. fd.append('isWaitingListEnabled', 'False');
  464. fd.append('IDServizioConsolare', '35');
  465. fd.append('IDServizioErogato', '{self._service_id}');
  466. fd.append('IdTipoPrenotazione', '1'); // Single
  467. fd.append('NumMaxAccompagnatori', '3');
  468. fd.append('NumAccompagnatoriSelected', '0');
  469. // 动态字段 (Dublin 示例)
  470. // [0] Other citizenship -> User Input
  471. fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
  472. fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
  473. fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
  474. fd.append('DatiAddizionaliPrenotante[0]._Id', '61738');
  475. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
  476. fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
  477. // [1] Full address -> User Input
  478. fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
  479. fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
  480. fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
  481. fd.append('DatiAddizionaliPrenotante[1]._Id', '61739');
  482. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
  483. fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
  484. // [2] Passport Num
  485. fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
  486. fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
  487. fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
  488. fd.append('DatiAddizionaliPrenotante[2]._Id', '61740');
  489. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
  490. fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
  491. // [3] Reason (Select)
  492. fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
  493. fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
  494. fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
  495. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
  496. fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
  497. fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42'); // 42 = Tourism? Need verify
  498. // OTP
  499. fd.append('otp-input', '{otp_code}');
  500. fd.append('PrivacyCheck', 'true');
  501. // 文件处理 (Base64 -> Blob -> FormData)
  502. // 注意:这里假设页面上有文件上传的对应 ID,或者我们直接硬编码 FormData
  503. // 原始抓包并未显示文件字段名,通常是 File_0, File_1
  504. // 我们需要将 base64 转 blob
  505. async function addFile(b64, name, filename) {{
  506. if(!b64) return;
  507. const res = await fetch(`data:application/pdf;base64,${{b64}}`);
  508. const blob = await res.blob();
  509. fd.append(name, blob, filename);
  510. }}
  511. // 并行处理文件
  512. await Promise.all([
  513. addFile('{ppt_b64}', 'File_0', 'passport.pdf'), // 假设 File_0 是护照
  514. addFile('{irp_b64}', 'File_1', 'irp.pdf') // 假设 File_1 是 IRP
  515. ]);
  516. // 发送 POST
  517. return fetch(url, {{
  518. method: 'POST',
  519. body: fd
  520. }}).then(async r => {{
  521. return {{ status: r.status, url: r.url, text: await r.text() }};
  522. }}).catch(e => {{ return {{ status: 0, text: e.toString() }}; }});
  523. """
  524. result_dict = self.page.run_js(js_submit)
  525. resp = BrowserResponse(result_dict)
  526. if resp.status_code == 302 or "BookingCalendar" in resp.url:
  527. self._log("User Info Submitted Successfully.")
  528. else:
  529. self._log(f"User Info Submit Failed: {resp.text[:100]}")
  530. # 如果 OTP 错误,页面会返回特定错误信息
  531. if "Codice errato" in resp.text:
  532. raise BizLogicError("Invalid OTP Code")
  533. return res # Fail
  534. # 4. 最终确认预约 (InsertNewBooking)
  535. self._log("Finalizing Booking...")
  536. final_url = f"{self._host}/BookingCalendar/InsertNewBooking"
  537. final_payload = {
  538. "idCalendarioGiornaliero": slot_id,
  539. "selectedDay": target_date,
  540. "selectedHour": slot_text # "10:00 - 10:30(2)"
  541. }
  542. # 这里用 Form-UrlEncoded
  543. resp_final = self._perform_request("POST", final_url, data=final_payload)
  544. if resp_final.status_code == 200:
  545. self._log("Booking Confirmed!")
  546. res.success = True
  547. res.book_date = target_date
  548. res.book_time = slot_text
  549. else:
  550. self._log(f"Final Booking Failed: {resp_final.status_code}")
  551. return res
  552. def _perform_request(self, method, url, headers=None, data=None, json_data=None):
  553. """JS Fetch Wrapper"""
  554. if not self.page: raise BizLogicError("Browser not init")
  555. fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
  556. if json_data:
  557. fetch_opts['body'] = json.dumps(json_data)
  558. fetch_opts['headers']['Content-Type'] = 'application/json; charset=UTF-8'
  559. elif data:
  560. if isinstance(data, dict):
  561. from urllib.parse import urlencode
  562. fetch_opts['body'] = urlencode(data)
  563. fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  564. else:
  565. fetch_opts['body'] = data
  566. js = f"""
  567. return fetch("{url}", {json.dumps(fetch_opts)})
  568. .then(async r => {{
  569. const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
  570. return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
  571. }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
  572. """
  573. return BrowserResponse(self.page.run_js(js, timeout=60)) # 文件上传可能较慢,给60s
  574. def _parse_valid_days(self, text):
  575. # 提取 DateLibere (YYYY-MM-DD)
  576. # 格式: {"DateLibere":"22/10/2024 00:00:00","SlotLiberi":1,"SlotRimanenti":1}
  577. # 原始正则: r'{"DateLibere":"(.*?)","SlotLiberi":\d+,"SlotRimanenti":(-?\d+)}'
  578. days = []
  579. try:
  580. matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
  581. for d_str, rem in matches:
  582. if int(rem) != -1:
  583. # 22/10/2024 -> 2024-10-22
  584. dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
  585. days.append(dt.strftime("%Y-%m-%d"))
  586. except: pass
  587. return days
  588. def _parse_time_slots(self, text):
  589. # 提取 IDCalendarioServizioGiornaliero, StartTime, EndTime, Remain
  590. slots = []
  591. try:
  592. # 原始逻辑比较复杂,这里简化正则
  593. # 查找 SlotRimanenti > 0 的记录
  594. # 关键是 IDCalendarioServizioGiornaliero
  595. raw_list = json.loads(text)
  596. # Prenotami 返回的是一个 JSON 列表字符串
  597. for item in raw_list:
  598. remain = item.get('SlotRimanenti', -1)
  599. if remain > 0:
  600. start = item['OrarioInizioFascia']
  601. end = item['OrarioFineFascia']
  602. s_time = f"{start['Hours']:02d}:{start['Minutes']:02d}"
  603. e_time = f"{end['Hours']:02d}:{end['Minutes']:02d}"
  604. slots.append({
  605. 'id': item['IDCalendarioServizioGiornaliero'],
  606. 'start': s_time,
  607. 'end': e_time,
  608. 'remain': remain
  609. })
  610. except: pass
  611. return slots
  612. # --- 资源清理核心方法 ---
  613. def cleanup(self):
  614. """
  615. 销毁浏览器并彻底删除临时文件
  616. """
  617. # 1. 关闭浏览器
  618. if self.page:
  619. try:
  620. self.page.quit() # 这会关闭 Chrome 进程
  621. except Exception:
  622. pass # 忽略已关闭的错误
  623. self.page = None
  624. # 2. 删除文件
  625. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  626. if os.path.exists(self.root_workspace):
  627. for _ in range(3):
  628. try:
  629. time.sleep(0.2)
  630. shutil.rmtree(self.root_workspace, ignore_errors=True)
  631. break
  632. except Exception as e:
  633. # 如果删除失败(通常是Windows文件占用),重试
  634. self._log(f"Cleanup retry: {e}")
  635. time.sleep(0.5)
  636. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  637. if os.path.exists(self.root_workspace):
  638. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  639. # 3. [新增] 关闭代理隧道
  640. if self.tunnel:
  641. try: self.tunnel.stop()
  642. except: pass
  643. self.tunnel = None
  644. def get_plugin_status(self) -> PluginStatus:
  645. account_name = self.config.account.username if self.config and self.config.account else ""
  646. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  647. current_url = ""
  648. if self.page:
  649. try:
  650. current_url = self.page.url
  651. except Exception:
  652. pass
  653. state = "running" if self.is_healthy else "unhealthy"
  654. return PluginStatus(
  655. instance_id=self.instance_id,
  656. is_healthy=self.is_healthy,
  657. state=state,
  658. current_url=current_url,
  659. account=account_name,
  660. proxy=proxy_info,
  661. session_age_sec=0,
  662. last_active_at=utc_now_str(),
  663. )
  664. def __del__(self):
  665. """
  666. 析构函数:当对象被垃圾回收时自动调用
  667. """
  668. self.cleanup()