bls_plugin.py 45 KB

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