vfs_plugin.py 50 KB

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