vfs_plugin.py 49 KB

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