vfs_plugin.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. # plugins/vfs_global_plugin.py
  2. import time
  3. import json
  4. import random
  5. import base64
  6. import re
  7. import urllib.parse
  8. from datetime import datetime
  9. from typing import Dict, Any, Optional, List, Tuple, Callable
  10. from curl_cffi import requests, const
  11. # 加密库
  12. from cryptography.hazmat.primitives import serialization, hashes
  13. from cryptography.hazmat.primitives.asymmetric import padding
  14. from cryptography.hazmat.backends import default_backend
  15. from vs_plg import IVSPlg
  16. from vs_types import VSPlgConfig, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  17. from toolkit.vs_cloud_api import VSCloudApi
  18. # ----------------- 静态常量与辅助数据 -----------------
  19. VFS_PUBLIC_KEY_PEM = """-----BEGIN PUBLIC KEY-----
  20. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuupFgB+lYIOtSxrRoHzc
  21. LmCZKJ6+oSbgqgOPzFMM0TasOeLw0NXEn1XfIzXdx75+tegNKwyIZumoh0yhubKs
  22. t59GV321kN0iquYRHrdh3ygfDDHlS9rROQeBqRga0ncSADtbLMrBPqXJjPCoV76y
  23. t92towriKoH75BhiazY0mghm4LjmAWrV0u/GNpV3tk9bxbtHEXGaFmxCJqjg+7x6
  24. 1e5wXLfvpj9w1QsiSWOSJxLOyICz/9ByxXycQQFdNmjnnnwco9Gt/Mi33NYH71j0
  25. 5oXIjklFC4lvJqaqSY5lS7Vwb9oCt9zX9J0Yz4z4e/3V+0jgRnWOFGofyks4FKe2
  26. GQIDAQAB
  27. -----END PUBLIC KEY-----"""
  28. COUNTRY_MAP = {
  29. "china": "CHN", "france": "FRA", "germany": "DEU", "italy": "ITA",
  30. "united kingdom": "GBR", "united states": "USA", "india": "IND",
  31. "russia": "RUS", "turkey": "TUR", "vietnam": "VNM"
  32. }
  33. def get_country_iso3(name: str) -> str:
  34. return COUNTRY_MAP.get(name.lower(), "CHN")
  35. def get_alias_email(email: str, new_domain: str = "gmail-app.com") -> str:
  36. """
  37. 将邮箱域名替换为指定域名(默认 gmail-app.com)
  38. """
  39. if "@" not in email:
  40. raise ValueError(f"Invalid email: {email}")
  41. local_part, _ = email.rsplit("@", 1)
  42. return f"{local_part}@{new_domain}"
  43. def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
  44. # 转换日期到YYYY-MM-DD 固定格式
  45. dt = datetime.strptime(data_str, date_str_format)
  46. return dt.strftime("%Y-%m-%d")
  47. class VfsPlugin(IVSPlg):
  48. def __init__(self, group_id: str):
  49. self.group_id = group_id
  50. self.config: Optional[VSPlgConfig] = None
  51. self.free_config: Dict[str, Any] = {}
  52. self.logger = None
  53. self.session: Optional[requests.Session] = None
  54. self.jwt_token: str = ""
  55. self.user_agent: str = ""
  56. self.real_ip: str = ""
  57. self.is_healthy: bool = True
  58. # 缓存配置
  59. self.center_conf = None
  60. self.category_conf: Dict = {}
  61. self.subcategory_conf: Dict = {}
  62. # 加载公钥
  63. self.public_key = serialization.load_pem_public_key(
  64. VFS_PUBLIC_KEY_PEM.encode(),
  65. backend=default_backend()
  66. )
  67. self.session_create_time: float = 0
  68. def get_group_id(self) -> str:
  69. return self.group_id
  70. def set_config(self, config: VSPlgConfig):
  71. self.config = config
  72. self.free_config = config.free_config or {}
  73. def set_log(self, logger: Callable[[str], None]) -> None:
  74. self.logger = logger
  75. def health_check(self) -> bool:
  76. if not self.is_healthy:
  77. return False
  78. if self.session is None:
  79. return False
  80. if self.config.session_max_life > 0:
  81. current_time = time.time()
  82. elapsed_time = current_time - self.session_create_time
  83. if elapsed_time > self.config.session_max_life * 60:
  84. self._log(f"Session Life ({int(elapsed_time)}s) out of max life limit ({self.config.session_max_life * 60}s), mark as unhealth session")
  85. return False
  86. return True
  87. def create_session(self) -> None:
  88. # 初始化 Session
  89. curlopt = {
  90. const.CurlOpt.MAXAGE_CONN: 1800,
  91. const.CurlOpt.MAXLIFETIME_CONN: 1800,
  92. const.CurlOpt.VERBOSE: self.config.debug,
  93. }
  94. self.session = requests.Session(
  95. proxy=self._get_proxy_url(),
  96. impersonate="chrome124",
  97. curl_options=curlopt,
  98. use_thread_local_curl=False,
  99. http_version=const.CurlHttpVersion.V2TLS
  100. )
  101. # 获取真实IP
  102. self.real_ip = self._get_realnetwork_ip()
  103. # 1. Cloudflare Turnstile
  104. cf_token = self._handle_cloudflare_challenge()
  105. # 2. 准备参数
  106. email = self.config.account.username
  107. password = self.config.account.password
  108. enc_password = self._encrypt_password(password)
  109. mission_code = self.free_config.get("mission_code", "")
  110. country_code = self.free_config.get("country_code", "")
  111. client_src = self._get_client_source()
  112. orange_src = self._get_orange_source(email)
  113. url = "https://lift-api.vfsglobal.com/user/login"
  114. headers = self._get_common_headers(with_auth=False)
  115. headers.update({
  116. "clientsource": client_src,
  117. "orangex": orange_src,
  118. "content-type": "application/x-www-form-urlencoded"
  119. })
  120. data = {
  121. "username": email,
  122. "password": enc_password,
  123. "missioncode": mission_code,
  124. "countrycode": country_code,
  125. "languageCode": "en-US",
  126. "captcha_version": "cloudflare-v1",
  127. "captcha_api_key": cf_token
  128. }
  129. # 3. 发送登录请求
  130. resp = self._perform_request("POST", url, headers=headers, data=data)
  131. resp_json = resp.json()
  132. # 分支 1: 登录直接成功,获取到 Token
  133. if resp_json.get('accessToken'):
  134. self.jwt_token = resp_json["accessToken"]
  135. self._log("Login successful, JWT obtained.")
  136. # 分支 2: 需要 OTP 验证
  137. elif resp_json.get("enableOTPAuthentication"):
  138. self._log("Login requires OTP.")
  139. otp = self._read_otp_email()
  140. # 提交 OTP,如果失败该函数内部应抛出异常
  141. self._submit_login_otp(None, otp)
  142. # 分支 3: 异常情况(既无 Token 也无 OTP)
  143. else:
  144. # 在分支内部抛出异常,包含响应内容方便调试
  145. raise BizLogicError(message=f"Login failed: No access token or OTP flow. Response: {resp_json}")
  146. self.session_create_time = time.time()
  147. self._log("Session created successfully.")
  148. def query(self) -> VSQueryResult:
  149. """查询可预约 Slot"""
  150. result = VSQueryResult()
  151. appt_types = self.free_config.get("appointment_types", [])
  152. if not appt_types:
  153. raise NotFoundError(message="No matching appointment configuration found.")
  154. apt_config = random.choice(appt_types)
  155. self._fetch_configurations(apt_config)
  156. earliest_date = self._query_earliest_slot(apt_config)
  157. result.success = False
  158. result.availability_status = AvailabilityStatus.NoneAvailable
  159. result.visa_type = apt_config.get("visa_type", "")
  160. result.city = apt_config.get("city", "")
  161. result.country = apt_config.get("country", "")
  162. result.routing_key = apt_config.get("routing_key", "")
  163. if earliest_date:
  164. result.success = True
  165. if "WaitList" in earliest_date:
  166. result.availability_status = AvailabilityStatus.Waitlist
  167. else:
  168. result.availability_status = AvailabilityStatus.Available
  169. result.earliest_date = earliest_date
  170. result.availability = [
  171. DateAvailability(
  172. date=earliest_date,
  173. times=[],
  174. )
  175. ]
  176. return result
  177. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  178. """
  179. 执行完整的预约流程,包含:上传文档 -> 添加申请人 -> OTP -> 选时间 -> 锁定 -> 支付
  180. """
  181. user_email = user_inputs.get('email')
  182. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="gmail-app.com")
  183. res = VSBookResult()
  184. slot_routing_key = slot_info.routing_key
  185. from_date = slot_info.earliest_date if slot_info.earliest_date else datetime.now().strftime("%Y-%m-%d")
  186. apt_config = None
  187. appt_types = self.free_config.get("appointment_types", [])
  188. for apt in appt_types:
  189. if apt.get("routing_key") == slot_routing_key:
  190. apt_config = apt
  191. break
  192. if not apt_config:
  193. raise NotFoundError(message="Book: Config missing.")
  194. self._fetch_configurations(apt_config)
  195. sub_cc = apt_config.get("subcategory_code")
  196. sub_conf = self.subcategory_conf.get(sub_cc, {})
  197. # OCR 识别 / 文档上传
  198. ocr_enabled = sub_conf.get("isOCREnable", False)
  199. if ocr_enabled:
  200. self._log("OCR Enabled, uploading documents...")
  201. upload_res = self._upload_applicant_documents(apt_config, user_inputs, upload_res)
  202. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  203. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes") # Base64
  204. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  205. # 需要提供申请号 (Cover Letter)
  206. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  207. # 添加申请人 (核心步骤 1)
  208. final_urn = None
  209. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  210. add_primary_retry = 0
  211. MAX_RETRY = 6
  212. while add_primary_retry < MAX_RETRY:
  213. try:
  214. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  215. if not final_urn:
  216. raise NotFoundError(message="URN not found")
  217. break
  218. except Exception as e:
  219. self._log(f"Add Applicant retry {add_primary_retry}...")
  220. time.sleep(10)
  221. add_primary_retry += 1
  222. if not final_urn:
  223. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken)")
  224. self._log("Applicant Added. URN: {final_urn}")
  225. # 申请人 OTP 验证 (核心步骤 2)
  226. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  227. if otp_enabled:
  228. self._log("Applicant OTP Required.")
  229. if not self._applicant_otp_send(apt_config, final_urn):
  230. raise BizLogicError(message='applicant otp send failed')
  231. # 复用之前的读邮件逻辑
  232. otp_code = self._read_otp_email()
  233. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  234. raise BizLogicError(message='applicant otp verify failed')
  235. # 如果是 Waitlist 模式,直接确认并返回
  236. if is_waitlist:
  237. if self._confirm_waitlist(apt_config, final_urn):
  238. res.success = True
  239. res.urn = final_urn
  240. return res
  241. raise BizLogicError(message='confirm waitlist failed')
  242. # 规则引擎与日期筛选 (核心步骤 3)
  243. expected_start = user_inputs.get("expected_start_date", "")
  244. expected_end = user_inputs.get("expected_end_date", "")
  245. # 计算需要扫描的月份, 如果 expected_start/end 为空,默认使用 from_date 所在月
  246. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  247. self._log(f"Scanning months: {months} (From: {from_date})")
  248. selected_slot_id = ""
  249. selected_slot_date = ""
  250. selected_slot_time_range = ""
  251. # 记录所有有号日期,避免重复处理
  252. all_ads = set()
  253. forbidden_dates = set()
  254. found_slot = False
  255. # 遍历月份寻找 Slot
  256. for m_str in months:
  257. ads = self._query_slot_calendar(apt_config, final_urn, m_str)
  258. # 过滤已知的 slots
  259. new_ads = [d for d in ads if d not in all_ads]
  260. all_ads.update(new_ads)
  261. # 尝试 3 次选择
  262. for _ in range(3):
  263. # 排除 forbidden
  264. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  265. # 规则筛选
  266. sel_dates = self._filter_dates(avail_candidates, expected_start, expected_end)
  267. print(f'avail_candidates={avail_candidates}, sel_dates={sel_dates}')
  268. if not sel_dates:
  269. break
  270. tmp_date = sel_dates[0]
  271. forbidden_dates.add(tmp_date)
  272. # 审计日志
  273. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  274. time.sleep(3)
  275. continue
  276. # 查询具体时间
  277. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  278. if not ats:
  279. time.sleep(3)
  280. continue
  281. # 随机选择一个时间段
  282. sel_tm = random.choice(ats)
  283. selected_slot_id = sel_tm.get("allocationId")
  284. selected_slot_date = tmp_date
  285. selected_slot_time_range = sel_tm.get("slot")
  286. found_slot = True
  287. break
  288. if found_slot:
  289. break
  290. if not found_slot:
  291. self._log("No valid slots found.")
  292. res.success = False
  293. return res
  294. self._log(f"Slot Selected: {selected_slot_date} {selected_slot_time_range} (ID: {selected_slot_id})")
  295. # 服务、费用、最终预约 (核心步骤 4)
  296. self._submit_no_addition_service(final_urn)
  297. amount, currency = self._query_fee(apt_config, final_urn)
  298. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  299. if not schedule_res.get("IsAppointmentBooked"):
  300. self._log(f"IsAppointmentBooked is false")
  301. res.success = False
  302. return res
  303. # 构造返回结果
  304. res.success = True
  305. res.account = self.config.account.username
  306. res.book_date = selected_slot_date
  307. res.book_time = selected_slot_time_range
  308. res.urn = final_urn
  309. res.fee_amount = int(amount * 100)
  310. res.fee_currency = currency
  311. # 处理支付链接
  312. if schedule_res.get("IsPaymentRequired", False):
  313. payload = schedule_res.get("payLoad", "")
  314. payment_url = self._pay_request(payload)
  315. if payment_url:
  316. res.payment_link = payment_url
  317. # 保存 Session
  318. saved_session = self._save_http_session(payment_url)
  319. if saved_session:
  320. res.session_id = saved_session['session_id']
  321. return res
  322. def _log(self, message):
  323. if self.logger:
  324. self.logger(f'[VfsPlugin] [{self.group_id}] {message}')
  325. def _get_proxy_url(self):
  326. # 构造代理
  327. proxy_url = ""
  328. if self.config.proxy.ip:
  329. s = self.config.proxy
  330. if s.username:
  331. proxy_url = f"{s.scheme}://{s.username}:{s.password}@{s.ip}:{s.port}"
  332. else:
  333. proxy_url = f"{s.scheme}://{s.ip}:{s.port}"
  334. return proxy_url
  335. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  336. """
  337. 计算需要查询的月份列表,格式 YYYY-MM-DD (每月1号)
  338. """
  339. fmt = "%Y-%m-%d"
  340. # 默认值处理
  341. try:
  342. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  343. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.now().replace(year=datetime.now().year + 1)
  344. try:
  345. dt_from = datetime.strptime(from_date, fmt)
  346. except:
  347. dt_from = datetime.now()
  348. except:
  349. return []
  350. # 归一化到月初
  351. dt_start = dt_start.replace(day=1)
  352. dt_end = dt_end.replace(day=1)
  353. dt_from = dt_from.replace(day=1)
  354. # 起始点取 max(start, from)
  355. curr = max(dt_start, dt_from)
  356. months = []
  357. while curr <= dt_end:
  358. months.append(curr.strftime(fmt))
  359. # 下个月
  360. if curr.month == 12:
  361. curr = curr.replace(year=curr.year + 1, month=1)
  362. else:
  363. curr = curr.replace(month=curr.month + 1)
  364. return months
  365. def _get_realnetwork_ip(self):
  366. url = "https://api.ipify.org/?format=json"
  367. headers = {
  368. 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  369. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  370. }
  371. resp = self._perform_request('GET', url, headers=headers)
  372. return resp.json()['ip']
  373. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  374. """
  375. 确认加入候补名单 (对应 C++ VFSApi::confirm_waitlist)
  376. """
  377. url = "https://lift-api.vfsglobal.com/appointment/ConfirmWaitlist"
  378. headers = self._get_common_headers(with_auth=True)
  379. headers["content-type"] = "application/json;charset=UTF-8"
  380. data = {
  381. "missionCode": self.free_config.get("mission_code"),
  382. "countryCode": self.free_config.get("country_code"),
  383. "centerCode": apt_config.get("vac_code"),
  384. "loginUser": self.config.account.username,
  385. "urn": urn,
  386. "notificationType": "none",
  387. "CanVFSReachoutToApplicant": True
  388. }
  389. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  390. return resp.json().get("isConfirmed")
  391. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  392. """上传护照图片"""
  393. url = "https://lift-api.vfsglobal.com/appointment/UploadApplicantDocument"
  394. passport_url = user_inputs.get("passport_image_url")
  395. if not passport_url:
  396. raise NotFoundError(message="Missing passport_image_url")
  397. img_resp = requests.get(passport_url, timeout=30)
  398. if img_resp.status_code != 200:
  399. raise BizLogicError(message="Failed to download passport image")
  400. b64_str = base64.b64encode(img_resp.content).decode('utf-8')
  401. headers = self._get_common_headers(with_auth=True)
  402. headers["content-type"] = "application/json;charset=UTF-8"
  403. data = {
  404. "missioncode": self.free_config.get("mission_code"),
  405. "countryCode": self.free_config.get("country_code"),
  406. "centerCode": apt_config.get("vac_code"),
  407. "loginUser": self.config.account.username,
  408. "languageCode": "en-US",
  409. "visaCategoryCode": apt_config.get("subcategory_code"),
  410. "fileBytes": b64_str,
  411. "selfiImageFileBytes": ""
  412. }
  413. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  414. result = resp.json()
  415. result["passportImageFilename"] = "passport_img.jpg"
  416. result["passportImageFileBytes"] = b64_str
  417. return result
  418. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  419. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  420. """
  421. 构造复杂的申请人 JSON payload 并提交
  422. """
  423. url = "https://lift-api.vfsglobal.com/appointment/applicants"
  424. headers = self._get_common_headers(with_auth=True)
  425. headers["content-type"] = "application/json;charset=UTF-8"
  426. #male/Male -> 1, 否则 -> 2
  427. gender_str = str(user_inputs.get("gender", "")).lower()
  428. gender_code = 1 if gender_str == "male" else 2
  429. raw_dial = user_inputs.get("phone_country_code", "86")
  430. dial_code = str(raw_dial)
  431. # to_ddmmyyyy (YYYY-MM-DD -> DD/MM/YYYY)
  432. def _to_ddmmyyyy(d_str):
  433. try:
  434. # 假设输入是 YYYY-MM-DD
  435. return datetime.strptime(d_str, "%Y-%m-%d").strftime("%d/%m/%Y")
  436. except:
  437. return d_str # 原样返回
  438. dob = _to_ddmmyyyy(str(user_inputs.get("birthday", "")))
  439. ppt_exp = _to_ddmmyyyy(str(user_inputs.get("passport_expiry_date", "")))
  440. # --- 构造单个 Applicant 对象 ---
  441. applicant = {
  442. "urn": "",
  443. "arn": "",
  444. "loginUser": self.config.account.username,
  445. # 基本信息 (全部大写)
  446. "firstName": str(user_inputs.get("first_name", "")).upper(),
  447. "middleName": "",
  448. "lastName": str(user_inputs.get("last_name", "")).upper(),
  449. "employerFirstName": "",
  450. "employerLastName": "",
  451. "salutation": "",
  452. "gender": gender_code,
  453. # 联系信息
  454. "contactNumber": str(user_inputs.get("phone", "")),
  455. "dialCode": dial_code,
  456. "employerContactNumber": "",
  457. "employerDialCode": "",
  458. "emailId": str(user_inputs.get("alias_email", "")).upper(),
  459. "employerEmailId": "",
  460. # 证件信息
  461. "passportNumber": str(user_inputs.get("passport_no", "")).upper(),
  462. "confirmPassportNumber": "",
  463. "passportExpirtyDate": ppt_exp,
  464. "dateOfBirth": dob,
  465. "nationalId": None,
  466. # 国籍 (使用全局辅助函数 get_country_iso3)
  467. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  468. # 地址与其它 (大部分为空)
  469. "state": None,
  470. "city": None,
  471. "addressline1": None,
  472. "addressline2": None,
  473. "pincode": None,
  474. "isEndorsedChild": False,
  475. "applicantType": 0,
  476. "vlnNumber": None,
  477. "applicantGroupId": 0,
  478. "parentPassportNumber": "",
  479. "parentPassportExpiry": "",
  480. "dateOfDeparture": None,
  481. "entryType": "",
  482. "eoiVisaType": "",
  483. "passportType": "",
  484. "vfsReferenceNumber": "",
  485. "familyReunificationCerificateNumber": "",
  486. "PVRequestRefNumber": "",
  487. "PVStatus": "",
  488. "PVStatusDescription": "",
  489. "PVCanAllowRetry": True,
  490. "PVisVerified": False,
  491. "eefRegistrationNumber": "",
  492. "isAutoRefresh": True,
  493. "helloVerifyNumber": "",
  494. "OfflineCClink": "",
  495. "idenfystatuscheck": False,
  496. "vafStatus": None,
  497. "SpecialAssistance": "",
  498. "AdditionalRefNo": None,
  499. "juridictionCode": "",
  500. "canInitiateVAF": False,
  501. "canEditVAF": False,
  502. "canDeleteVAF": False,
  503. "canDownloadVAF": False,
  504. "Retryleft": "",
  505. # 真实 IP 注入
  506. "ipAddress": self.real_ip
  507. }
  508. # --- 处理 Reference Number (Cover Letter) ---
  509. if enable_ref:
  510. applicant["referenceNumber"] = str(user_inputs.get("cover_letter", ""))
  511. else:
  512. applicant["referenceNumber"] = None
  513. # --- 处理 OCR 数据 ---
  514. if ocr_enabled:
  515. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  516. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  517. applicant["GUID"] = str(user_inputs.get("guid", ""))
  518. # --- 构造最外层 Payload ---
  519. payload = {
  520. "countryCode": self.free_config.get("country_code"),
  521. "missionCode": self.free_config.get("mission_code"),
  522. "centerCode": apt_config.get("vac_code"),
  523. "loginUser": self.config.account.username,
  524. "visaCategoryCode": apt_config.get("subcategory_code"),
  525. "applicantList": [applicant], # 数组形式
  526. "languageCode": "en-US",
  527. "isWaitlist": is_waitlist,
  528. "isEdit": False,
  529. "feeEntryTypeCode": None,
  530. "feeExemptionTypeCode": None,
  531. "feeExemptionDetailsCode": None,
  532. "juridictionCode": None,
  533. "regionCode": None
  534. }
  535. # --- 发送请求 ---
  536. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  537. # --- 处理响应 ---
  538. return resp.json()["urn"]
  539. def _applicant_otp_send(self, apt_config, urn) -> bool:
  540. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  541. headers = self._get_common_headers(with_auth=True)
  542. headers["content-type"] = "application/json;charset=UTF-8"
  543. data = {
  544. "urn": urn,
  545. "loginUser": self.config.account.username,
  546. "missionCode": self.free_config.get("mission_code"),
  547. "countryCode": self.free_config.get("country_code"),
  548. "centerCode": apt_config.get("vac_code"),
  549. "OTP": "",
  550. "otpAction": "GENERATE",
  551. "languageCode": "en-US"
  552. }
  553. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  554. return resp.json().get("isOTPGenerated")
  555. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  556. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  557. headers = self._get_common_headers(with_auth=True)
  558. headers["datacenter"] = "GERMANY"
  559. headers["content-type"] = "application/json;charset=UTF-8"
  560. data = {
  561. "urn": urn,
  562. "loginUser": self.config.account.username,
  563. "missionCode": self.free_config.get("mission_code"),
  564. "countryCode": self.free_config.get("country_code"),
  565. "centerCode": apt_config.get("vac_code"),
  566. "OTP": otp,
  567. "otpAction": "VALIDATE",
  568. "languageCode": "en-US"
  569. }
  570. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  571. return resp.json().get("isOTPValidated")
  572. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  573. url = "https://lift-api.vfsglobal.com/appointment/calendar"
  574. headers = self._get_common_headers(with_auth=True)
  575. headers["content-type"] = "application/json;charset=UTF-8"
  576. dt_m = datetime.strptime(from_date, "%Y-%m-%d")
  577. converted_date = dt_m.strftime("%d/%m/%Y")
  578. data = {
  579. "missionCode": self.free_config.get("mission_code"),
  580. "countryCode": self.free_config.get("country_code"),
  581. "centerCode": apt_config.get("vac_code"),
  582. "loginUser": self.config.account.username,
  583. "visaCategoryCode": apt_config.get("subcategory_code"),
  584. "fromDate": converted_date,
  585. "urn": urn,
  586. "payCode": ""
  587. }
  588. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  589. calendars = resp.json().get("calendars")
  590. if calendars:
  591. ads_out = []
  592. for item in calendars:
  593. # "MM/DD/YYYY" -> "YYYY-MM-DD"
  594. raw = item.get("date")
  595. ads_out.append(to_yyyymmdd(raw, "%m/%d/%Y"))
  596. return ads_out
  597. return []
  598. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  599. url = "https://lift-api.vfsglobal.com/appointment/timeslot"
  600. headers = self._get_common_headers(with_auth=True)
  601. headers["content-type"] = "application/json;charset=UTF-8"
  602. dt_m = datetime.strptime(slot_date, "%Y-%m-%d")
  603. converted_date = dt_m.strftime("%d/%m/%Y")
  604. data = {
  605. "missionCode": self.free_config.get("mission_code"),
  606. "countryCode": self.free_config.get("country_code"),
  607. "centerCode": apt_config.get("vac_code"),
  608. "loginUser": self.config.account.username,
  609. "visaCategoryCode": apt_config.get("subcategory_code"),
  610. "slotDate": converted_date,
  611. "urn": urn
  612. }
  613. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  614. return resp.json().get("slots")
  615. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  616. url = "https://lift-api.vfsglobal.com/appointment/saveuseractionaudit"
  617. headers = self._get_common_headers(with_auth=True)
  618. headers["content-type"] = "application/json;charset=UTF-8"
  619. # ISO format conversion
  620. dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  621. data = {
  622. "missionCode": self.free_config.get("mission_code"),
  623. "countryCode": self.free_config.get("country_code"),
  624. "centerCode": apt_config.get("vac_code"),
  625. "loginUser": self.config.account.username,
  626. "urn": urn,
  627. "firstEarliestSlotDate": dt.strftime("%d/%m/%Y"),
  628. "action": "schedule",
  629. "ipAddress": self.real_ip,
  630. "eadAppointmentDetail": dt.strftime("%Y-%m-%dT%H:%M:%S")
  631. }
  632. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  633. return resp.json().get("isSavedSuccess", False)
  634. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  635. """
  636. 统一 HTTP 请求封装,严格复刻 C++ 逻辑:
  637. 1. 发送 OPTIONS 请求
  638. 2. 发送实际请求
  639. """
  640. # --- 1. 发送 OPTIONS 请求 ---
  641. try:
  642. # OPTIONS 请求使用相同的 URL 和 headers (部分 header 如 content-length 会被自动处理)
  643. # 某些服务器反爬会检测 OPTIONS 请求
  644. opt_headers = headers.copy() if headers else {}
  645. # 发送 OPTIONS
  646. self.session.request("OPTIONS", url, headers=opt_headers, timeout=10)
  647. # C++ 代码中并不检查 OPTIONS 的返回值,只检查执行是否成功
  648. # 这里我们假设只要不抛出异常即可
  649. except Exception as e:
  650. # 记录警告但不中断流程,防止仅仅是 OPTIONS 失败导致误判
  651. self._log(f"OPTIONS request failed (non-fatal): {str(e)}")
  652. resp = self.session.request(method, url, headers=headers, data=data, json=json_data, params=params, timeout=30)
  653. if self.config.debug:
  654. self._log(f'[perform request] Response={resp.text}\nMethod={method}, Url={url}, Data={data}, JsonData={json_data}, Params={params}')
  655. if resp.status_code == 200:
  656. return resp
  657. elif resp.status_code == 401:
  658. self.is_healthy = False
  659. raise SessionExpiredOrInvalidError()
  660. elif resp.status_code == 403:
  661. raise PermissionDeniedError()
  662. elif resp.status_code == 429:
  663. self.is_healthy = False
  664. raise RateLimiteddError()
  665. else:
  666. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  667. def _encrypt_password(self, password: str) -> str:
  668. ciphertext = self.public_key.encrypt(
  669. password.encode(),
  670. padding.OAEP(
  671. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  672. algorithm=hashes.SHA256(),
  673. label=None
  674. )
  675. )
  676. return base64.b64encode(ciphertext).decode()
  677. def _get_orange_source(self, email: str) -> str:
  678. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  679. payload = f"{email};{timestamp}"
  680. return self._encrypt_password(payload)
  681. def _get_client_source(self) -> str:
  682. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  683. payload = f"GA;{timestamp}Z"
  684. return self._encrypt_password(payload)
  685. def _handle_cloudflare_challenge(self) -> str:
  686. """
  687. 完整实现的 Cloudflare Turnstile 验证逻辑
  688. """
  689. mission = self.free_config.get("mission_code", "")
  690. country = self.free_config.get("country_code", "")
  691. if not mission or not country:
  692. raise NotFoundError(message="Missing mission_code or country_code in free_config")
  693. website_url = f"https://visa.vfsglobal.com/{country}/en/{mission}/login"
  694. # 构造代理字符串传给打码平台 (格式: http://user:pass@ip:port)
  695. proxy_str = self._get_proxy_url()
  696. # 2. 提交任务
  697. self._log(f"Submitting Turnstile task for {website_url}...")
  698. task_out = VSCloudApi.Instance().submit_anti_turnstile_task(proxy_str, website_url)
  699. if not task_out:
  700. raise BizLogicError(message="Failed to submit captcha task to Cloud API")
  701. task_id = str(task_out.get("id"))
  702. if not task_id:
  703. raise BizLogicError(message="Cloud API returned invalid task ID")
  704. # 3. 轮询结果 (超时时间 120秒)
  705. timeout = 120
  706. start_time = time.time()
  707. while time.time() - start_time < timeout:
  708. result_out = VSCloudApi.Instance().get_anti_turnstile_result(task_id)
  709. if not result_out:
  710. time.sleep(3)
  711. continue
  712. # status: 0=Pending, 1=Processing, 2=Success, 3=Failed
  713. status = result_out.get("status", 0)
  714. if status == 2:
  715. raw_result = result_out.get("result", "")
  716. if isinstance(raw_result, str):
  717. data = json.loads(raw_result)
  718. else:
  719. data = raw_result
  720. token = data.get("token")
  721. ua = data.get("userAgent")
  722. cookies_list = data.get("cookies", [])
  723. if not token:
  724. raise BizLogicError("Captcha solved but token is empty")
  725. # A. 设置 User-Agent
  726. if ua:
  727. self.user_agent = ua
  728. self.session.headers["User-Agent"] = ua
  729. # B. 设置 Cookies
  730. if cookies_list:
  731. self._log(f"Syncing {len(cookies_list)} cookies from Captcha solver...")
  732. for cookie in cookies_list:
  733. # 兼容不同的 cookie 格式
  734. c_name = cookie.get("name")
  735. c_value = cookie.get("value")
  736. c_domain = cookie.get("domain", "")
  737. c_path = cookie.get("path", "/")
  738. if c_name and c_value:
  739. self.session.cookies.set(
  740. name=c_name,
  741. value=c_value,
  742. domain=c_domain,
  743. path=c_path
  744. )
  745. self._log("Cloudflare challenge passed.")
  746. return token
  747. elif status == 3: # Failed
  748. err_msg = result_out.get("result", "Unknown error")
  749. raise BizLogicError(message=f"Captcha task failed: {err_msg}")
  750. else:
  751. # Pending / Processing
  752. time.sleep(3)
  753. raise BizLogicError(message="Captcha task timeout (120s)")
  754. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  755. mission = self.free_config.get("mission_code", "")
  756. country = self.free_config.get("country_code", "")
  757. lang = self.free_config.get("language", "en")
  758. route = f"{country}/{lang}/{mission}"
  759. h = {
  760. "accept": "application/json, text/plain, */*",
  761. "accept-language": "en-US,en;q=0.9",
  762. "origin": "https://visa.vfsglobal.com",
  763. "referer": "https://visa.vfsglobal.com/",
  764. "route": route
  765. }
  766. client_src = self._get_client_source()
  767. h["clientsource"] = client_src
  768. if with_auth and self.jwt_token:
  769. h["authorize"] = self.jwt_token
  770. return h
  771. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  772. """
  773. 查询最早 Slot(403 自动绕盾 + 重试)
  774. """
  775. url = "https://lift-api.vfsglobal.com/appointment/CheckIsSlotAvailable"
  776. max_retries = self.free_config.get("slot_query_max_retries", 2)
  777. data = {
  778. "missioncode": self.free_config.get("mission_code"),
  779. "countrycode": self.free_config.get("country_code"),
  780. "vacCode": apt_config.get("vac_code"),
  781. "visaCategoryCode": apt_config.get("subcategory_code"),
  782. "roleName": "Individual",
  783. "loginUser": self.config.account.username,
  784. "payCode": ""
  785. }
  786. headers = self._get_common_headers(with_auth=True)
  787. headers["content-type"] = "application/json;charset=UTF-8"
  788. for attempt in range(1, max_retries + 1):
  789. try:
  790. resp = self._perform_request(
  791. "POST",
  792. url,
  793. headers=headers,
  794. json_data=data
  795. )
  796. break # ✅ 请求成功,跳出重试循环
  797. except PermissionDeniedError:
  798. self._log(f"Earliest slot blocked (403), attempt {attempt}/{max_retries}")
  799. # 最后一次就不再绕盾了
  800. if attempt >= max_retries:
  801. raise PermissionDeniedError()
  802. self._handle_cloudflare_challenge()
  803. self._log("Cloudflare bypass success, retrying...")
  804. continue
  805. # ====== 正常解析响应 ======
  806. if "WaitList" in resp.text:
  807. return "WaitList"
  808. j = resp.json()
  809. if j.get("earliestSlotLists"):
  810. raw_date = j["earliestSlotLists"][0]["date"]
  811. return to_yyyymmdd(raw_date, "%m/%d/%Y %H:%M:%S")
  812. return ""
  813. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  814. # 1. 获取所有中心配置 (query_center)
  815. if not self.center_conf:
  816. self.center_conf = self._query_center()
  817. # 2. 获取 Visa Category 配置
  818. vac_code = apt_config.get("vac_code")
  819. category_code = apt_config.get("category_code")
  820. # 检查目标 category_code 是否已在缓存中
  821. if category_code not in self.category_conf:
  822. visa_categories = []
  823. visa_categories = self._query_visa_category(vac_code)
  824. found = False
  825. for vc in visa_categories:
  826. if vc.get("code") == category_code:
  827. self.category_conf[category_code] = vc
  828. found = True
  829. break
  830. # 如果没找到,可能配置错误,但 C++ 没报错,只继续
  831. if not found:
  832. raise NotFoundError(message=f"{self.group_id} Category code {category_code} not found in VAC {vac_code}")
  833. # 3. 获取 Visa SubCategory 配置
  834. sub_category_code = apt_config.get("subcategory_code")
  835. if sub_category_code not in self.subcategory_conf:
  836. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  837. found = False
  838. for svc in visa_subcategories:
  839. if svc.get("code") == sub_category_code:
  840. self.subcategory_conf[sub_category_code] = svc
  841. found = True
  842. break
  843. if not found:
  844. raise NotFoundError(message=f"{self.group_id} SubCategory code {sub_category_code} not found")
  845. def _query_center(self) -> List:
  846. mission = self.free_config.get("mission_code")
  847. country = self.free_config.get("country_code")
  848. url = f"https://lift-api.vfsglobal.com/master/center/{mission}/{country}/en-US"
  849. headers = self._get_common_headers(with_auth=False)
  850. resp = self._perform_request("GET", url, headers=headers)
  851. return resp.json()
  852. def _query_visa_category(self, center_code: str) -> List:
  853. mission = self.free_config.get("mission_code")
  854. country = self.free_config.get("country_code")
  855. enc_center = urllib.parse.quote(center_code)
  856. url = f"https://lift-api.vfsglobal.com/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  857. headers = self._get_common_headers(with_auth=False)
  858. resp = self._perform_request("GET", url, headers=headers)
  859. return resp.json()
  860. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  861. mission = self.free_config.get("mission_code")
  862. country = self.free_config.get("country_code")
  863. enc_center = urllib.parse.quote(center_code)
  864. enc_cat = urllib.parse.quote(category_code)
  865. url = f"https://lift-api.vfsglobal.com/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  866. headers = self._get_common_headers(with_auth=False)
  867. resp = self._perform_request("GET", url, headers=headers)
  868. return resp.json()
  869. def _read_otp_email(self) -> str:
  870. """
  871. 读取 OTP 邮件
  872. """
  873. master_email = "visafly666@gmail.com"
  874. recipient = self.config.account.username
  875. sender = "donotreply at vfshelpline.com"
  876. subject_keywords = "One Time Password"
  877. body_keywords = "OTP"
  878. now_utc = datetime.utcnow()
  879. formatted_utc_time = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  880. self._log(f"Waiting for OTP email sent after {formatted_utc_time}...")
  881. # 3. 轮询查收
  882. for i in range(12):
  883. content_out = VSCloudApi.Instance().fetch_mail_content(
  884. master_email,
  885. sender,
  886. recipient,
  887. subject_keywords,
  888. body_keywords,
  889. formatted_utc_time,
  890. 300
  891. )
  892. if content_out:
  893. match = re.search(r'\b\d{6}\b', content_out)
  894. if match:
  895. otp = match.group(0)
  896. self._log(f"OTP code found: {otp}")
  897. return otp
  898. time.sleep(5)
  899. raise NotFoundError(message="OTP email not found (timeout)")
  900. def _submit_login_otp(self, cf_token: str, otp: str):
  901. """
  902. 提交 OTP 验证码进行登录
  903. """
  904. self._log("Submitting Login OTP...")
  905. # 1. 准备基础数据
  906. email = self.config.account.username
  907. password = self.config.account.password
  908. enc_password = self._encrypt_password(password)
  909. mission_code = self.free_config.get("mission_code", "")
  910. country_code = self.free_config.get("country_code", "")
  911. # 2. 生成加密 Source (每次请求时间戳不同,建议重新生成)
  912. client_src = self._get_client_source()
  913. orange_src = self._get_orange_source(email)
  914. # 3. 构造请求
  915. url = "https://lift-api.vfsglobal.com/user/login"
  916. headers = self._get_common_headers(with_auth=False)
  917. headers.update({
  918. "clientsource": client_src,
  919. "orangex": orange_src,
  920. "content-type": "application/x-www-form-urlencoded"
  921. })
  922. # 为了稳健,如果传入为空,尝试重新获取。
  923. if not cf_token:
  924. self._log("CF Token is empty, regenerating for OTP...")
  925. cf_token = self._handle_cloudflare_challenge()
  926. data = {
  927. "username": email,
  928. "password": enc_password,
  929. "missioncode": mission_code,
  930. "countrycode": country_code,
  931. "languageCode": "en-US",
  932. "captcha_version": "cloudflare-v1",
  933. "captcha_api_key": cf_token,
  934. "otp": otp # 关键字段:OTP 验证码
  935. }
  936. # 4. 发送请求 (POST form-urlencoded)
  937. resp = self._perform_request("POST", url, headers=headers, data=data)
  938. resp_json = resp.json()
  939. if resp_json["accessToken"]:
  940. self.jwt_token = resp_json["accessToken"]
  941. self._log("OTP Login successful, JWT obtained.")
  942. return
  943. raise PermissionDeniedError(message=resp.text)
  944. def _submit_no_addition_service(self, urn):
  945. url = "https://lift-api.vfsglobal.com/vas/mapvas"
  946. headers = self._get_common_headers(with_auth=True)
  947. headers["content-type"] = "application/json;charset=UTF-8"
  948. data = {
  949. "loginUser": self.config.account.username,
  950. "missionCode": self.free_config.get("mission_code"),
  951. "countryCode": self.free_config.get("country_code"),
  952. "urn": urn,
  953. "applicants": []
  954. }
  955. # C++ 只请求不检查结果,或者只要200就行
  956. self._perform_request("POST", url, headers=headers, json_data=data)
  957. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  958. url = "https://lift-api.vfsglobal.com/appointment/fees"
  959. headers = self._get_common_headers(with_auth=True)
  960. headers["content-type"] = "application/json;charset=UTF-8"
  961. data = {
  962. "missionCode": self.free_config.get("mission_code"),
  963. "countryCode": self.free_config.get("country_code"),
  964. "centerCode": apt_config.get("vac_code"),
  965. "loginUser": self.config.account.username,
  966. "urn": urn,
  967. "languageCode": "en-US"
  968. }
  969. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  970. j = resp.json()
  971. return j.get("totalamount"), j["feeDetails"][0].get("currency")
  972. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  973. url = "https://lift-api.vfsglobal.com/appointment/schedule"
  974. headers = self._get_common_headers(with_auth=True)
  975. headers["content-type"] = "application/json;charset=UTF-8"
  976. data = {
  977. "missionCode": self.free_config.get("mission_code"),
  978. "countryCode": self.free_config.get("country_code"),
  979. "centerCode": apt_config.get("vac_code"),
  980. "loginUser": self.config.account.username,
  981. "urn": urn,
  982. "notificationType": "none",
  983. "paymentdetails": {
  984. "paymentmode": "Online",
  985. "RequestRefNo": "",
  986. "clientId": "",
  987. "merchantId": "",
  988. "amount": amount,
  989. "currency": currency
  990. },
  991. "allocationId": str(slot_id),
  992. "CanVFSReachoutToApplicant": True
  993. }
  994. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  995. return resp.json()
  996. def _pay_request(self, payload) -> str:
  997. # C++: 检查 301/302 Redirect Location
  998. url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={payload}"
  999. headers = {
  1000. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  1001. "referer": "https://visa.vfsglobal.com/",
  1002. "user-agent": self.user_agent
  1003. }
  1004. # allow_redirects=False 以捕获 Location header
  1005. resp = self.session.get(url, headers=headers, allow_redirects=False)
  1006. if resp.status_code in [301, 302]:
  1007. loc = resp.headers.get("Location", "")
  1008. if loc.startswith("http"):
  1009. return loc
  1010. else:
  1011. return "https://online.vfsglobal.com" + loc if loc.startswith("/") else "https://online.vfsglobal.com/" + loc
  1012. else:
  1013. raise NotFoundError(message='payment link not found')
  1014. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  1015. """
  1016. 根据用户的期望范围筛选可用日期
  1017. :param dates: API 返回的可用日期列表 (YYYY-MM-DD)
  1018. :param start_str: 用户期望开始日期 (YYYY-MM-DD)
  1019. :param end_str: 用户期望结束日期 (YYYY-MM-DD)
  1020. :return: 符合要求的日期列表
  1021. """
  1022. # 如果没有设置范围,则不过滤,返回所有日期
  1023. if not start_str or not end_str:
  1024. return dates
  1025. valid_dates = []
  1026. # 截取前10位以防带有时分秒
  1027. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  1028. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  1029. for date_str in dates:
  1030. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  1031. # 比较范围 (闭区间)
  1032. if s_date <= curr_date <= e_date:
  1033. valid_dates.append(date_str)
  1034. random.shuffle(valid_dates)
  1035. return valid_dates
  1036. def _save_http_session(self, page_url):
  1037. """
  1038. 提取 cookies, local_storage, 存入 VSCloudApi
  1039. """
  1040. cookies_dict = {}
  1041. # 方式 1: curl_cffi 的 cookies 对象通常支持 get_dict()
  1042. if hasattr(self.session.cookies, "get_dict"):
  1043. cookies_dict = self.session.cookies.get_dict()
  1044. else:
  1045. # 方式 2: 迭代 (兼容标准 CookieJar)
  1046. for c in self.session.cookies:
  1047. cookies_dict[c.name] = c.value
  1048. cookies_str = json.dumps(cookies_dict)
  1049. # 简单生成 SessionID hash
  1050. ua_str = self.user_agent or "unknown_ua"
  1051. raw = cookies_str + ua_str + page_url
  1052. session_id = hashes.Hash(hashes.SHA256(), backend=default_backend())
  1053. session_id.update(raw.encode())
  1054. sid = session_id.finalize().hex()
  1055. proxy_str = ""
  1056. if self.config.proxy.ip:
  1057. proxy_str = f"{self.config.proxy.scheme}://"
  1058. if self.config.proxy.username:
  1059. proxy_str += f"{self.config.proxy.username}:{self.config.proxy.password}@"
  1060. proxy_str += f"{self.config.proxy.ip}:{self.config.proxy.port}"
  1061. return VSCloudApi.Instance().create_http_session(
  1062. sid, cookies_str, "", ua_str, proxy_str, page_url
  1063. )