bls_plugin.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. import re
  2. import os
  3. import base64
  4. import time
  5. import json
  6. import random
  7. import string
  8. from datetime import datetime, timedelta
  9. from pathlib import Path
  10. from urllib.parse import urlparse, parse_qs, urlencode
  11. from typing import Dict, List, Optional, Any
  12. from curl_cffi import requests, const
  13. from bs4 import BeautifulSoup
  14. from cryptography.hazmat.primitives import serialization, hashes
  15. from cryptography.hazmat.primitives.asymmetric import padding
  16. from cryptography.hazmat.backends import default_backend
  17. # 框架依赖
  18. from vs_plg import IVSPlg, VSError
  19. from vs_types import VSPlgConfig, VSQueryResult, VSBookResult, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  20. from vs_log_macros import VSC_INFO, VSC_ERROR, VSC_DEBUG, VSC_WARN
  21. from toolkit.vs_cloud_api import VSCloudApi
  22. from utils.browser_util import get_browser
  23. class BlsPlugin(IVSPlg):
  24. """
  25. BLS 签证预约插件 (精简版)
  26. """
  27. def __init__(self, group_id: str):
  28. self.group_id = group_id
  29. self.config: Optional[VSPlgConfig] = None
  30. self.free_config: Dict[str, Any] = {}
  31. self.session: Optional[requests.Session] = None
  32. # 运行时状态
  33. self.book_params: Dict = {}
  34. self.last_error = VSError(0, "OK")
  35. self.is_healthy = True
  36. # OCR 服务地址默认值
  37. self.ocr_service_url = "http://127.0.0.1:8085/predict/vfcode?model=pytorch"
  38. self.browser = get_browser()
  39. def get_group_id(self) -> str:
  40. return self.group_id
  41. def set_config(self, config: VSPlgConfig):
  42. self.config = config
  43. try:
  44. self.free_config = json.loads(config.free_config) if config.free_config else {}
  45. except:
  46. self.free_config = {}
  47. # 从配置中读取 OCR 服务地址,如果没有则使用默认
  48. if self.free_config.get("ocr_service_url"):
  49. self.ocr_service_url = self.free_config["ocr_service_url"]
  50. def health_check(self) -> bool:
  51. return self.is_healthy
  52. def create_session(self):
  53. self.session = requests.Session(
  54. proxy=self._get_proxy_url(),
  55. impersonate="chrome131",
  56. curl_options={
  57. const.CurlOpt.MAXAGE_CONN: 1800,
  58. const.CurlOpt.VERBOSE: False
  59. }
  60. )
  61. domain = self.free_config.get("domain")
  62. if not domain:
  63. raise NotFoundError(message="Required field [domain] in free config")
  64. # 1.1 获取登录页 & 解析参数
  65. login_url = f"https://{domain}/Global/account/login"
  66. headers = {
  67. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  68. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  69. }
  70. resp = self._perform_request('GET', login_url, headers=headers)
  71. soup = BeautifulSoup(resp.text, 'html.parser')
  72. form_data = self._extract_hidden_fields(soup)
  73. # 解析动态 ID (UserId1, Password1 等)
  74. for inp in soup.find_all('input'):
  75. iid = inp.get('id', '')
  76. if 'UserId' in iid and re.search(r'\d+', iid):
  77. form_data["UserIdKey"] = iid # 暂存 Key
  78. form_data["UserId"] = re.search(r'\d+', iid).group(0)
  79. if 'Password' in iid and re.search(r'\d+', iid):
  80. form_data["PasswordKey"] = iid # 暂存 Key
  81. form_data["Password"] = re.search(r'\d+', iid).group(0)
  82. # 解析 data 参数 (用于验证码)
  83. data_val = self._extract_js_var(resp.text, "iframeOpenUrl", r"data=([^']+)")
  84. # 1.2 处理验证码
  85. captcha_token = self._solve_bls_captcha(data_val)
  86. # 1.3 提交登录
  87. submit_url = f"https://{domain}/Global/account/loginsubmit"
  88. payload = form_data
  89. payload["X-Requested-With"] = "XMLHttpRequest"
  90. payload["CaptchaData"] = captcha_token
  91. # 填入账号密码
  92. if "UserIdKey" in form_data:
  93. payload[form_data["UserIdKey"]] = self.config.account.username
  94. if "PasswordKey" in form_data:
  95. payload[form_data["PasswordKey"]] = self.config.account.password
  96. login_resp = self._perform_request('POST', submit_url, data=payload, headers=headers)
  97. if login_resp.json()['success']:
  98. return
  99. raise BizLogicError(message='Login failed')
  100. # =========================================================================
  101. # 2. 查询流程 (Query)
  102. # =========================================================================
  103. def query(self) -> VSQueryResult:
  104. res = VSQueryResult()
  105. domain = self.free_config.get("domain")
  106. # 2.1 签证类型验证
  107. url_vtv = f"https://{domain}/Global/bls/visatypeverification"
  108. headers = {
  109. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  110. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  111. }
  112. resp = self._perform_request('GET', url_vtv, headers=headers)
  113. form_vtv = self._extract_hidden_fields(BeautifulSoup(resp.text, 'html.parser'))
  114. captcha_token = self._solve_bls_captcha()
  115. form_vtv['CaptchaData'] = captcha_token
  116. form_vtv["X-Requested-With"] = "XMLHttpRequest"
  117. vtv_resp = self._perform_request('POST', f"https://{domain}/Global/bls/VisaTypeVerification", data=form_vtv, headers=headers)
  118. if not vtv_resp.json()['success']:
  119. raise BizLogicError(message='Submit VisaTypeVerification Failed')
  120. # 2.2 签证类型选择
  121. return_url = vtv_resp.json()['returnUrl'] # 包含 data=xxx
  122. data_val = re.search(r"data=([^&]+)", return_url).group(1)
  123. url_vt = f"https://{domain}/Global/bls/visatype?data={data_val}"
  124. vt_resp = self._perform_request('GET', url_vt, headers=headers)
  125. # 这里需要极其复杂的 JS 变量提取 (JS Arrays -> Match Name -> Get ID)
  126. vt_payload = self._construct_visatype_payload(vt_resp.text, BeautifulSoup(vt_resp.text, 'html.parser'))
  127. vt_res = self._perform_request('POST', f"https://{domain}/Global/bls/VisaType", data=vt_payload, headers=headers)
  128. if not vt_res.json()['success']:
  129. if not vt_res.json()['available']:
  130. res.success = False
  131. res.availability_status = AvailabilityStatus.NoneAvailable
  132. return res
  133. # 2.3 获取预约参数
  134. final_url = vt_res.json()['returnUrl']
  135. q_params = parse_qs(urlparse(final_url).query)
  136. self.book_params = {k: v[0] for k, v in q_params.items()}
  137. # 2.4 查询日历
  138. url_ma = f"https://{domain}/Global/blsAppointment/ManageAppointment?{urlencode(self.book_params)}"
  139. resp_ma = self._perform_request('GET', url_ma, headers=headers)
  140. avail_str = self._extract_js_var(resp_ma.text, "var availDates", r"var availDates =(.*?);")
  141. if avail_str:
  142. avail_json = json.loads(avail_str)
  143. # 提取日期
  144. dates = [x['DateText'] for x in avail_json['ad'] if x['SingleSlotAvailable']]
  145. if dates:
  146. res.success = True
  147. res.availability_status = AvailabilityStatus.Available
  148. res.earliest_date = dates[0]
  149. for d in dates:
  150. da = VSQueryResult.DateAvailability(date=d)
  151. da.times.append(VSQueryResult.DateAvailability.TimeSlot(time="00:00", label="Available"))
  152. res.availability.append(da)
  153. else:
  154. res.success = False
  155. res.availability_status = AvailabilityStatus.NoneAvailable
  156. return res
  157. raise BizLogicError(message='Query page not found required field [var availDates]')
  158. def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
  159. res = VSBookResult()
  160. domain = self.free_config.get("domain")
  161. headers = {
  162. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  163. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  164. }
  165. # 3.1 获取 Manage Page (为了 Token 和 JS 变量)
  166. url_ma = f"https://{domain}/Global/blsAppointment/ManageAppointment?{urlencode(self.book_params)}"
  167. resp_ma = self._perform_request('GET', url_ma, headers=headers)
  168. ma_soup = BeautifulSoup(resp_ma.text, 'html.parser')
  169. ma_form = self._extract_hidden_fields(ma_soup)
  170. req_token = ma_form.get('__RequestVerificationToken')
  171. # 3.2 上传照片
  172. if 'passport_image_url' not in user_inputs:
  173. raise NotFoundError()
  174. photo_bytes = requests.get(user_inputs['passport_image_url']).content
  175. boundary = "----WebKitFormBoundary" + "".join(random.choices(string.ascii_letters + string.digits, k=16))
  176. upload_headers = {
  177. "content-type": f"multipart/form-data; boundary={boundary}",
  178. "requestverificationtoken": req_token,
  179. "x-requested-with": "XMLHttpRequest",
  180. }
  181. body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"\r\n"
  182. f"Content-Type: image/jpeg\r\n\r\n").encode("utf-8") + photo_bytes + f"\r\n--{boundary}--\r\n".encode("utf-8")
  183. up_resp = self.session.post(f"https://{domain}/Global/query/UploadProfileImage", headers=upload_headers, data=body)
  184. if up_resp.status_code !=200:
  185. raise BizLogicError(message='Upload Passport Image failed')
  186. ma_form['ApplicantPhotoId'] = up_resp.json()['fileId']
  187. # 3.3 邮箱 OTP 流程
  188. data_val = self._extract_js_var(resp_ma.text, "win.iframeOpenUrl", r"data=([^&]+)")
  189. # 发送 OTP
  190. headers["X-Requested-With"] = "XMLHttpRequest"
  191. self._perform_request('GET', f"https://{domain}/Global/blsappointment/SendAppointmentVerificationCode?code={data_val}", headers=headers)
  192. # 读取 OTP (Wait 30s max)
  193. otp_code = self._read_otp_email(wait_sec=30)
  194. # 验证 OTP
  195. verify_payload = {"Code": otp_code, "Value": ma_form.get('EmailCode'), "Id": ma_form.get('Id')}
  196. headers['requestverificationtoken'] = req_token
  197. v_resp = self._perform_request('POST', f"https://{domain}/Global/blsappointment/VerifyEmail", data=verify_payload, headers=headers)
  198. headers.pop('requestverificationtoken')
  199. if not v_resp.json().get('success'):
  200. raise BizLogicError(message='Email verification failed')
  201. ma_form['EmailVerified'] = 'True'
  202. ma_form['EmailVerificationCode'] = otp_code
  203. # 3.4 锁定时间 (简单随机)
  204. target_date = slot_info.earliest_date
  205. # Query Slots in Day
  206. slot_url = f"https://{domain}/Global/blsappointment/GetAvailableSlotsByDate"
  207. # 构造复杂的 query params... 省略部分非关键参数
  208. slot_params = {
  209. "appointmentDate": target_date,
  210. "locationId": ma_form.get("LocationId"),
  211. "categoryId": ma_form.get("AppointmentCategoryId"),
  212. "visaType": ma_form.get("VisaType"),
  213. "visaSubType": ma_form.get("VisaSubTypeId"),
  214. "applicantCount": 1,
  215. "dataSource": ma_form.get("DataSource"),
  216. "missionId": ma_form.get("MissionId")
  217. }
  218. headers['requestverificationtoken'] = req_token
  219. slots_resp = self._perform_request('POST', slot_url, params=slot_params, headers=headers)
  220. headers.pop('requestverificationtoken')
  221. slots_data = sorted(slots_resp.json(), key=lambda x: -x["Count"]) # 选剩余最多的
  222. if not slots_data or slots_data[0]['Count'] <= 0:
  223. VSC_WARN('bls', 'Available slot times not found')
  224. res.success = False
  225. return res
  226. target_time = slots_data[0]['Name']
  227. ma_form['ServerAppointmentDate'] = target_date
  228. ma_form['AppointmentDetailsList'] = '[]'
  229. # 这里的 key 是动态的 ID,需重新解析 ID
  230. date_id = re.search(r'AppointmentDate(\d+)', str(ma_soup)).group(1)
  231. slot_id = re.search(r'AppointmentSlot(\d+)', str(ma_soup)).group(1)
  232. ma_form[f'AppointmentDate{date_id}'] = target_date
  233. ma_form[f'AppointmentSlot{slot_id}'] = target_time
  234. # 3.5 再次验证码 & 提交 ManageAppointment
  235. captcha_token = self._solve_bls_captcha(data_val)
  236. ma_form['CaptchaData'] = captcha_token
  237. final_ma_resp = self._perform_request('POST', f"https://{domain}/Global/BLSAppointment/ManageAppointment", data=ma_form, headers=headers)
  238. appt_model_id = final_ma_resp.json().get('model', {}).get('Id')
  239. if not appt_model_id:
  240. raise NotFoundError(message='Appointment model id not found')
  241. # 3.6 填写申请表 (VisaAppointmentForm)
  242. # 获取页面 -> 解析 JS 变量 -> 映射 UserInfo -> 提交
  243. # 这里逻辑较深,核心是映射。简化为提交一个空的 applicants JSON,实际需完整映射。
  244. # 假设 _fill_applicant_form 做了这些工作
  245. self._submit_final_form(appt_model_id, user_inputs, self.book_params, req_token)
  246. # 成功,返回 Liveness 链接
  247. Liveness_page = f"https://{domain}/Global/BlsAppointment/livenessView?id={appt_model_id}"
  248. session_data = self._save_http_session(Liveness_page)
  249. res.success = True
  250. res.account = self.config.account.username
  251. res.session_id = session_data['session_id']
  252. res.book_date = target_date
  253. res.book_time = target_time
  254. VSC_INFO("bls_plg", "[%s] Book Success. Liveness URL: %s", self.group_id, res.payment_link)
  255. return res
  256. def _save_debug_html(self, content: str, prefix: str = "debug"):
  257. save_dir = "debug_pages"
  258. if not os.path.exists(save_dir):
  259. os.makedirs(save_dir)
  260. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  261. filename = f"{save_dir}/{prefix}_{self.group_id}_{timestamp}.html"
  262. with open(filename, "w", encoding="utf-8") as f:
  263. f.write(content)
  264. VSC_INFO("bls_plg", "[%s] HTML saved to: %s", self.group_id, filename)
  265. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  266. """
  267. 统一 HTTP 请求封装,严格复刻 C++ 逻辑:
  268. 1. 发送 OPTIONS 请求
  269. 2. 发送实际请求
  270. """
  271. print(f'[perform request] {method} {url}')
  272. resp = self.session.request(method, url, headers=headers, data=data, json=json_data, params=params, timeout=30)
  273. VSC_INFO('bls_plg', resp.text)
  274. if resp.status_code == 200:
  275. return resp
  276. elif resp.status_code == 401:
  277. self.is_healthy = False
  278. raise SessionExpiredOrInvalidError()
  279. elif resp.status_code == 403:
  280. raise PermissionDeniedError()
  281. elif resp.status_code == 429:
  282. self.is_healthy = False
  283. raise RateLimiteddError()
  284. else:
  285. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  286. def _solve_bls_captcha(self, data='') -> Optional[str]:
  287. """
  288. 验证码处理:获取图片 -> 调用远程 OCR 服务 -> 提交验证
  289. """
  290. domain = self.free_config.get("domain")
  291. url = f"https://{domain}/Global/NewCaptcha/GenerateCaptcha"
  292. if data: url = f"https://{domain}/Global/CaptchaPublic/GenerateCaptcha?data={data}"
  293. headers = {
  294. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  295. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  296. }
  297. resp = self._perform_request("GET", url, headers=headers)
  298. with open("tmp.html", 'w') as f:
  299. f.write(resp.text)
  300. selected_ids = []
  301. html_file_path = Path("tmp.html").resolve()
  302. file_url = f'file://{html_file_path}'
  303. self.browser.get(file_url)
  304. captions_ele = self.browser.ele('xpath://*[@id="captcha-main-div"]/div/div[1]', timeout=5)
  305. if not captions_ele:
  306. raise NotFoundError(message='Captions elements not found')
  307. caption_eles = captions_ele.children()
  308. caption_text = ''
  309. for caption in caption_eles:
  310. if not caption.states.is_covered:
  311. caption_text = caption.text
  312. numbers = re.findall(r'\d+', caption_text)[0]
  313. captcha_images_ele = self.browser.ele('xpath://*[@id="captcha-main-div"]/div/div[2]')
  314. captcha_image_eles = captcha_images_ele.children()
  315. rect_dict = {}
  316. for captcha_image in captcha_image_eles:
  317. img = captcha_image.ele('.captcha-img')
  318. if img.states.has_rect:
  319. rect_dict[img._backend_id] = img.states.has_rect
  320. for captcha_image in captcha_image_eles:
  321. img = captcha_image.ele('.captcha-img')
  322. if img.states.has_rect and img.states.is_covered == False:
  323. img_src = img.attr('src')
  324. if img_src and img_src.startswith('data:image'):
  325. base64_data = re.sub('^data:image/.+;base64,', '', img_src)
  326. img_bytes = base64.b64decode(base64_data)
  327. ocr_resp = requests.post(
  328. self.ocr_service_url,
  329. data=img_bytes,
  330. headers={"Content-Type": "application/octet-stream"},
  331. timeout=5
  332. )
  333. if ocr_resp.status_code == 200:
  334. res_json = ocr_resp.json()
  335. ocr_res = res_json.get('data', '').replace('$', '')[:3]
  336. VSC_INFO("bls_plg", f'ocr captcha id={captcha_image.attr("id")} result={ocr_res}, target={numbers}')
  337. if ocr_res == numbers:
  338. eid = captcha_image.attr('id')
  339. selected_ids.append(eid)
  340. else:
  341. raise BizLogicError(message='Captcha server response error')
  342. if not selected_ids:
  343. raise BizLogicError(message='Captcha selected ids is empty')
  344. VSC_INFO("bls_plg", f'select_ids={selected_ids}')
  345. soup = BeautifulSoup(resp.text, 'html.parser')
  346. # 3. 提交选中结果
  347. form = self._extract_hidden_fields(soup)
  348. form['SelectedImages'] = ",".join(selected_ids)
  349. submit_url = f"https://{domain}/Global/{'CaptchaPublic' if data else 'NewCaptcha'}/SubmitCaptcha"
  350. headers["X-Requested-With"] = "XMLHttpRequest"
  351. resp = self._perform_request('POST', submit_url, headers=headers, data=form)
  352. return resp.json()['captcha']
  353. def _extract_hidden_fields(self, soup) -> Dict:
  354. params = {}
  355. form = soup.find("form")
  356. if form:
  357. for inp in form.find_all("input"):
  358. name = inp.get("name")
  359. if name: params[name] = inp.get("value", "")
  360. else:
  361. VSC_WARN('bls_plg', 'Form element not found')
  362. return params
  363. def _extract_js_var(self, html, context, pattern):
  364. # 简单正则提取
  365. if context in html:
  366. match = re.search(pattern, html)
  367. if match: return match.group(1)
  368. return ""
  369. def _construct_visatype_payload(self, html: str, soup: BeautifulSoup) -> Optional[Dict]:
  370. """
  371. 构造 VisaType 提交参数 (对应原代码 parse_visatype_form)
  372. """
  373. # 1. 基础表单参数 (__RequestVerificationToken 等)
  374. params = self._extract_hidden_fields(soup)
  375. # 2. 提取页面中的 JS 数据变量
  376. def get_js_data(var_name):
  377. try:
  378. # 匹配 var name = [...]; 结构
  379. pattern = f"var {var_name}\\s*=\\s*(.*?);"
  380. match = re.search(pattern, html, re.DOTALL)
  381. if match:
  382. return json.loads(match.group(1))
  383. except Exception as e:
  384. VSC_DEBUG("bls_plg", f"Failed to parse JS var {var_name}: {e}")
  385. return []
  386. jurisdiction_list = get_js_data("jurisdictionData")
  387. location_list = get_js_data("locationData")
  388. visa_type_list = get_js_data("visaIdData")
  389. visa_subtype_list = get_js_data("visasubIdData")
  390. app_category_list = get_js_data("AppointmentCategoryIdData")
  391. # 3. 读取配置
  392. cfg_jur = self.free_config.get("jurisdiction")
  393. cfg_loc = self.free_config.get("location")
  394. cfg_type = self.free_config.get("visaType")
  395. cfg_subtype = self.free_config.get("visaSubType")
  396. cfg_cat = self.free_config.get("appointmentCategory", "Normal")
  397. # 4. 匹配 ID
  398. jur_id = None
  399. loc_id = None
  400. type_id = None
  401. subtype_id = None
  402. cat_id = None
  403. # (A) Appointment Category
  404. for item in app_category_list:
  405. if item.get("Name") == cfg_cat:
  406. cat_id = item.get("Id")
  407. break
  408. # (B) Jurisdiction (如果配置了)
  409. if cfg_jur and jurisdiction_list:
  410. for item in jurisdiction_list:
  411. if item.get("Name") == cfg_jur:
  412. jur_id = item.get("Id")
  413. break
  414. # (C) Location
  415. for item in location_list:
  416. if item.get("Name") == cfg_loc:
  417. loc_id = item.get("Id")
  418. break
  419. # (D) Visa Type (需匹配 LocationId)
  420. if loc_id:
  421. for item in visa_type_list:
  422. # 比较 Name 和 LocationId
  423. if item.get("Name") == cfg_type and str(item.get("LocationId")) == str(loc_id):
  424. type_id = item.get("Id")
  425. break
  426. # (E) Visa SubType (需匹配 VisaType Value)
  427. if type_id:
  428. for item in visa_subtype_list:
  429. # BLS 逻辑: visasubIdData 中的 Value 字段对应 VisaTypeId
  430. if item.get("Name") == cfg_subtype and str(item.get("Value")) == str(type_id):
  431. subtype_id = item.get("Id")
  432. break
  433. # 5. 构造动态参数 & 校验
  434. if not cat_id:
  435. raise NotFoundError(message=f"Config: AppCategory '{cfg_cat}' not found")
  436. params[f"AppointmentCategoryId{cat_id}"] = cat_id
  437. if cfg_jur:
  438. if not jur_id:
  439. raise NotFoundError(message=f"Config: Jurisdiction '{cfg_jur}' not found")
  440. params[f"JurisdictionId{jur_id}"] = jur_id
  441. if not loc_id:
  442. raise NotFoundError(message=f"Config: Location '{cfg_loc}' not found")
  443. params[f"Location{loc_id}"] = loc_id
  444. if not type_id:
  445. raise NotFoundError(message=f"Config: VisaType '{cfg_type}' not found for Loc '{cfg_loc}'")
  446. params[f"VisaType{type_id}"] = type_id
  447. if not subtype_id:
  448. raise NotFoundError(message=f"Config: VisaSubType '{cfg_subtype}' not found")
  449. params[f"VisaSubType{subtype_id}"] = subtype_id
  450. # 固定参数
  451. params["AppointmentFor1"] = "Individual"
  452. # 6. 构造 ResponseData (行为轨迹模拟)
  453. # BLS 后端会校验这个字段,模拟用户选择下拉框的时间间隔
  454. response_data = []
  455. current_time = datetime.utcnow()
  456. def add_trace(prefix, val_id):
  457. nonlocal current_time
  458. # 模拟 1-3 秒的操作间隔
  459. duration = random.randint(1000, 3000)
  460. gap = random.randint(500, 1500)
  461. start = current_time
  462. end = start + timedelta(milliseconds=duration)
  463. # BLS 时间格式: 2023-10-27T10:00:00.123Z
  464. fmt = "%Y-%m-%dT%H:%M:%S.%f"
  465. response_data.append({
  466. "Id": f"{prefix}{val_id}",
  467. "Start": start.strftime(fmt)[:-3] + "Z",
  468. "End": end.strftime(fmt)[:-3] + "Z",
  469. "Total": duration,
  470. "Selected": True
  471. })
  472. current_time = end + timedelta(milliseconds=gap)
  473. # 按顺序添加轨迹
  474. add_trace("AppointmentCategoryId", cat_id)
  475. if jur_id: add_trace("JurisdictionId", jur_id)
  476. add_trace("Location", loc_id)
  477. add_trace("VisaType", type_id)
  478. add_trace("VisaSubType", subtype_id)
  479. params["ResponseData"] = json.dumps(response_data)
  480. params["X-Requested-With"] = "XMLHttpRequest"
  481. return params
  482. def _submit_final_form(self, model_id: str, user_inputs: Dict, book_params: Dict, token: str):
  483. """
  484. 提交最终签证申请表 (VisaAppointmentForm)
  485. 对应原代码的: get_visa_appointment_form_html -> parse -> fix_data -> submit
  486. """
  487. domain = self.free_config.get("domain")
  488. headers = {
  489. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  490. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  491. }
  492. # 1. 获取表单页面 (为了提取 JS 变量映射表)
  493. url_get = f"https://{domain}/Global/BlsAppointment/VisaAppointmentForm?appointmentId={model_id}"
  494. # 构造 Referer
  495. ref_query = urlencode(book_params)
  496. referer = f"Global/blsAppointment/ManageAppointment?{ref_query}"
  497. headers['X-Requested-With'] = "XMLHttpRequest"
  498. headers['Referer'] = f"https://{domain}/{referer}"
  499. resp = self._perform_request('GET', url_get, headers=headers)
  500. headers.pop['X-Requested-With']
  501. headers.pop['Referer']
  502. html = resp.text
  503. soup = BeautifulSoup(resp.text, 'html.parser')
  504. # 2. 提取基础隐藏域 (包含 __RequestVerificationToken 等)
  505. form_data = self._extract_hidden_fields(soup)
  506. # 3. 提取下拉菜单数据源 (JS Variables)
  507. # BLS 的页面里有很多 var countryData = [...]; 这种数据
  508. def get_list(name):
  509. val = self._extract_js_var(html, f"var {name}", rf"var {name}\s*=\s*(.*?);")
  510. return json.loads(val) if val else []
  511. # 提取关键数据源
  512. country_data = get_list("countryData")
  513. gender_data = get_list("genderData")
  514. marital_data = get_list("maritalStatusData")
  515. occupation_data = get_list("occupationData")
  516. # passport_type_data = get_list("passportTypeData") # 通常默认 Ordinary
  517. # 4. 辅助函数:根据文本找 ID
  518. def find_id(data_list, text_val, default=None):
  519. if not text_val: return default
  520. text_val = str(text_val).lower().strip()
  521. for item in data_list:
  522. if str(item.get("Name")).lower() == text_val:
  523. return item.get("Id")
  524. return default
  525. # 5. 准备日期 (YYYY-MM-DD)
  526. # uinfo 中的日期可能是不同格式,需统一
  527. def fmt_date(d_str):
  528. try:
  529. # 尝试解析常见格式
  530. for fmt in ["%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y"]:
  531. try:
  532. return datetime.strptime(d_str, fmt).strftime("%Y-%m-%d")
  533. except: pass
  534. except: pass
  535. return d_str # 原样返回 fallback
  536. dob = fmt_date(user_inputs.get("birthday", ""))
  537. ppt_issue = fmt_date(user_inputs.get("passport_issue_date", ""))
  538. ppt_expiry = fmt_date(user_inputs.get("passport_expiry_date", ""))
  539. # 自动计算行程日期 (如果未提供,默认一个月后)
  540. try:
  541. travel_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
  542. except: travel_date = ""
  543. # 6. 构造申请人详细数据对象 (JSON)
  544. # 注意:这里的字段名必须严格匹配 BLS 后端实体定义
  545. applicant_detail = {
  546. "ApplicantSerialNo": "1",
  547. "ApplicantId": form_data.get("applicantId", "0"), # 从页面隐藏域提取
  548. "Id": form_data.get("applicantId", "0"),
  549. "ParentId": form_data.get("Id", model_id), # 关联的 Appointment ID
  550. # 基本信息
  551. "FirstName": user_inputs.get("first_name", ""),
  552. "SurName": user_inputs.get("last_name", ""),
  553. "LastName": user_inputs.get("last_name", ""),
  554. "SurnameAtBirth": user_inputs.get("last_name", ""), # 默认同名
  555. "GenderId": find_id(gender_data, user_inputs.get("gender"), "1"), # 默认 Male
  556. "MaritalStatusId": find_id(marital_data, user_inputs.get("marital_status", "Single"), "1"),
  557. "ServerDateOfBirth": dob,
  558. # 国籍/出生地
  559. "PlaceOfBirth": user_inputs.get("place_of_birth", "-"),
  560. "CountryOfBirthId": find_id(country_data, user_inputs.get("nationality"), "0"),
  561. "NationalityAtBirthId": find_id(country_data, user_inputs.get("nationality"), "0"),
  562. "NationalityId": find_id(country_data, user_inputs.get("nationality"), "0"),
  563. # 护照信息
  564. "PassportType": "Ordinary Passport", # 默认
  565. "PassportNo": user_inputs.get("passport_no", ""),
  566. "ServerPassportIssueDate": ppt_issue,
  567. "ServerPassportExpiryDate": ppt_expiry,
  568. "IssuePlace": user_inputs.get("place_of_issue", "-"),
  569. "IssueCountryId": find_id(country_data, user_inputs.get("nationality"), "0"),
  570. # 联系方式 (必填占位符)
  571. "HomeAddressLine1": "-",
  572. "HomeAddressCity": "-",
  573. "HomeAddressPostalCode": "-",
  574. "HomeAddressContactNumber": user_inputs.get("phone", "-"),
  575. "HomeAddressCountryId": find_id(country_data, user_inputs.get("nationality"), "0"),
  576. "EmployerName": "-",
  577. "EmployerAddress": "-",
  578. # 职业
  579. "CurrentOccupationId": find_id(occupation_data, user_inputs.get("occupation", "Others"), "20"),
  580. # 行程信息 (部分写死为常规旅游)
  581. "PurposeOfJourneyId": "Tourism",
  582. "MemberStateDestinationId": "Spain",
  583. "MemberStateFirstEntryId": "Spain",
  584. "NumberOfEntriesRequested": "Multiple Entries",
  585. "IntendedStayDuration": "5",
  586. "ServerTravelDate": travel_date,
  587. "ServerIntendedDateOfArrival": travel_date,
  588. "ServerIntendedDateOfDeparture": travel_date, # 简化
  589. # 费用承担
  590. "CostCoveredById": "By the Applicant himself / herself",
  591. "MeansOfSupportId": "Cash",
  592. # 杂项
  593. "IsMinor": False,
  594. "IsVisaIssuedBefore": False,
  595. "BlsInvitingAuthority": "1", # 这里的 1 通常代表 "No" 或者特定枚举
  596. "PreviousFingerPrintStatus": "2", # 2 通常代表 No
  597. # 邀请人信息 (旅游通常填酒店或空)
  598. "InvitingAuthorityName": "-",
  599. "InvitingAddress": "-",
  600. "InvitingCity": "-",
  601. "InvitingEmail": "no-reply@example.com"
  602. }
  603. # 7. 更新表单数据
  604. # ApplicantsDetailsList 需要是一个 JSON 字符串
  605. form_data['ApplicantsDetailsList'] = json.dumps([applicant_detail])
  606. # 补全其他可能需要的字段
  607. form_data['PreviousFingerPrintStatus_0'] = "2"
  608. form_data['BlsInvitingAuthority_0'] = "1"
  609. form_data["X-Requested-With"] = "XMLHttpRequest"
  610. # 8. 提交
  611. # 注意:提交地址通常和 manage appointment 相同,或者是特定的 Save 接口
  612. # 根据你的原代码,是 Global/BLSAppointment/ManageAppointment
  613. url_post = f"https://{domain}/Global/BLSAppointment/ManageAppointment"
  614. # Headers 需要 Token
  615. headers = {
  616. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0 Safari/537.36',
  617. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
  618. "Referer": f"https://{domain}/{referer}",
  619. "X-Requested-With": "XMLHttpRequest",
  620. "requestverificationtoken": token
  621. }
  622. # 这里的 form_data['params'] 逻辑在 _extract_hidden_fields 可能会有差异
  623. # 确保 form_data 是扁平的字典
  624. submit_resp = self._perform_request('POST', url_post, data=form_data, headers=headers)
  625. if submit_resp.json().get('success'):
  626. VSC_INFO("bls_plg", "[%s] Final Form Submitted Successfully.", self.group_id)
  627. return True
  628. raise BizLogicError(message='Submit application form failed')
  629. def _read_otp_email(self, wait_sec: int = 60) -> str:
  630. """
  631. 读取 BLS 的 OTP 邮件
  632. """
  633. master_email = "visafly666@gmail.com"
  634. recipient = self.config.account.username
  635. sender = "Info@blsinternational.com"
  636. subject_keywords = "BLS"
  637. body_keywords = "verification code"
  638. # 设置时间起点 (UTC)
  639. now_utc = datetime.utcnow()
  640. formatted_utc_time = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  641. VSC_INFO("bls_plg", "[%s] Waiting for OTP from %s...", self.group_id, sender)
  642. # 轮询查收, 每 5 秒查一次
  643. attempts = wait_sec // 5
  644. for i in range(attempts):
  645. # 调用云端接口获取邮件内容
  646. # expiry=300 表示邮件有效搜索窗口为 5 分钟
  647. content_out = VSCloudApi.Instance().fetch_mail_content(
  648. master_email,
  649. sender,
  650. recipient,
  651. subject_keywords,
  652. body_keywords,
  653. formatted_utc_time,
  654. 300
  655. )
  656. # 正则匹配 6 位数字验证码
  657. match = re.search(r'\b\d{6}\b', content_out)
  658. if match:
  659. otp = match.group(0)
  660. VSC_INFO("bls_plg", "[%s] OTP code found: %s", self.group_id, otp)
  661. return otp
  662. # 等待下一次轮询
  663. time.sleep(5)
  664. if i % 2 == 0:
  665. VSC_DEBUG("bls_plg", "[%s] OTP not received yet, retrying...", self.group_id)
  666. # 超时处理
  667. raise NotFoundError(f"OTP email not found within {wait_sec}s")
  668. def _save_http_session(self, page_url):
  669. """
  670. 提取 cookies, local_storage, 存入 VSCloudApi
  671. """
  672. cookies_dict = {}
  673. # 方式 1: curl_cffi 的 cookies 对象通常支持 get_dict()
  674. if hasattr(self.session.cookies, "get_dict"):
  675. cookies_dict = self.session.cookies.get_dict()
  676. else:
  677. # 方式 2: 迭代 (兼容标准 CookieJar)
  678. for c in self.session.cookies:
  679. cookies_dict[c.name] = c.value
  680. cookies_str = json.dumps(cookies_dict)
  681. # 简单生成 SessionID hash
  682. ua_str = self.user_agent or "unknown_ua"
  683. raw = cookies_str + ua_str + page_url
  684. session_id = hashes.Hash(hashes.SHA256(), backend=default_backend())
  685. session_id.update(raw.encode())
  686. sid = session_id.finalize().hex()
  687. proxy_str = ""
  688. if self.config.proxy.ip:
  689. proxy_str = f"{self.config.proxy.scheme}://"
  690. if self.config.proxy.username:
  691. proxy_str += f"{self.config.proxy.username}:{self.config.proxy.password}@"
  692. proxy_str += f"{self.config.proxy.ip}:{self.config.proxy.port}"
  693. return VSCloudApi.Instance().create_http_session(
  694. sid, cookies_str, "", ua_str, proxy_str, page_url
  695. )