vfs_plugin.py 52 KB

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