bls_plugin.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. import re
  2. import os
  3. import uuid
  4. import base64
  5. import time
  6. import json
  7. import shutil
  8. import random
  9. import string
  10. from datetime import datetime, timedelta
  11. from pathlib import Path
  12. from urllib.parse import urlparse, parse_qs, urlencode
  13. from typing import Dict, List, Optional, Any, Callable
  14. from curl_cffi import requests, const
  15. from bs4 import BeautifulSoup
  16. # DrissionPage 核心
  17. from DrissionPage import ChromiumPage, ChromiumOptions
  18. from cryptography.hazmat.primitives import hashes
  19. from cryptography.hazmat.backends import default_backend
  20. # 框架依赖
  21. from vs_plg import IVSPlg
  22. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, TimeSlot, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  23. from toolkit.vs_cloud_api import VSCloudApi
  24. from toolkit.ocr_engine import PyTorchEngine
  25. class BlsPlugin(IVSPlg):
  26. """
  27. BLS 签证预约插件 (精简版)
  28. """
  29. def __init__(self, group_id: str):
  30. self.group_id = group_id
  31. self.config: Optional[VSPlgConfig] = None
  32. self.free_config: Dict[str, Any] = {}
  33. self.logger = None
  34. self.session: Optional[requests.Session] = None
  35. # 运行时状态
  36. self.book_params: Dict = {}
  37. self.is_healthy: bool = True
  38. # 浏览器实例
  39. self.page: Optional[ChromiumPage] = None
  40. # --- [核心修改] 并发隔离与资源管理 ---
  41. # 生成唯一实例 ID
  42. self.instance_id = uuid.uuid4().hex[:8]
  43. self.root_workspace = os.path.abspath(os.path.join("temp_browser_data", f"{self.group_id}_{self.instance_id}"))
  44. # 定义子目录:代理插件目录 & 浏览器用户数据目录
  45. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  46. # 字符识别引擎
  47. self.ocr_engine: Optional[PyTorchEngine] = None
  48. # OCR 服务地址默认值
  49. self.local_service_url: str = ""
  50. self.session_create_time: float = 0
  51. def get_group_id(self) -> str:
  52. return self.group_id
  53. def set_log(self, logger: Callable[[str], None]) -> None:
  54. self.logger = logger
  55. def _log(self, message):
  56. if self.logger:
  57. self.logger(f'[BlsPlugin] [{self.group_id}] {message}')
  58. else:
  59. print(f'[BlsPlugin] [{self.group_id}] {message}')
  60. def set_config(self, config: VSPlgConfig):
  61. self.config = config
  62. self.free_config = config.free_config or {}
  63. # 从配置中读取 OCR 服务地址,如果没有则使用默认
  64. if self.free_config.get("local_service_url"):
  65. self.local_service_url = self.free_config["local_service_url"]
  66. def health_check(self) -> bool:
  67. if not self.is_healthy:
  68. return False
  69. if self.session is None:
  70. return False
  71. if self.config.session_max_life > 0:
  72. current_time = time.time()
  73. elapsed_time = current_time - self.session_create_time
  74. if elapsed_time > self.config.session_max_life * 60:
  75. self._log(f"Session expired.")
  76. return False
  77. return True
  78. def create_session(self):
  79. self._log(f"Initializing Session (ID: {self.instance_id})...")
  80. co = ChromiumOptions()
  81. # -------------------------------------------------------------
  82. # [核心修复] 解决 'not enough values to unpack'
  83. # -------------------------------------------------------------
  84. # 1. 不要用 co.auto_port(),因为它依赖解析 stdout,会被 DBus 报错干扰
  85. # 2. 我们手动随机生成一个端口
  86. import random
  87. import socket
  88. def get_free_port():
  89. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  90. s.bind(('', 0))
  91. return s.getsockname()[1]
  92. debug_port = get_free_port()
  93. self._log(f"Assigned Debug Port: {debug_port}")
  94. # 3. 强制指定端口,DrissionPage 就会直接连接,不再解析日志
  95. co.set_local_port(debug_port)
  96. # --- [关键配置] 设置独立的用户数据目录 ---
  97. # 这样每个实例的 Cache, Cookies, LocalStorage 都是完全隔离的
  98. # 同时也防止了多进程争抢同一个 Default 文件夹导致的崩溃
  99. co.set_user_data_path(self.user_data_path)
  100. # --- 1. 指定浏览器路径 (适配 Docker) ---
  101. chrome_path = os.getenv("CHROME_BIN")
  102. if chrome_path and os.path.exists(chrome_path):
  103. co.set_paths(browser_path=chrome_path)
  104. co.headless(False)
  105. co.set_argument('--no-sandbox')
  106. co.set_argument('--disable-gpu')
  107. # Docker 默认 /dev/shm 只有 64MB,Chromium 很容易爆内存崩溃
  108. co.set_argument('--disable-dev-shm-usage')
  109. co.set_argument('--window-size=1920,1080')
  110. co.set_argument('--disable-blink-features=AutomationControlled')
  111. try:
  112. self.page = ChromiumPage(co)
  113. except Exception as e:
  114. self._log(f"Session Create Error: {e}")
  115. self.cleanup()
  116. raise e
  117. self.ocr_engine = PyTorchEngine(self.free_config.get('ocr_model'))
  118. self.session = requests.Session(
  119. proxy=self._get_proxy_url(),
  120. impersonate="chrome124",
  121. curl_options={
  122. const.CurlOpt.MAXAGE_CONN: 1800,
  123. const.CurlOpt.VERBOSE: self.config.debug
  124. }
  125. )
  126. domain = self.free_config.get("domain")
  127. if not domain:
  128. raise NotFoundError(message="Required field [domain] in free config")
  129. # 1.1 获取登录页 & 解析参数
  130. login_url = f"https://{domain}/Global/account/login"
  131. resp = self._perform_request('GET', login_url)
  132. if self.config.debug:
  133. self._save_debug_html(resp.text, prefix="Bls_Login_Page")
  134. soup = BeautifulSoup(resp.text, 'html.parser')
  135. form_data = self._extract_hidden_fields(soup)
  136. real_user = None
  137. real_pass = None
  138. # 解析动态 ID (UserId1, Password1 等)
  139. for inp in soup.find_all('input'):
  140. name = inp.get('name', '')
  141. if inp.has_attr('required'):
  142. if 'UserId' in name:
  143. real_user = name
  144. elif 'Password' in name:
  145. real_pass = name
  146. # 解析 data 参数 (用于验证码)
  147. data_val = self._extract_js_var(resp.text, "iframeOpenUrl", r"data=([^']+)")
  148. # 1.2 处理验证码
  149. captcha_token = self._solve_bls_captcha(data_val)
  150. # 1.3 提交登录
  151. submit_url = f"https://{domain}/Global/account/loginsubmit"
  152. payload = form_data
  153. payload["X-Requested-With"] = "XMLHttpRequest"
  154. payload["CaptchaData"] = captcha_token
  155. # 填入账号密码
  156. payload[real_user] = self.config.account.username
  157. payload[real_pass] = self.config.account.password
  158. login_resp = self._perform_request('POST', submit_url, data=payload)
  159. if not login_resp.json()['success']:
  160. raise BizLogicError(message='Login failed')
  161. self.session_create_time = time.time()
  162. self._log("Session created successfully.")
  163. # =========================================================================
  164. # 2. 查询流程 (Query)
  165. # =========================================================================
  166. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  167. res = VSQueryResult()
  168. apt_config = self.free_config.get("apt_configs", {}).get(apt_type.routing_key)
  169. domain = self.free_config.get("domain")
  170. # 2.1 签证类型验证
  171. url_vtv = f"https://{domain}/Global/bls/visatypeverification"
  172. resp = self._perform_request('GET', url_vtv)
  173. if self.config.debug:
  174. self._save_debug_html(resp.text, prefix="Bls_Visatypeverification_Page")
  175. self._check_resp_is_session_expired_or_invalid('APPLICATION PROCESS', resp)
  176. form_vtv = self._extract_hidden_fields(BeautifulSoup(resp.text, 'html.parser'))
  177. captcha_token = self._solve_bls_captcha()
  178. form_vtv['CaptchaData'] = captcha_token
  179. form_vtv["X-Requested-With"] = "XMLHttpRequest"
  180. vtv_resp = self._perform_request('POST', f"https://{domain}/Global/bls/VisaTypeVerification", data=form_vtv)
  181. if not vtv_resp.json()['success']:
  182. raise BizLogicError(message='Submit VisaTypeVerification Failed')
  183. # 2.2 签证类型选择
  184. return_url = vtv_resp.json()['returnUrl'] # 包含 data=xxx
  185. data_val = re.search(r"data=([^&]+)", return_url).group(1)
  186. url_vt = f"https://{domain}/Global/bls/visatype?data={data_val}"
  187. vt_resp = self._perform_request('GET', url_vt)
  188. if self.config.debug:
  189. self._save_debug_html(resp.text, prefix="Bls_Visatype_Page")
  190. self._check_resp_is_session_expired_or_invalid('APPLICATION PROCESS', resp)
  191. # 这里需要极其复杂的 JS 变量提取 (JS Arrays -> Match Name -> Get ID)
  192. vt_payload = self._construct_visatype_payload(apt_config, vt_resp.text, BeautifulSoup(vt_resp.text, 'html.parser'))
  193. vt_res = self._perform_request('POST', f"https://{domain}/Global/bls/VisaType", data=vt_payload)
  194. if not vt_res.json()['success']:
  195. if not vt_res.json()['available']:
  196. res.success = False
  197. res.availability_status = AvailabilityStatus.NoneAvailable
  198. return res
  199. # 2.3 获取预约参数
  200. final_url = vt_res.json()['returnUrl']
  201. q_params = parse_qs(urlparse(final_url).query)
  202. self.book_params = {k: v[0] for k, v in q_params.items()}
  203. # 2.4 查询日历
  204. url_ma = f"https://{domain}/Global/blsAppointment/ManageAppointment?{urlencode(self.book_params)}"
  205. resp_ma = self._perform_request('GET', url_ma)
  206. if self.config.debug:
  207. self._save_debug_html(resp.text, prefix="Bls_ManageAppointment_Page")
  208. self._check_resp_is_session_expired_or_invalid('APPLICATION PROCESS', resp)
  209. avail_str = self._extract_js_var(resp_ma.text, "var availDates", r"var availDates =(.*?);")
  210. if avail_str:
  211. avail_json = json.loads(avail_str)
  212. # 提取日期
  213. dates = [x['DateText'] for x in avail_json['ad'] if x['SingleSlotAvailable']]
  214. if dates:
  215. res.success = True
  216. res.availability_status = AvailabilityStatus.Available
  217. earliest_date = dates[0]
  218. earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  219. res.earliest_date = earliest_dt
  220. res.availability = [
  221. DateAvailability(
  222. date=datetime.strptime(d, "%Y-%m-%d"),
  223. times=[],
  224. )
  225. for d in dates
  226. ]
  227. else:
  228. # 查询成功,但没有可用日期
  229. res.success = True
  230. res.availability_status = AvailabilityStatus.NoneAvailable
  231. res.availability = []
  232. return res
  233. raise BizLogicError(message='Query page not found required field [var availDates]')
  234. def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
  235. res = VSBookResult()
  236. domain = self.free_config.get("domain")
  237. # 3.1 获取 Manage Page (为了 Token 和 JS 变量)
  238. url_ma = f"https://{domain}/Global/blsAppointment/ManageAppointment?{urlencode(self.book_params)}"
  239. resp_ma = self._perform_request('GET', url_ma)
  240. ma_soup = BeautifulSoup(resp_ma.text, 'html.parser')
  241. ma_form = self._extract_hidden_fields(ma_soup)
  242. req_token = ma_form.get('__RequestVerificationToken')
  243. # 3.2 上传照片
  244. if 'passport_image_url' not in user_inputs:
  245. raise NotFoundError()
  246. photo_bytes = requests.get(user_inputs['passport_image_url']).content
  247. boundary = "----WebKitFormBoundary" + "".join(random.choices(string.ascii_letters + string.digits, k=16))
  248. upload_headers = {
  249. "content-type": f"multipart/form-data; boundary={boundary}",
  250. "requestverificationtoken": req_token,
  251. "x-requested-with": "XMLHttpRequest",
  252. }
  253. body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"\r\n"
  254. f"Content-Type: image/jpeg\r\n\r\n").encode("utf-8") + photo_bytes + f"\r\n--{boundary}--\r\n".encode("utf-8")
  255. up_resp = self.session.post(f"https://{domain}/Global/query/UploadProfileImage", headers=upload_headers, data=body)
  256. if up_resp.status_code !=200:
  257. raise BizLogicError(message='Upload Passport Image failed')
  258. ma_form['ApplicantPhotoId'] = up_resp.json()['fileId']
  259. # 3.3 邮箱 OTP 流程
  260. data_val = self._extract_js_var(resp_ma.text, "win.iframeOpenUrl", r"data=([^&]+)")
  261. # 发送 OTP
  262. headers = {
  263. "X-Requested-With": "XMLHttpRequest"
  264. }
  265. self._perform_request('GET', f"https://{domain}/Global/blsappointment/SendAppointmentVerificationCode?code={data_val}", headers=headers)
  266. # 读取 OTP (Wait 30s max)
  267. otp_code = self._read_otp_email(wait_sec=30)
  268. # 验证 OTP
  269. verify_payload = {
  270. "Code": otp_code,
  271. "Value": ma_form.get('EmailCode'),
  272. "Id": ma_form.get('Id')
  273. }
  274. headers['requestverificationtoken'] = req_token
  275. v_resp = self._perform_request('POST', f"https://{domain}/Global/blsappointment/VerifyEmail", data=verify_payload, headers=headers)
  276. headers.pop('requestverificationtoken')
  277. if not v_resp.json().get('success'):
  278. raise BizLogicError(message='Email verification failed')
  279. ma_form['EmailVerified'] = 'True'
  280. ma_form['EmailVerificationCode'] = otp_code
  281. # 3.4 锁定时间 (简单随机)
  282. target_dt = slot_info.earliest_date
  283. target_date = target_dt.strftime("%Y-%m-%d")
  284. # Query Slots in Day
  285. slot_url = f"https://{domain}/Global/blsappointment/GetAvailableSlotsByDate"
  286. # 构造复杂的 query params... 省略部分非关键参数
  287. slot_params = {
  288. "appointmentDate": target_date,
  289. "locationId": ma_form.get("LocationId"),
  290. "categoryId": ma_form.get("AppointmentCategoryId"),
  291. "visaType": ma_form.get("VisaType"),
  292. "visaSubType": ma_form.get("VisaSubTypeId"),
  293. "applicantCount": 1,
  294. "dataSource": ma_form.get("DataSource"),
  295. "missionId": ma_form.get("MissionId")
  296. }
  297. headers['requestverificationtoken'] = req_token
  298. slots_resp = self._perform_request('POST', slot_url, params=slot_params, headers=headers)
  299. headers.pop('requestverificationtoken')
  300. slots_data = sorted(slots_resp.json(), key=lambda x: -x["Count"]) # 选剩余最多的
  301. if not slots_data or slots_data[0]['Count'] <= 0:
  302. self._log('Available slot times not found')
  303. res.success = False
  304. return res
  305. target_time = slots_data[0]['Name']
  306. ma_form['ServerAppointmentDate'] = target_date
  307. ma_form['AppointmentDetailsList'] = '[]'
  308. # 这里的 key 是动态的 ID,需重新解析 ID
  309. date_id = re.search(r'AppointmentDate(\d+)', str(ma_soup)).group(1)
  310. slot_id = re.search(r'AppointmentSlot(\d+)', str(ma_soup)).group(1)
  311. ma_form[f'AppointmentDate{date_id}'] = target_date
  312. ma_form[f'AppointmentSlot{slot_id}'] = target_time
  313. # 3.5 再次验证码 & 提交 ManageAppointment
  314. captcha_token = self._solve_bls_captcha(data_val)
  315. ma_form['CaptchaData'] = captcha_token
  316. final_ma_resp = self._perform_request('POST', f"https://{domain}/Global/BLSAppointment/ManageAppointment", data=ma_form, headers=headers)
  317. appt_model_id = final_ma_resp.json().get('model', {}).get('Id')
  318. if not appt_model_id:
  319. raise NotFoundError(message='Appointment model id not found')
  320. # 3.6 填写申请表 (VisaAppointmentForm)
  321. # 获取页面 -> 解析 JS 变量 -> 映射 UserInfo -> 提交
  322. # 这里逻辑较深,核心是映射。简化为提交一个空的 applicants JSON,实际需完整映射。
  323. # 假设 _fill_applicant_form 做了这些工作
  324. self._submit_final_form(appt_model_id, user_inputs, self.book_params, req_token)
  325. # 成功,返回 Liveness 链接
  326. Liveness_page = f"https://{domain}/Global/BlsAppointment/livenessView?id={appt_model_id}"
  327. session_data = self._save_http_session(Liveness_page)
  328. res.success = True
  329. res.account = self.config.account.username
  330. res.session_id = session_data['session_id']
  331. res.book_date = target_date
  332. res.book_time = target_time
  333. self._log(f"Book Success. Liveness URL: {res.payment_link}")
  334. return res
  335. def _get_proxy_url(self):
  336. # 构造代理
  337. proxy_url = ""
  338. if self.config.proxy.ip:
  339. s = self.config.proxy
  340. if s.username:
  341. proxy_url = f"{s.scheme}://{s.username}:{s.password}@{s.ip}:{s.port}"
  342. else:
  343. proxy_url = f"{s.scheme}://{s.ip}:{s.port}"
  344. return proxy_url
  345. def _save_debug_html(self, content: str, prefix: str = "debug"):
  346. save_dir = "debug_pages"
  347. if not os.path.exists(save_dir):
  348. os.makedirs(save_dir)
  349. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  350. filename = f"{save_dir}/{prefix}_{timestamp}.html"
  351. with open(filename, "w", encoding="utf-8") as f:
  352. f.write(content)
  353. self._log(f"HTML saved to: {filename}")
  354. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  355. """
  356. 统一 HTTP 请求封装,严格复刻 C++ 逻辑:
  357. 1. 发送 OPTIONS 请求
  358. 2. 发送实际请求
  359. """
  360. resp = self.session.request(method, url, headers=headers, data=data, json=json_data, params=params, timeout=30)
  361. if self.config.debug:
  362. self._log(f'[perform request] Response={resp.text}\nMethod={method}, Url={url}, Data={data}, JsonData={json_data}, Params={params}')
  363. if resp.status_code == 200:
  364. return resp
  365. elif resp.status_code == 401:
  366. self.is_healthy = False
  367. raise SessionExpiredOrInvalidError()
  368. elif resp.status_code == 403:
  369. raise PermissionDeniedError()
  370. elif resp.status_code == 429:
  371. self.is_healthy = False
  372. raise RateLimiteddError()
  373. else:
  374. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  375. def _extract_captcha_data(self, tmp_file):
  376. # 1. 加载文件
  377. html_file_path = Path(tmp_file).resolve()
  378. self.page.get(f'file://{html_file_path}')
  379. # 2. 定位主容器 (作为后续查找的基准,减少全局扫描)
  380. main_div = self.page.ele('#captcha-main-div', timeout=5)
  381. if not main_div:
  382. raise BizLogicError(message='Captcha main container not found')
  383. # --- 3. 提取提示数字 ---
  384. # 假设结构是 main -> div -> div[1] (header)
  385. # 使用相对 XPath 定位 header 区域
  386. header_ele = main_div.ele('xpath:./div/div[1]')
  387. caption_text = ""
  388. if header_ele:
  389. # 遍历子元素寻找可见的提示语
  390. for child in header_ele.children():
  391. # 这里的 is_displayed 检查是否有大小,is_covered 检查是否被遮挡
  392. if child.states.is_displayed and not child.states.is_covered:
  393. caption_text = child.text
  394. if caption_text: # 找到文本就跳出
  395. break
  396. # 安全提取数字
  397. number_match = re.search(r'\d+', caption_text)
  398. if not number_match:
  399. # 如果没找到数字,返回错误或特定的 status
  400. raise BizLogicError(message="No number found in caption")
  401. number = number_match.group()
  402. # --- 4. 提取图片 ID ---
  403. images_ids = []
  404. # 优化策略:直接查找所有 class 为 captcha-img 的图片元素
  405. # 语法: tag:img @@ class:captcha-img
  406. all_imgs = main_div.eles('tag:img@@class:captcha-img')
  407. for img in all_imgs:
  408. # 1. 检查可见性 (有尺寸且未被遮挡)
  409. if img.states.has_rect and not img.states.is_covered:
  410. # 2. 检查 src 属性
  411. src = img.attr('src')
  412. if src and src.startswith('data:image'):
  413. # 3. 获取父级元素的 ID (根据原逻辑,ID 在 img 的父级容器上)
  414. parent_id = img.parent().attr('id')
  415. if parent_id:
  416. images_ids.append(parent_id)
  417. data = {
  418. "number": number,
  419. "image_ids": images_ids,
  420. }
  421. return data
  422. def _solve_bls_captcha(self, data='') -> Optional[str]:
  423. """
  424. 验证码处理:获取图片 -> 调用远程 OCR 服务 -> 提交验证
  425. """
  426. domain = self.free_config.get("domain")
  427. url = f"https://{domain}/Global/NewCaptcha/GenerateCaptcha"
  428. if data:
  429. url = f"https://{domain}/Global/CaptchaPublic/GenerateCaptcha?data={data}"
  430. resp = self._perform_request("GET", url)
  431. if self.config.debug:
  432. self._save_debug_html(resp.text, prefix="Bls_Captcha_Page")
  433. self._check_resp_is_session_expired_or_invalid('Please select all boxes with number', resp)
  434. tmpfile = os.path.join(self.root_workspace, "tmp.html")
  435. with open(tmpfile, 'w', encoding='utf-8') as tfp:
  436. tfp.write(resp.text)
  437. soup = BeautifulSoup(resp.text, 'html.parser')
  438. extract_data = self._extract_captcha_data(tmpfile)
  439. numbers = extract_data['number']
  440. image_ids = extract_data['image_ids']
  441. selected_ids = []
  442. for sid in image_ids:
  443. div = soup.find("div", id=sid)
  444. img = div.find("img")
  445. src = img.get("src")
  446. base64_data = src.split("base64,", 1)[1]
  447. img_bytes = base64.b64decode(base64_data)
  448. ocr_output = self.ocr_engine.inference_bytes(img_bytes)
  449. ocr_res = ocr_output.replace('$', '')[:3]
  450. self._log(f'ocr captcha id={sid} result={ocr_res}, target={numbers}')
  451. if ocr_res == numbers:
  452. selected_ids.append(sid)
  453. if not selected_ids:
  454. raise BizLogicError(message='Captcha selected ids is empty')
  455. # 3. 提交选中结果
  456. self._log(f'select_ids={selected_ids}')
  457. form = self._extract_hidden_fields(soup)
  458. form['SelectedImages'] = ",".join(selected_ids)
  459. submit_url = f"https://{domain}/Global/{'CaptchaPublic' if data else 'NewCaptcha'}/SubmitCaptcha"
  460. headers = {
  461. "X-Requested-With": "XMLHttpRequest"
  462. }
  463. resp = self._perform_request('POST', submit_url, headers=headers, data=form)
  464. j = resp.json()
  465. if j.get('success'):
  466. if data:
  467. return resp.json()['captcha']
  468. else:
  469. return resp.json()['cd']
  470. else:
  471. # 存盘所有错误验证码后续进行数据分析
  472. self._log('Captcha Selection Invalid, Saving important data to data/bls_captcha')
  473. for img in soup.select("img.captcha-img"):
  474. src = img.get("src", "")
  475. if not src.startswith("data:image"):
  476. continue
  477. b64 = src.split("base64,", 1)[1]
  478. with open(f'data/bls_captcha/{uuid.uuid4().hex}.jpg', "wb") as fp:
  479. fp.write(base64.b64decode(b64))
  480. raise BizLogicError(message="Sovle captcha failed")
  481. def _extract_hidden_fields(self, soup) -> Dict:
  482. params = {}
  483. form = soup.find("form")
  484. if form:
  485. for inp in form.find_all("input"):
  486. name = inp.get("name")
  487. if name: params[name] = inp.get("value", "")
  488. else:
  489. self._log('Form element not found')
  490. return params
  491. def _extract_js_var(self, html, context, pattern):
  492. # 简单正则提取
  493. if context in html:
  494. match = re.search(pattern, html)
  495. if match: return match.group(1)
  496. return ""
  497. def _construct_visatype_payload(self, apt_config, html: str, soup: BeautifulSoup) -> Optional[Dict]:
  498. """
  499. 构造 VisaType 提交参数 (对应原代码 parse_visatype_form)
  500. """
  501. # 基础表单参数 (__RequestVerificationToken 等)
  502. params = self._extract_hidden_fields(soup)
  503. # 提取页面中的 JS 数据变量
  504. def get_js_data(var_name):
  505. try:
  506. # 匹配 var name = [...]; 结构
  507. pattern = f"var {var_name}\\s*=\\s*(.*?);"
  508. match = re.search(pattern, html, re.DOTALL)
  509. if match:
  510. return json.loads(match.group(1))
  511. except Exception as e:
  512. self._log(f"Failed to parse JS var {var_name}: {e}")
  513. return []
  514. # 读取配置
  515. cfg_jur = apt_config.get("jurisdiction")
  516. cfg_loc = apt_config.get("location")
  517. cfg_type = apt_config.get("visa_type")
  518. cfg_subtype = apt_config.get("visa_subtype")
  519. cfg_cat = apt_config.get("appointment_category")
  520. jur_value = None
  521. loc_value = None
  522. type_value = None
  523. subtype_value = None
  524. cat_value = None
  525. jur_id = None
  526. loc_id = None
  527. type_id = None
  528. subtype_id = None
  529. cat_id = None
  530. tmpfile = os.path.join(self.root_workspace, "tmp.html")
  531. with open(tmpfile, 'w', encoding='utf-8') as tfp:
  532. tfp.write(html)
  533. self.page.get(f'file://{tmpfile}')
  534. # 匹配 ID
  535. app_category_labels = self.page.eles(f'Appointment Category', timeout=1)
  536. for app_category_label in app_category_labels:
  537. if app_category_label.states.has_rect and app_category_label.tag == 'label':
  538. eid = app_category_label.after('tag:input').attr('id')
  539. cat_id = int(''.join(filter(str.isdigit, eid)))
  540. break
  541. jurisdiction_labels = self.page.eles(f'Jurisdiction', timeout=1)
  542. if jurisdiction_labels:
  543. for jurisdiction_label in jurisdiction_labels:
  544. if jurisdiction_label.states.has_rect and jurisdiction_label.tag == 'label':
  545. eid = jurisdiction_label.after('tag:input').attr('id')
  546. jur_id = int(''.join(filter(str.isdigit, eid)))
  547. break
  548. location_labels = self.page.eles(f'Location', timeout=1)
  549. for location_label in location_labels:
  550. if location_label.states.has_rect and location_label.tag == 'label':
  551. eid = location_label.after('tag:input', index=2).attr('id')
  552. loc_id = int(''.join(filter(str.isdigit, eid)))
  553. break
  554. visa_type_labels = self.page.eles(f'Visa Type', timeout=1)
  555. for visa_type_label in visa_type_labels:
  556. if visa_type_label.states.has_rect and visa_type_label.tag == 'label':
  557. eid = visa_type_label.after('tag:input').attr('id')
  558. type_id = int(''.join(filter(str.isdigit, eid)))
  559. break
  560. visa_subtype_labels = self.page.eles(f'Visa Sub Type', timeout=1)
  561. for visa_subtype_label in visa_subtype_labels:
  562. if visa_subtype_label.states.has_rect and visa_subtype_label.tag == 'label':
  563. eid = visa_subtype_label.after('tag:input').attr('id')
  564. subtype_id = int(''.join(filter(str.isdigit, eid)))
  565. break
  566. jurisdiction_list = get_js_data("jurisdictionData")
  567. location_list = get_js_data("locationData")
  568. visa_type_list = get_js_data("visaIdData")
  569. visa_subtype_list = get_js_data("visasubIdData")
  570. app_category_list = get_js_data("AppointmentCategoryIdData")
  571. # 4. 匹配 Value
  572. # (A) Appointment Category
  573. for item in app_category_list:
  574. if item.get("Name") == cfg_cat:
  575. cat_value = item.get("Id")
  576. break
  577. # (B) Jurisdiction (如果配置了)
  578. if cfg_jur and jurisdiction_list:
  579. for item in jurisdiction_list:
  580. if item.get("Name") == cfg_jur:
  581. jur_value = item.get("Id")
  582. break
  583. # (C) Location
  584. for item in location_list:
  585. if item.get("Name") == cfg_loc:
  586. loc_value = item.get("Id")
  587. break
  588. # (D) Visa Type (需匹配 LocationId)
  589. if loc_value:
  590. for item in visa_type_list:
  591. # 比较 Name 和 LocationId
  592. if item.get("Name") == cfg_type and str(item.get("LocationId")) == str(loc_value):
  593. type_value = item.get("Id")
  594. break
  595. # (E) Visa SubType (需匹配 VisaType Value)
  596. if type_value:
  597. for item in visa_subtype_list:
  598. # BLS 逻辑: visasubIdData 中的 Value 字段对应 VisaTypeId
  599. if item.get("Name") == cfg_subtype and str(item.get("Value")) == str(type_value):
  600. subtype_value = item.get("Id")
  601. break
  602. # 5. 构造动态参数 & 校验
  603. if not cat_value:
  604. raise NotFoundError(message=f"Config: AppCategory '{cfg_cat}' not found")
  605. params[f"AppointmentCategoryId{cat_id}"] = cat_value
  606. if cfg_jur:
  607. if not jur_value:
  608. raise NotFoundError(message=f"Config: Jurisdiction '{cfg_jur}' not found")
  609. params[f"JurisdictionId{jur_id}"] = jur_value
  610. if not loc_value:
  611. raise NotFoundError(message=f"Config: Location '{cfg_loc}' not found")
  612. params[f"Location{loc_id}"] = loc_value
  613. if not type_value:
  614. raise NotFoundError(message=f"Config: VisaType '{cfg_type}' not found for Loc '{cfg_loc}'")
  615. params[f"VisaType{type_id}"] = type_value
  616. if not subtype_value:
  617. raise NotFoundError(message=f"Config: VisaSubType '{cfg_subtype}' not found")
  618. params[f"VisaSubType{subtype_id}"] = subtype_value
  619. # 固定参数
  620. for k in list(params.keys()):
  621. if k.startswith("AppointmentFor"):
  622. params[k] = "Individual"
  623. # 6. 构造 ResponseData (行为轨迹模拟)
  624. # BLS 后端会校验这个字段,模拟用户选择下拉框的时间间隔
  625. response_data = []
  626. current_time = datetime.utcnow()
  627. def add_trace(prefix, val_id):
  628. nonlocal current_time
  629. # 模拟 1-3 秒的操作间隔
  630. duration = random.randint(1000, 3000)
  631. gap = random.randint(500, 1500)
  632. start = current_time
  633. end = start + timedelta(milliseconds=duration)
  634. # BLS 时间格式: 2023-10-27T10:00:00.123Z
  635. fmt = "%Y-%m-%dT%H:%M:%S.%f"
  636. response_data.append({
  637. "Id": f"{prefix}{val_id}",
  638. "Start": start.strftime(fmt)[:-3] + "Z",
  639. "End": end.strftime(fmt)[:-3] + "Z",
  640. "Total": duration,
  641. "Selected": True
  642. })
  643. current_time = end + timedelta(milliseconds=gap)
  644. # 按顺序添加轨迹
  645. add_trace("AppointmentCategoryId", cat_id)
  646. if jur_id: add_trace("JurisdictionId", jur_id)
  647. add_trace("Location", loc_id)
  648. add_trace("VisaType", type_id)
  649. add_trace("VisaSubType", subtype_id)
  650. params["ResponseData"] = json.dumps(response_data)
  651. params["X-Requested-With"] = "XMLHttpRequest"
  652. return params
  653. def _submit_final_form(self, model_id: str, user_inputs: Dict, book_params: Dict, token: str):
  654. """
  655. 提交最终签证申请表 (VisaAppointmentForm)
  656. 对应原代码的: get_visa_appointment_form_html -> parse -> fix_data -> submit
  657. """
  658. domain = self.free_config.get("domain")
  659. # 1. 获取表单页面 (为了提取 JS 变量映射表)
  660. url_get = f"https://{domain}/Global/BlsAppointment/VisaAppointmentForm?appointmentId={model_id}"
  661. # 构造 Referer
  662. ref_query = urlencode(book_params)
  663. referer = f"Global/blsAppointment/ManageAppointment?{ref_query}"
  664. headers = {
  665. 'X-Requested-With': "XMLHttpRequest"
  666. }
  667. resp = self._perform_request('GET', url_get, headers=headers)
  668. headers.pop['X-Requested-With']
  669. html = resp.text
  670. soup = BeautifulSoup(resp.text, 'html.parser')
  671. # 2. 提取基础隐藏域 (包含 __RequestVerificationToken 等)
  672. form_data = self._extract_hidden_fields(soup)
  673. # 3. 提取下拉菜单数据源 (JS Variables)
  674. # BLS 的页面里有很多 var countryData = [...]; 这种数据
  675. def get_list(name):
  676. val = self._extract_js_var(html, f"var {name}", rf"var {name}\s*=\s*(.*?);")
  677. return json.loads(val) if val else []
  678. # 提取关键数据源
  679. country_data = get_list("countryData")
  680. gender_data = get_list("genderData")
  681. marital_data = get_list("maritalStatusData")
  682. occupation_data = get_list("occupationData")
  683. # passport_type_data = get_list("passportTypeData") # 通常默认 Ordinary
  684. # 4. 辅助函数:根据文本找 ID
  685. def find_id(data_list, text_val, default=None):
  686. if not text_val: return default
  687. text_val = str(text_val).lower().strip()
  688. for item in data_list:
  689. if str(item.get("Name")).lower() == text_val:
  690. return item.get("Id")
  691. return default
  692. # 5. 准备日期 (YYYY-MM-DD)
  693. # uinfo 中的日期可能是不同格式,需统一
  694. def fmt_date(d_str):
  695. try:
  696. # 尝试解析常见格式
  697. for fmt in ["%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y"]:
  698. try:
  699. return datetime.strptime(d_str, fmt).strftime("%Y-%m-%d")
  700. except: pass
  701. except: pass
  702. return d_str # 原样返回 fallback
  703. dob = fmt_date(user_inputs.get("birthday", ""))
  704. ppt_issue = fmt_date(user_inputs.get("passport_issue_date", ""))
  705. ppt_expiry = fmt_date(user_inputs.get("passport_expiry_date", ""))
  706. # 自动计算行程日期 (如果未提供,默认一个月后)
  707. try:
  708. travel_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
  709. except: travel_date = ""
  710. # 6. 构造申请人详细数据对象 (JSON)
  711. # 注意:这里的字段名必须严格匹配 BLS 后端实体定义
  712. applicant_detail = {
  713. "ApplicantSerialNo": "1",
  714. "ApplicantId": form_data.get("applicantId", "0"), # 从页面隐藏域提取
  715. "Id": form_data.get("applicantId", "0"),
  716. "ParentId": form_data.get("Id", model_id), # 关联的 Appointment ID
  717. # 基本信息
  718. "FirstName": user_inputs.get("first_name", ""),
  719. "SurName": user_inputs.get("last_name", ""),
  720. "LastName": user_inputs.get("last_name", ""),
  721. "SurnameAtBirth": user_inputs.get("last_name", ""), # 默认同名
  722. "GenderId": find_id(gender_data, user_inputs.get("gender"), "1"), # 默认 Male
  723. "MaritalStatusId": find_id(marital_data, user_inputs.get("marital_status", "Single"), "1"),
  724. "ServerDateOfBirth": dob,
  725. # 国籍/出生地
  726. "PlaceOfBirth": user_inputs.get("place_of_birth", "-"),
  727. "CountryOfBirthId": find_id(country_data, user_inputs.get("nationality"), "0"),
  728. "NationalityAtBirthId": find_id(country_data, user_inputs.get("nationality"), "0"),
  729. "NationalityId": find_id(country_data, user_inputs.get("nationality"), "0"),
  730. # 护照信息
  731. "PassportType": "Ordinary Passport", # 默认
  732. "PassportNo": user_inputs.get("passport_no", ""),
  733. "ServerPassportIssueDate": ppt_issue,
  734. "ServerPassportExpiryDate": ppt_expiry,
  735. "IssuePlace": user_inputs.get("place_of_issue", "-"),
  736. "IssueCountryId": find_id(country_data, user_inputs.get("nationality"), "0"),
  737. # 联系方式 (必填占位符)
  738. "HomeAddressLine1": "-",
  739. "HomeAddressCity": "-",
  740. "HomeAddressPostalCode": "-",
  741. "HomeAddressContactNumber": user_inputs.get("phone", "-"),
  742. "HomeAddressCountryId": find_id(country_data, user_inputs.get("nationality"), "0"),
  743. "EmployerName": "-",
  744. "EmployerAddress": "-",
  745. # 职业
  746. "CurrentOccupationId": find_id(occupation_data, user_inputs.get("occupation", "Others"), "20"),
  747. # 行程信息 (部分写死为常规旅游)
  748. "PurposeOfJourneyId": "Tourism",
  749. "MemberStateDestinationId": "Spain",
  750. "MemberStateFirstEntryId": "Spain",
  751. "NumberOfEntriesRequested": "Multiple Entries",
  752. "IntendedStayDuration": "5",
  753. "ServerTravelDate": travel_date,
  754. "ServerIntendedDateOfArrival": travel_date,
  755. "ServerIntendedDateOfDeparture": travel_date, # 简化
  756. # 费用承担
  757. "CostCoveredById": "By the Applicant himself / herself",
  758. "MeansOfSupportId": "Cash",
  759. # 杂项
  760. "IsMinor": False,
  761. "IsVisaIssuedBefore": False,
  762. "BlsInvitingAuthority": "1", # 这里的 1 通常代表 "No" 或者特定枚举
  763. "PreviousFingerPrintStatus": "2", # 2 通常代表 No
  764. # 邀请人信息 (旅游通常填酒店或空)
  765. "InvitingAuthorityName": "-",
  766. "InvitingAddress": "-",
  767. "InvitingCity": "-",
  768. "InvitingEmail": "no-reply@example.com"
  769. }
  770. # 7. 更新表单数据
  771. # ApplicantsDetailsList 需要是一个 JSON 字符串
  772. form_data['ApplicantsDetailsList'] = json.dumps([applicant_detail])
  773. # 补全其他可能需要的字段
  774. form_data['PreviousFingerPrintStatus_0'] = "2"
  775. form_data['BlsInvitingAuthority_0'] = "1"
  776. form_data["X-Requested-With"] = "XMLHttpRequest"
  777. # 8. 提交
  778. # 注意:提交地址通常和 manage appointment 相同,或者是特定的 Save 接口
  779. # 根据你的原代码,是 Global/BLSAppointment/ManageAppointment
  780. url_post = f"https://{domain}/Global/BLSAppointment/ManageAppointment"
  781. # Headers 需要 Token
  782. headers = {
  783. "Referer": f"https://{domain}/{referer}",
  784. "X-Requested-With": "XMLHttpRequest",
  785. "requestverificationtoken": token
  786. }
  787. # 这里的 form_data['params'] 逻辑在 _extract_hidden_fields 可能会有差异
  788. # 确保 form_data 是扁平的字典
  789. submit_resp = self._perform_request('POST', url_post, data=form_data, headers=headers)
  790. if submit_resp.json().get('success'):
  791. self._log("Final Form Submitted Successfully.")
  792. return True
  793. raise BizLogicError(message='Submit application form failed')
  794. def _read_otp_email(self, wait_sec: int = 60) -> str:
  795. """
  796. 读取 BLS 的 OTP 邮件
  797. """
  798. master_email = "visafly666@gmail.com"
  799. recipient = self.config.account.username
  800. sender = "Info@blsinternational.com"
  801. subject_keywords = "BLS"
  802. body_keywords = "verification code"
  803. # 设置时间起点 (UTC)
  804. now_utc = datetime.utcnow()
  805. formatted_utc_time = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  806. self._log(f"Waiting for OTP from {sender}...")
  807. # 轮询查收, 每 5 秒查一次
  808. attempts = wait_sec // 5
  809. for i in range(attempts):
  810. # 调用云端接口获取邮件内容
  811. # expiry=300 表示邮件有效搜索窗口为 5 分钟
  812. content_out = VSCloudApi.Instance().fetch_mail_content(
  813. master_email,
  814. sender,
  815. recipient,
  816. subject_keywords,
  817. body_keywords,
  818. formatted_utc_time,
  819. 300
  820. )
  821. # 正则匹配 6 位数字验证码
  822. match = re.search(r'\b\d{6}\b', content_out)
  823. if match:
  824. otp = match.group(0)
  825. self._log("OTP code found: {otp}")
  826. return otp
  827. # 等待下一次轮询
  828. time.sleep(5)
  829. if i % 2 == 0:
  830. self._log("OTP not received yet, retrying...")
  831. # 超时处理
  832. raise NotFoundError(f"OTP email not found within {wait_sec}s")
  833. def _check_resp_is_session_expired_or_invalid(self, keyword, resp) -> bool:
  834. """
  835. 检测是否发生了 Session 过期
  836. """
  837. # 1. 检查最终 URL 是否包含登录页特征
  838. # 这里的判断依据是你提供的日志:Redirect to /Global/Account/LogIn
  839. if "/Account/LogIn" in resp.url or "/Account/Login" in resp.url:
  840. self.is_healthy = False
  841. raise SessionExpiredOrInvalidError()
  842. # 2. (备用) 如果 _perform_request 禁止了重定向,检查 302 Location
  843. if resp.status_code == 302:
  844. location = resp.headers.get("Location", "")
  845. if "/Account/LogIn" in location or "/Account/Login" in location:
  846. self.is_healthy = False
  847. raise SessionExpiredOrInvalidError()
  848. resp_text = resp.text
  849. if not resp_text:
  850. self.is_healthy = False
  851. raise SessionExpiredOrInvalidError()
  852. if keyword not in resp_text:
  853. if 'your session has expired, please login again.' in resp_text.lower():
  854. self.is_healthy = False
  855. raise SessionExpiredOrInvalidError()
  856. def _save_http_session(self, page_url):
  857. """
  858. 提取 cookies, local_storage, 存入 VSCloudApi
  859. """
  860. cookies_dict = {}
  861. # 方式 1: curl_cffi 的 cookies 对象通常支持 get_dict()
  862. if hasattr(self.session.cookies, "get_dict"):
  863. cookies_dict = self.session.cookies.get_dict()
  864. else:
  865. # 方式 2: 迭代 (兼容标准 CookieJar)
  866. for c in self.session.cookies:
  867. cookies_dict[c.name] = c.value
  868. cookies_str = json.dumps(cookies_dict)
  869. # 简单生成 SessionID hash
  870. ua_str = self.user_agent or "unknown_ua"
  871. raw = cookies_str + ua_str + page_url
  872. session_id = hashes.Hash(hashes.SHA256(), backend=default_backend())
  873. session_id.update(raw.encode())
  874. sid = session_id.finalize().hex()
  875. proxy_str = ""
  876. if self.config.proxy.ip:
  877. proxy_str = f"{self.config.proxy.scheme}://"
  878. if self.config.proxy.username:
  879. proxy_str += f"{self.config.proxy.username}:{self.config.proxy.password}@"
  880. proxy_str += f"{self.config.proxy.ip}:{self.config.proxy.port}"
  881. return VSCloudApi.Instance().create_http_session(
  882. sid, cookies_str, "", ua_str, proxy_str, page_url
  883. )
  884. # --- 资源清理核心方法 ---
  885. def cleanup(self):
  886. """
  887. 销毁浏览器并彻底删除临时文件
  888. """
  889. # 1. 关闭浏览器
  890. if self.page:
  891. try:
  892. self.page.quit() # 这会关闭 Chrome 进程
  893. except Exception:
  894. pass # 忽略已关闭的错误
  895. self.page = None
  896. # 2. 删除文件
  897. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  898. if os.path.exists(self.root_workspace):
  899. for _ in range(3):
  900. try:
  901. time.sleep(0.2)
  902. shutil.rmtree(self.root_workspace, ignore_errors=True)
  903. break
  904. except Exception as e:
  905. # 如果删除失败(通常是Windows文件占用),重试
  906. self._log(f"Cleanup retry: {e}")
  907. time.sleep(0.5)
  908. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  909. if os.path.exists(self.root_workspace):
  910. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  911. def __del__(self):
  912. """
  913. 析构函数:当对象被垃圾回收时自动调用
  914. """
  915. self.cleanup()