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