vfs_plugin.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. # plugins/vfs_plugin2.py
  2. import os
  3. import time
  4. import json
  5. import random
  6. import base64
  7. import uuid
  8. import shutil
  9. import re
  10. import socket
  11. import urllib.parse
  12. from datetime import datetime
  13. from typing import Dict, Any, Optional, List, Tuple, Callable
  14. from DrissionPage import ChromiumPage, ChromiumOptions
  15. from DrissionPage.common import Settings
  16. from cryptography.hazmat.primitives import serialization, hashes
  17. from cryptography.hazmat.primitives.asymmetric import padding
  18. from cryptography.hazmat.backends import default_backend
  19. import configure
  20. from vs_plg import IVSPlg
  21. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  22. from toolkit.vs_cloud_api import VSCloudApi
  23. from toolkit.mihomo_tunnel import MihomoTunnel
  24. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  25. VFS_PUBLIC_KEY_PEM = """-----BEGIN PUBLIC KEY-----
  26. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuupFgB+lYIOtSxrRoHzc
  27. LmCZKJ6+oSbgqgOPzFMM0TasOeLw0NXEn1XfIzXdx75+tegNKwyIZumoh0yhubKs
  28. t59GV321kN0iquYRHrdh3ygfDDHlS9rROQeBqRga0ncSADtbLMrBPqXJjPCoV76y
  29. t92towriKoH75BhiazY0mghm4LjmAWrV0u/GNpV3tk9bxbtHEXGaFmxCJqjg+7x6
  30. 1e5wXLfvpj9w1QsiSWOSJxLOyICz/9ByxXycQQFdNmjnnnwco9Gt/Mi33NYH71j0
  31. 5oXIjklFC4lvJqaqSY5lS7Vwb9oCt9zX9J0Yz4z4e/3V+0jgRnWOFGofyks4FKe2
  32. GQIDAQAB
  33. -----END PUBLIC KEY-----"""
  34. COUNTRY_MAP = {
  35. "afghanistan": "AFG", "albania": "ALB", "algeria": "DZA", "andorra": "AND", "angola": "AGO",
  36. "antigua and barbuda": "ATG", "argentina": "ARG", "armenia": "ARM", "australia": "AUS", "austria": "AUT",
  37. "azerbaijan": "AZE", "bahamas": "BHS", "bahrain": "BHR", "bangladesh": "BGD", "barbados": "BRB", "belarus": "BLR",
  38. "belgium": "BEL", "belize": "BLZ", "benin": "BEN", "bhutan": "BTN", "bolivia": "BOL", "bosnia and herzegovina": "BIH",
  39. "botswana": "BWA", "brazil": "BRA", "brunei": "BRN", "bulgaria": "BGR", "burkina faso": "BFA", "burundi": "BDI",
  40. "cabo verde": "CPV", "cambodia": "KHM", "cameroon": "CMR", "canada": "CAN", "central african republic": "CAF",
  41. "chad": "TCD", "chile": "CHL", "china": "CHN", "colombia": "COL", "comoros": "COM", "congo (brazzaville)": "COG",
  42. "congo (kinshasa)": "COD", "costa rica": "CRI", "croatia": "HRV", "cuba": "CUB", "cyprus": "CYP", "czech republic": "CZE",
  43. "denmark": "DNK", "djibouti": "DJI", "dominica": "DMA", "dominican republic": "DOM", "ecuador": "ECU", "egypt": "EGY",
  44. "el salvador": "SLV", "equatorial guinea": "GNQ", "eritrea": "ERI", "estonia": "EST", "eswatini": "SWZ", "ethiopia": "ETH",
  45. "fiji": "FJI", "finland": "FIN", "france": "FRA", "gabon": "GAB", "gambia": "GMB", "georgia": "GEO", "germany": "DEU",
  46. "ghana": "GHA", "greece": "GRC", "grenada": "GRD", "guatemala": "GTM", "guinea": "GIN", "guinea-bissau": "GNB", "guyana": "GUY",
  47. "haiti": "HTI", "honduras": "HND", "hungary": "HUN", "iceland": "ISL", "india": "IND", "indonesia": "IDN", "iran": "IRN",
  48. "iraq": "IRQ", "ireland": "IRL", "israel": "ISR", "italy": "ITA", "jamaica": "JAM", "japan": "JPN", "jordan": "JOR",
  49. "kazakhstan": "KAZ", "kenya": "KEN", "kiribati": "KIR", "korea, north": "PRK", "korea, south": "KOR", "kuwait": "KWT",
  50. "kyrgyzstan": "KGZ", "laos": "LAO", "latvia": "LVA", "lebanon": "LBN", "lesotho": "LSO", "liberia": "LBR", "libya": "LBY",
  51. "liechtenstein": "LIE", "lithuania": "LTU", "luxembourg": "LUX", "madagascar": "MDG", "malawi": "MWI", "malaysia": "MYS",
  52. "maldives": "MDV", "mali": "MLI", "malta": "MLT", "marshall islands": "MHL", "mauritania": "MRT", "mauritius": "MUS",
  53. "mexico": "MEX", "micronesia": "FSM", "moldova": "MDA", "monaco": "MCO", "mongolia": "MNG", "montenegro": "MNE", "morocco": "MAR",
  54. "mozambique": "MOZ", "myanmar": "MMR", "namibia": "NAM", "nauru": "NRU", "nepal": "NPL", "netherlands": "NLD", "new zealand": "NZL",
  55. "nicaragua": "NIC", "niger": "NER", "nigeria": "NGA", "north macedonia": "MKD", "norway": "NOR", "oman": "OMN", "pakistan": "PAK",
  56. "palau": "PLW", "panama": "PAN", "papua new guinea": "PNG", "paraguay": "PRY", "peru": "PER", "philippines": "PHL", "poland": "POL",
  57. "portugal": "PRT", "qatar": "QAT", "romania": "ROU", "russia": "RUS", "rwanda": "RWA", "saudi arabia": "SAU", "senegal": "SEN",
  58. "serbia": "SRB", "seychelles": "SYC", "sierra leone": "SLE", "singapore": "SGP", "slovakia": "SVK", "slovenia": "SVN",
  59. "solomon islands": "SLB", "somalia": "SOM", "south africa": "ZAF", "spain": "ESP", "sri lanka": "LKA", "sudan": "SDN",
  60. "suriname": "SUR", "sweden": "SWE", "switzerland": "CHE", "syria": "SYR", "tajikistan": "TJK", "tanzania": "TZA", "thailand": "THA",
  61. "timor-leste": "TLS", "togo": "TGO", "tonga": "TON", "tunisia": "TUN", "turkey": "TUR", "turkmenistan": "TKM", "uganda": "UGA",
  62. "ukraine": "UKR", "united arab emirates": "ARE", "united kingdom": "GBR", "united states": "USA", "uruguay": "URY", "uzbekistan": "UZB",
  63. "vanuatu": "VUT", "venezuela": "VEN", "vietnam": "VNM", "yemen": "YEM", "zambia": "ZMB", "zimbabwe": "ZWE"
  64. }
  65. def get_country_iso3(name: str) -> str:
  66. return COUNTRY_MAP.get(name.lower(), "CHN")
  67. def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
  68. try:
  69. dt = datetime.strptime(data_str, date_str_format)
  70. return dt.strftime(target_format)
  71. except:
  72. return data_str
  73. def get_alias_email(email: str, new_domain: str = "gmail-app.com") -> str:
  74. """
  75. 将邮箱域名替换为指定域名(默认 gmail-app.com)
  76. """
  77. if "@" not in email:
  78. raise ValueError(f"Invalid email: {email}")
  79. local_part, _ = email.rsplit("@", 1)
  80. return f"{local_part}@{new_domain}"
  81. # --- 模拟 Requests Response 对象 ---
  82. class BrowserResponse:
  83. def __init__(self, result_dict):
  84. result_dict = result_dict or {}
  85. self.status_code = result_dict.get('status', 0)
  86. self.text = result_dict.get('body', '')
  87. self.headers = result_dict.get('headers', {})
  88. self.url = result_dict.get('url', '')
  89. self._json = None
  90. def json(self):
  91. if self._json is None:
  92. if not self.text:
  93. return {}
  94. try:
  95. self._json = json.loads(self.text)
  96. except:
  97. self._json = {}
  98. return self._json
  99. @property
  100. def content(self):
  101. return self.text.encode('utf-8')
  102. class VfsPlugin(IVSPlg):
  103. def __init__(self, group_id: str):
  104. self.group_id = group_id
  105. self.config: Optional[VSPlgConfig] = None
  106. self.free_config: Dict[str, Any] = {}
  107. self.logger = None
  108. self.page: Optional[ChromiumPage] = None
  109. self.jwt_token: str = ""
  110. self.real_ip: str = ""
  111. self.is_healthy: bool = True
  112. self.center_conf = None
  113. self.category_conf: Dict = {}
  114. self.subcategory_conf: Dict = {}
  115. self.booking_wait_applied = False
  116. self.public_key = serialization.load_pem_public_key(
  117. VFS_PUBLIC_KEY_PEM.encode(),
  118. backend=default_backend()
  119. )
  120. # --- [核心修改] 并发隔离与资源管理 ---
  121. # 生成唯一实例 ID
  122. self.instance_id = uuid.uuid4().hex[:8]
  123. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  124. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  125. # 持有隧道实例
  126. self.tunnel = None
  127. # 确保根目录存在 (子目录由具体逻辑创建)
  128. if not os.path.exists(self.root_workspace):
  129. os.makedirs(self.root_workspace)
  130. self.session_create_time: float = 0
  131. def get_group_id(self) -> str:
  132. return self.group_id
  133. def set_config(self, config: VSPlgConfig):
  134. self.config = config
  135. self.free_config = config.free_config or {}
  136. def set_log(self, logger: Callable[[str], None]) -> None:
  137. self.logger = logger
  138. def _log(self, message):
  139. if self.logger:
  140. self.logger(f'[VfsPlugin] [{self.group_id}] {message}')
  141. else:
  142. print(f'[VfsPlugin] [{self.group_id}] {message}')
  143. def keep_alive(self):
  144. try:
  145. applicants = self._get_application()
  146. self._log(f'keep_alive request, get applicant resp={applicants}')
  147. except:
  148. self.is_healthy = False
  149. def health_check(self) -> bool:
  150. if not self.is_healthy:
  151. return False
  152. if self.page is None:
  153. return False
  154. # 检查页面是否还活着
  155. try:
  156. if not self.page.run_js("return 1;"):
  157. return False
  158. except:
  159. return False
  160. if self.config.session_max_life > 0:
  161. current_time = time.time()
  162. elapsed_time = current_time - self.session_create_time
  163. if elapsed_time > self.config.session_max_life:
  164. self._log(f"Session expired.")
  165. return False
  166. return True
  167. def create_session(self) -> None:
  168. """
  169. 使用 DrissionPage 创建会话:
  170. 1. 启动浏览器
  171. 2. 导航到登录页
  172. 3. 自动过盾并提取 Token (集成 CloudflareBypasser)
  173. 4. JS fetch 登录
  174. """
  175. self._log(f"Initializing Session (ID: {self.instance_id})...")
  176. co = ChromiumOptions()
  177. def get_free_port():
  178. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  179. s.bind(('', 0))
  180. return s.getsockname()[1]
  181. debug_port = get_free_port()
  182. self._log(f"Assigned Debug Port: {debug_port}")
  183. co.set_local_port(debug_port)
  184. co.set_user_data_path(self.user_data_path)
  185. chrome_path = configure.CHROME_PATH
  186. if not chrome_path:
  187. chrome_path = os.getenv("CHROME_BIN")
  188. if chrome_path and os.path.exists(chrome_path):
  189. co.set_paths(browser_path=chrome_path)
  190. if self.config.proxy and self.config.proxy.ip:
  191. p = self.config.proxy
  192. self._log(f'Current proxy id={p.id}')
  193. if p.username and p.password:
  194. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  195. exit_node = {
  196. "name": "ExitNode",
  197. "type": p.proto,
  198. "server": p.ip,
  199. "port": p.port,
  200. "username": p.username,
  201. "password": p.password
  202. }
  203. relay_node = None
  204. if configure.MIHOMO_RELAY_NODES:
  205. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  206. mihomo_path = configure.MIHOMO_BIN_PATH
  207. if not mihomo_path:
  208. mihomo_path = os.getenv("MIHOMO_BIN")
  209. if not mihomo_path:
  210. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  211. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  212. local_proxy = self.tunnel.start()
  213. self._log(f"Tunnel started at {local_proxy}")
  214. co.set_argument(f'--proxy-server={local_proxy}')
  215. else:
  216. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  217. co.set_argument(f'--proxy-server={proxy_str}')
  218. else:
  219. self._log("[WARN] No proxy configured!")
  220. co.headless(False)
  221. co.set_argument('--no-sandbox')
  222. co.set_argument('--disable-gpu')
  223. co.set_argument('--disable-dev-shm-usage')
  224. co.set_argument('--window-size=1920,1080')
  225. co.set_argument('--disable-blink-features=AutomationControlled')
  226. try:
  227. self.page = ChromiumPage(co)
  228. mission = self.free_config.get("mission_code", "")
  229. country = self.free_config.get("country_code", "")
  230. lang = self.free_config.get("language", "en")
  231. if not mission or not country:
  232. raise BizLogicError("Missing mission/country code config")
  233. login_page_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
  234. self._log(f"Navigating to {login_page_url}...")
  235. self.page.get(login_page_url)
  236. self._log("Handling Cloudflare challenge...")
  237. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  238. cf_token = ""
  239. for i in range(40):
  240. time.sleep(1)
  241. self._handle_cookie_banner()
  242. try:
  243. ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
  244. if ele and ele.value:
  245. cf_token = ele.value
  246. self._log("Cloudflare Turnstile token extracted.")
  247. break
  248. except:
  249. pass
  250. if i > 2:
  251. try:
  252. use_dfs = False
  253. cf_bypasser.click_verification_button(use_dfs)
  254. except Exception as e:
  255. pass
  256. if self.page.ele('tag:form', timeout=0.5) or self.page.ele('#mat-input-0', timeout=0.5):
  257. self._log("Login form detected.")
  258. if i > 5 and not cf_token:
  259. self._log("Form visible but token not found yet...")
  260. # -------------------------------------------------------------
  261. if not cf_token:
  262. try:
  263. cf_token = self.page.ele('@name=cf-turnstile-response').value
  264. except:
  265. pass
  266. if not cf_token:
  267. self._log("[WARN] Could not extract Turnstile token.")
  268. raise BizLogicError(f"Could not extract Turnstile token.")
  269. email = self.config.account.username
  270. password = self.config.account.password
  271. enc_password = self._encrypt_password(password)
  272. client_src = self._get_client_source()
  273. orange_src = self._get_orange_source(email)
  274. url = "https://lift-api.vfsglobal.com/user/login"
  275. headers = self._get_common_headers(with_auth=False)
  276. headers.update({
  277. "clientsource": client_src,
  278. "orangex": orange_src
  279. })
  280. data = {
  281. "username": email,
  282. "password": enc_password,
  283. "missioncode": mission,
  284. "countrycode": country,
  285. "languageCode": "en-US",
  286. "captcha_version": "cloudflare-v1",
  287. "captcha_api_key": cf_token
  288. }
  289. now_utc = datetime.utcnow()
  290. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  291. self._log("Sending Login Request via Browser Fetch...")
  292. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  293. resp_json = resp.json()
  294. if resp_json.get('accessToken'):
  295. self.jwt_token = resp_json["accessToken"]
  296. self._log("Login successful, JWT obtained.")
  297. elif resp_json.get("enableOTPAuthentication"):
  298. self._log("Login requires OTP.")
  299. otp = self._read_otp_email(sent_at=sent_at)
  300. self._submit_login_otp(cf_token, otp)
  301. else:
  302. raise BizLogicError(f"Login failed: {resp.text[:200]}")
  303. self.session_create_time = time.time()
  304. try:
  305. self.real_ip = self._get_realnetwork_ip()
  306. except:
  307. self.real_ip = "0.0.0.0"
  308. except Exception as e:
  309. self._log(f"Create Session Failed: {e}")
  310. time.sleep(3600)
  311. self.cleanup()
  312. raise e
  313. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  314. """查询可预约 Slot"""
  315. result = VSQueryResult()
  316. apt_config = self.free_config.get("apt_configs", {}).get(apt_type.routing_key)
  317. try:
  318. self._fetch_configurations(apt_config)
  319. query_result = self._query_earliest_slot(apt_config)
  320. result.success = False
  321. result.availability_status = AvailabilityStatus.NoneAvailable
  322. if query_result:
  323. result.success = True
  324. if "WaitList" in query_result:
  325. result.availability_status = AvailabilityStatus.Waitlist
  326. else:
  327. earliest_dt = datetime.strptime(query_result, "%Y-%m-%d")
  328. result.availability_status = AvailabilityStatus.Available
  329. result.earliest_date = earliest_dt
  330. result.availability = [DateAvailability(date=earliest_dt, times=[])]
  331. self._log(f"Slot Found! -> {query_result}")
  332. else:
  333. self._log("No slots available.")
  334. except Exception as e:
  335. self._log(f"Query Error: {e}")
  336. raise e
  337. return result
  338. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  339. """
  340. 核心方法:在 DrissionPage 浏览器上下文中注入 JS 执行 fetch
  341. 并记录详细的 Traffic 日志用于分析
  342. """
  343. if not self.page:
  344. raise BizLogicError("Browser session not initialized")
  345. req_url = url
  346. if params:
  347. sep = '&' if '?' in req_url else '?'
  348. req_url += sep + urllib.parse.urlencode(params)
  349. final_headers = headers or {}
  350. fetch_options = {
  351. "method": method.upper(),
  352. "headers": final_headers,
  353. "credentials": "include" # 关键:带上浏览器 Cookie
  354. }
  355. log_body = "None"
  356. if json_data:
  357. json_str = json.dumps(json_data)
  358. fetch_options['body'] = json_str
  359. fetch_options['headers']['Content-Type'] = 'application/json'
  360. log_body = json_str
  361. elif data:
  362. if isinstance(data, dict):
  363. encoded_data = urllib.parse.urlencode(data)
  364. fetch_options['body'] = encoded_data
  365. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  366. log_body = encoded_data
  367. else:
  368. fetch_options['body'] = data
  369. log_body = str(data)
  370. self._log(f"┌── [TRAFFIC REQUEST] {method} {req_url}")
  371. self._log(f"├── Headers: {json.dumps(final_headers)}")
  372. self._log(f"└── Body: {log_body}")
  373. js_script = f"""
  374. const url = "{req_url}";
  375. const options = {json.dumps(fetch_options)};
  376. const startTime = Date.now();
  377. return fetch(url, options)
  378. .then(async response => {{
  379. const text = await response.text();
  380. const headers = {{}};
  381. response.headers.forEach((value, key) => headers[key] = value);
  382. const endTime = Date.now();
  383. return {{
  384. status: response.status,
  385. body: text,
  386. headers: headers,
  387. url: response.url,
  388. duration: endTime - startTime
  389. }};
  390. }})
  391. .catch(error => {{
  392. return {{
  393. status: 0,
  394. body: error.toString(),
  395. headers: {{}},
  396. url: url,
  397. duration: Date.now() - startTime
  398. }};
  399. }});
  400. """
  401. try:
  402. res_dict = self.page.run_js(js_script, timeout=60)
  403. except Exception as e:
  404. self._log(f"[TRAFFIC ERROR] JS Execution failed: {e}")
  405. raise BizLogicError(f"Browser JS Execution Error: {e}")
  406. resp = BrowserResponse(res_dict)
  407. duration = res_dict.get('duration', 0)
  408. resp_preview = resp.text[:1000] + "..." if len(resp.text) > 1000 else resp.text
  409. self._log(f"┌── [TRAFFIC RESPONSE] Status: {resp.status_code} | Time: {duration}ms")
  410. self._log(f"└── Body: {resp_preview}")
  411. if resp.status_code == 200:
  412. return resp
  413. elif resp.status_code == 401:
  414. self.is_healthy = False
  415. raise SessionExpiredOrInvalidError(f"401 Unauthorized: {resp.text[:100]}")
  416. elif resp.status_code == 403:
  417. if "Just a moment" in resp.text or "cloudflare" in resp.text.lower():
  418. self._log(f"[TRAFFIC] HTTP 403 (Cloudflare) detected. Re-verifying (Try {retry_count+1}/3)...")
  419. if retry_count < 3:
  420. new_token = self._refresh_turnstile_token()
  421. if new_token:
  422. self._log("[TRAFFIC] In-page verification success. Retrying...")
  423. if json_data and "captcha_api_key" in json_data:
  424. json_data["captcha_api_key"] = new_token
  425. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  426. raise PermissionDeniedError(f"HTTP 403 Forbidden: {resp.text[:100]}")
  427. elif resp.status_code == 429:
  428. self.is_healthy = False
  429. raise RateLimiteddError(f"429 Rate Limit: {resp.text[:100]}")
  430. elif resp.status_code == 0:
  431. raise BizLogicError(f"Network Error (Fetch Failed): {resp.text}")
  432. else:
  433. if url.endswith("/login") and resp.status_code == 400:
  434. return resp
  435. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  436. def _handle_cookie_banner(self):
  437. """
  438. 处理 OneTrust Cookie 遮挡
  439. 策略:尝试点击“接受所有”,如果点不到就直接移除 DOM
  440. """
  441. try:
  442. # 使用 JS 处理最快,且不会因为元素运动报错
  443. js = """
  444. try {
  445. // 1. 尝试点击 '接受所有' 按钮
  446. var acceptBtn = document.getElementById('onetrust-accept-btn-handler');
  447. if (acceptBtn) {
  448. acceptBtn.click();
  449. return true;
  450. }
  451. // 2. 如果没有按钮,或者还在遮挡,直接把整个 banner 删掉
  452. var banner = document.getElementById('onetrust-banner-sdk');
  453. if (banner) {
  454. banner.style.display = 'none'; // 隐藏
  455. banner.remove(); // 或者移除
  456. return true;
  457. }
  458. } catch(e) {}
  459. return false;
  460. """
  461. self.page.run_js(js)
  462. except:
  463. pass
  464. def _get_proxy_url(self):
  465. if self.config.proxy and self.config.proxy.ip:
  466. s = self.config.proxy
  467. if s.username:
  468. return f"{s.proto}://{s.username}:{s.password}@{s.ip}:{s.port}"
  469. else:
  470. return f"{s.proto}://{s.ip}:{s.port}"
  471. return None
  472. def _get_realnetwork_ip(self):
  473. """
  474. 通过新建标签页获取 IP
  475. 解决 CORS 403 问题:新标签页请求属于 Top-Level Navigation,
  476. 不带 Origin: visa.vfsglobal.com,也不带 credentials,符合 ipify 规则。
  477. """
  478. try:
  479. tab = self.page.new_tab("https://api.ipify.org/?format=json")
  480. if tab.ele('tag:pre'):
  481. json_text = tab.ele('tag:pre').text
  482. else:
  483. json_text = tab.ele('tag:body').text
  484. ip = json.loads(json_text)['ip']
  485. tab.close()
  486. self._log(f"Real Network IP: {ip}")
  487. return ip
  488. except Exception as e:
  489. self._log(f"[WARN] Failed to check IP via new tab: {e}")
  490. try:
  491. if self.page.tabs_count > 1:
  492. tab.close()
  493. except:
  494. pass
  495. return "0.0.0.0"
  496. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  497. # DrissionPage 浏览器会自动带上 Origin, Referer, User-Agent, Sec-CH-UA 等
  498. # 这里只需要补充业务特定的 Headers
  499. mission = self.free_config.get("mission_code", "")
  500. country = self.free_config.get("country_code", "")
  501. lang = self.free_config.get("language", "en")
  502. route = f"{country}/{lang}/{mission}"
  503. h = {
  504. "accept": "application/json, text/plain, */*",
  505. "route": route
  506. }
  507. h["clientsource"] = self._get_client_source()
  508. if with_auth and self.jwt_token:
  509. h["authorize"] = self.jwt_token
  510. return h
  511. def _encrypt_password(self, password: str) -> str:
  512. ciphertext = self.public_key.encrypt(
  513. password.encode(),
  514. padding.OAEP(
  515. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  516. algorithm=hashes.SHA256(),
  517. label=None
  518. )
  519. )
  520. return base64.b64encode(ciphertext).decode()
  521. def _get_orange_source(self, email: str) -> str:
  522. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  523. payload = f"{email};{timestamp}"
  524. return self._encrypt_password(payload)
  525. def _get_client_source(self) -> str:
  526. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  527. payload = f"GA;{timestamp}Z"
  528. return self._encrypt_password(payload)
  529. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  530. url = "https://lift-api.vfsglobal.com/appointment/CheckIsSlotAvailable"
  531. data = {
  532. "missioncode": self.free_config.get("mission_code"),
  533. "countrycode": self.free_config.get("country_code"),
  534. "vacCode": apt_config.get("vac_code"),
  535. "visaCategoryCode": apt_config.get("subcategory_code"),
  536. "roleName": "Individual",
  537. "loginUser": self.config.account.username,
  538. "payCode": ""
  539. }
  540. headers = self._get_common_headers(with_auth=True)
  541. resp = self._perform_request("POST", url, headers=headers, json_data=data, retry_count=2)
  542. if "WaitList" in resp.text:
  543. return "WaitList"
  544. j = resp.json()
  545. if j.get("earliestSlotLists"):
  546. raw_date = j["earliestSlotLists"][0]["date"]
  547. return to_yyyymmdd(raw_date, "%m/%d/%Y %H:%M:%S")
  548. return ""
  549. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  550. if not self.center_conf:
  551. self.center_conf = self._query_center()
  552. vac_code = apt_config.get("vac_code")
  553. category_code = apt_config.get("category_code")
  554. if category_code not in self.category_conf:
  555. visa_categories = self._query_visa_category(vac_code)
  556. found = False
  557. for vc in visa_categories:
  558. if vc.get("code") == category_code:
  559. self.category_conf[category_code] = vc
  560. found = True
  561. break
  562. if not found:
  563. self._log(f"WARN: Category {category_code} not found")
  564. sub_category_code = apt_config.get("subcategory_code")
  565. if sub_category_code not in self.subcategory_conf:
  566. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  567. found = False
  568. for svc in visa_subcategories:
  569. if svc.get("code") == sub_category_code:
  570. self.subcategory_conf[sub_category_code] = svc
  571. found = True
  572. break
  573. if not found:
  574. self._log(f"WARN: SubCategory {sub_category_code} not found")
  575. def _query_center(self) -> List:
  576. mission = self.free_config.get("mission_code")
  577. country = self.free_config.get("country_code")
  578. url = f"https://lift-api.vfsglobal.com/master/center/{mission}/{country}/en-US"
  579. headers = self._get_common_headers(with_auth=False)
  580. resp = self._perform_request("GET", url, headers=headers)
  581. return resp.json()
  582. def _query_visa_category(self, center_code: str) -> List:
  583. mission = self.free_config.get("mission_code")
  584. country = self.free_config.get("country_code")
  585. enc_center = urllib.parse.quote(center_code)
  586. url = f"https://lift-api.vfsglobal.com/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  587. headers = self._get_common_headers(with_auth=False)
  588. resp = self._perform_request("GET", url, headers=headers)
  589. return resp.json()
  590. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  591. mission = self.free_config.get("mission_code")
  592. country = self.free_config.get("country_code")
  593. enc_center = urllib.parse.quote(center_code)
  594. enc_cat = urllib.parse.quote(category_code)
  595. url = f"https://lift-api.vfsglobal.com/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  596. headers = self._get_common_headers(with_auth=False)
  597. resp = self._perform_request("GET", url, headers=headers)
  598. return resp.json()
  599. def _read_otp_email(self, sent_at='', sender='VFS Global') -> str:
  600. # 保持原样,这部分使用云API读取邮件,不依赖本地网络库
  601. master_email = "visafly666@gmail.com"
  602. recipient = self.config.account.username
  603. subject_keywords = "One Time Password"
  604. body_keywords = "OTP"
  605. if not sent_at:
  606. now_utc = datetime.utcnow()
  607. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  608. self._log(f"Waiting for OTP email...")
  609. content_out = VSCloudApi.Instance().fetch_mail_content(
  610. master_email, sender, recipient, subject_keywords, body_keywords, sent_at, 300
  611. )
  612. if content_out:
  613. match = re.search(r'\b\d{6}\b', content_out)
  614. if match:
  615. return match.group(0)
  616. raise BizLogicError(message="OTP code not found")
  617. def _submit_login_otp(self, old_cf_token: str, otp: str):
  618. self._log("Submitting Login OTP...")
  619. new_cf_token = self._refresh_turnstile_token()
  620. # ---------------------------
  621. email = self.config.account.username
  622. password = self.config.account.password
  623. enc_password = self._encrypt_password(password)
  624. mission = self.free_config.get("mission_code", "")
  625. country = self.free_config.get("country_code", "")
  626. client_src = self._get_client_source()
  627. orange_src = self._get_orange_source(email)
  628. url = "https://lift-api.vfsglobal.com/user/login"
  629. headers = self._get_common_headers(with_auth=False)
  630. headers.update({
  631. "clientsource": client_src,
  632. "orangex": orange_src
  633. })
  634. data = {
  635. "username": email,
  636. "password": enc_password,
  637. "missioncode": mission,
  638. "countrycode": country,
  639. "languageCode": "en-US",
  640. "captcha_version": "cloudflare-v1",
  641. "captcha_api_key": new_cf_token,
  642. "otp": otp
  643. }
  644. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  645. resp_json = resp.json()
  646. if resp_json.get("accessToken"):
  647. self.jwt_token = resp_json["accessToken"]
  648. self._log("OTP Login successful.")
  649. return
  650. error_desc = resp_json.get("description", resp.text)
  651. raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
  652. def _refresh_turnstile_token(self) -> str:
  653. """
  654. 强制刷新 Cloudflare Turnstile 并获取新 Token (集成 CloudflareBypasser 版)
  655. """
  656. self._log("Refreshing Cloudflare Turnstile token...")
  657. js_reset = """
  658. try {
  659. var input = document.querySelector('input[name="cf-turnstile-response"]');
  660. if (input) input.value = "";
  661. window.turnstile.reset();
  662. } catch(e) {
  663. console.log("Turnstile reset error:", e);
  664. }
  665. """
  666. self.page.run_js(js_reset)
  667. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  668. for i in range(60):
  669. time.sleep(0.5)
  670. try:
  671. ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
  672. if ele and ele.value:
  673. self._log("Turnstile token refreshed successfully.")
  674. return ele.value
  675. except:
  676. pass
  677. if i > 4:
  678. self._handle_cookie_banner()
  679. try:
  680. use_dfs = False
  681. cf_bypasser.click_verification_button(use_dfs)
  682. except Exception as e:
  683. # 点击过程报错不要中断主循环
  684. pass
  685. raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
  686. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  687. """
  688. 执行完整的预约流程
  689. """
  690. self._log("Starting booking process...")
  691. user_email = user_inputs.get('email')
  692. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="gmail-app.com")
  693. res = VSBookResult()
  694. app_type = slot_info.apt_type
  695. from_date = slot_info.earliest_date.strftime("%Y-%m-%d") if slot_info.earliest_date else datetime.now().strftime("%Y-%m-%d")
  696. apt_config = self.free_config.get("apt_configs", {}).get(app_type.routing_key)
  697. if not apt_config:
  698. raise NotFoundError(message="Book: Config missing for this routing key.")
  699. self._fetch_configurations(apt_config)
  700. sub_cc = apt_config.get("subcategory_code")
  701. sub_conf = self.subcategory_conf.get(sub_cc, {})
  702. ocr_enabled = sub_conf.get("isOCREnable", False)
  703. if ocr_enabled:
  704. self._log("OCR Enabled, uploading documents...")
  705. upload_res = self._upload_applicant_documents(apt_config, user_inputs)
  706. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  707. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes")
  708. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  709. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  710. final_urn = None
  711. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  712. if not self.booking_wait_applied:
  713. self._log("pre-booking wait: sleeping 20s before booking to avoid risk control")
  714. time.sleep(20)
  715. self.booking_wait_applied = True
  716. MAX_RETRY = 2
  717. for i in range(MAX_RETRY):
  718. try:
  719. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  720. break
  721. except BizLogicError as e:
  722. err_msg = str(e)
  723. self._log(f"Add Applicant retry {i+1}/{MAX_RETRY}: {err_msg}")
  724. if 'Capping has exceeded' in err_msg:
  725. raise e
  726. time.sleep(10.0)
  727. if not final_urn:
  728. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken or API error)")
  729. self._log(f"Applicant Added. URN: {final_urn}")
  730. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  731. if otp_enabled:
  732. self._log("Applicant OTP Required.")
  733. now_utc = datetime.utcnow()
  734. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  735. if not self._applicant_otp_send(apt_config, final_urn):
  736. raise BizLogicError(message='Applicant OTP send failed')
  737. otp_code = self._read_otp_email(sent_at=sent_at)
  738. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  739. raise BizLogicError(message='Applicant OTP verify failed')
  740. if is_waitlist:
  741. if self._confirm_waitlist(apt_config, final_urn):
  742. res.success = True
  743. res.urn = final_urn
  744. res.account = self.config.account.username
  745. self._log("Waitlist confirmed.")
  746. return res
  747. raise BizLogicError(message='Confirm waitlist failed')
  748. expected_start = user_inputs.get("expected_start_date", "")
  749. expected_end = user_inputs.get("expected_end_date", "")
  750. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  751. self._log(f"Scanning months: {months} (Start looking from: {from_date})")
  752. selected_slot_id = ""
  753. selected_slot_date = ""
  754. selected_slot_time_range = ""
  755. all_ads = set()
  756. forbidden_dates = set()
  757. found_slot = False
  758. for m_str in months:
  759. self._log(f"Checking calendar for {m_str}...")
  760. ads = self._query_slot_calendar(apt_config, final_urn, m_str)
  761. new_ads = [d for d in ads if d not in all_ads]
  762. all_ads.update(new_ads)
  763. for _ in range(3):
  764. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  765. sel_dates = self._filter_dates(avail_candidates, expected_start, expected_end)
  766. if not sel_dates:
  767. break
  768. tmp_date = sel_dates[0]
  769. forbidden_dates.add(tmp_date)
  770. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  771. self._log(f"Audit failed for {tmp_date}, skipping...")
  772. time.sleep(1)
  773. continue
  774. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  775. if not ats:
  776. self._log(f"No timeslots for {tmp_date}")
  777. continue
  778. sel_tm = random.choice(ats)
  779. selected_slot_id = sel_tm.get("allocationId")
  780. selected_slot_date = tmp_date
  781. selected_slot_time_range = sel_tm.get("slot")
  782. found_slot = True
  783. break
  784. if found_slot:
  785. break
  786. if not found_slot:
  787. self._log("No valid slots found after scanning.")
  788. res.success = False
  789. return res
  790. self._log(f"Slot Selected: {selected_slot_date} {selected_slot_time_range} (ID: {selected_slot_id})")
  791. self._submit_no_addition_service(final_urn)
  792. amount, currency = self._query_fee(apt_config, final_urn)
  793. self._log("Submitting schedule...")
  794. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  795. if not schedule_res.get("IsAppointmentBooked"):
  796. self._log(f"Booking failed: {schedule_res}")
  797. res.success = False
  798. return res
  799. res.success = True
  800. res.account = self.config.account.username
  801. res.book_date = selected_slot_date
  802. res.book_time = selected_slot_time_range
  803. res.urn = final_urn
  804. res.fee_amount = int(amount * 100)
  805. res.fee_currency = currency
  806. if schedule_res.get("IsPaymentRequired", False):
  807. payload = schedule_res.get("payLoad", "")
  808. if payload:
  809. self._log("Processing payment link...")
  810. payment_url = self._pay_request(payload)
  811. if payment_url:
  812. res.payment_link = payment_url
  813. return res
  814. def _get_application(self):
  815. url = 'https://lift-api.vfsglobal.com/appointment/application'
  816. headers = self._get_common_headers(with_auth=True)
  817. data = {
  818. 'countryCode': self.free_config.get("country_code"),
  819. 'missionCode': self.free_config.get("mission_code"),
  820. 'loginUser': self.config.account.username,
  821. 'languageCode': 'en-US',
  822. }
  823. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  824. return resp.json()
  825. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  826. """上传图片:先下载外部图片,再通过浏览器上传到 VFS"""
  827. import requests as standard_requests # 使用标准库下载外部资源
  828. url = "https://lift-api.vfsglobal.com/appointment/UploadApplicantDocument"
  829. passport_url = user_inputs.get("passport_image_url")
  830. if not passport_url:
  831. raise NotFoundError(message="Missing passport_image_url")
  832. try:
  833. img_resp = standard_requests.get(passport_url, timeout=30)
  834. if img_resp.status_code != 200:
  835. raise BizLogicError(message=f"Failed to download passport image: {img_resp.status_code}")
  836. b64_str = base64.b64encode(img_resp.content).decode('utf-8')
  837. except Exception as e:
  838. raise BizLogicError(message=f"Image download error: {e}")
  839. headers = self._get_common_headers(with_auth=True)
  840. data = {
  841. "missioncode": self.free_config.get("mission_code"),
  842. "countryCode": self.free_config.get("country_code"),
  843. "centerCode": apt_config.get("vac_code"),
  844. "loginUser": self.config.account.username,
  845. "languageCode": "en-US",
  846. "visaCategoryCode": apt_config.get("subcategory_code"),
  847. "fileBytes": b64_str,
  848. "selfiImageFileBytes": ""
  849. }
  850. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  851. result = resp.json()
  852. result["passportImageFilename"] = "passport_img.jpg"
  853. result["passportImageFileBytes"] = b64_str
  854. return result
  855. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  856. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  857. """构造申请人 payload 并提交"""
  858. url = "https://lift-api.vfsglobal.com/appointment/applicants"
  859. headers = self._get_common_headers(with_auth=True)
  860. gender_str = str(user_inputs.get("gender", "")).lower()
  861. gender_code = 1 if gender_str == "male" else 2
  862. raw_dial = user_inputs.get("phone_country_code", "86")
  863. dial_code = str(raw_dial)
  864. # 日期格式转换 YYYY-MM-DD -> DD/MM/YYYY
  865. def _to_ddmmyyyy(d_str):
  866. try:
  867. return datetime.strptime(str(d_str), "%Y-%m-%d").strftime("%d/%m/%Y")
  868. except:
  869. return str(d_str)
  870. dob = _to_ddmmyyyy(user_inputs.get("birthday", ""))
  871. ppt_exp = _to_ddmmyyyy(user_inputs.get("passport_expiry_date", ""))
  872. applicant = {
  873. "urn": "",
  874. "arn": "",
  875. "loginUser": self.config.account.username,
  876. "firstName": str(user_inputs.get("first_name", "")).strip().upper(),
  877. "middleName": "",
  878. "lastName": str(user_inputs.get("last_name", "")).strip().upper(),
  879. "employerFirstName": "",
  880. "employerLastName": "",
  881. "salutation": "",
  882. "Subclasscode": None,
  883. "VisaToken": None,
  884. "centerClassCode": None,
  885. "dateOfApplication": None,
  886. "selectedSubvisaCategory": None,
  887. "gender": gender_code,
  888. "contactNumber": str(user_inputs.get("phone", "")).strip().lstrip("0"),
  889. "dialCode": dial_code,
  890. "employerContactNumber": "",
  891. "employerDialCode": "",
  892. "emailId": str(user_inputs.get("alias_email", "")).strip().upper(),
  893. "employerEmailId": "",
  894. "passportNumber": str(user_inputs.get("passport_no", "")).strip().upper(),
  895. "confirmPassportNumber": "",
  896. "passportExpirtyDate": ppt_exp,
  897. "dateOfBirth": dob,
  898. "nationalId": None,
  899. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  900. "state": user_inputs.get("state"),
  901. "city": user_inputs.get("city"),
  902. "addressline1": user_inputs.get("addressline1"),
  903. "addressline2": user_inputs.get("addressline2"),
  904. "pincode": None,
  905. "isEndorsedChild": False,
  906. "applicantType": 0,
  907. "vlnNumber": None,
  908. "applicantGroupId": 0,
  909. "parentPassportNumber": "",
  910. "parentPassportExpiry": "",
  911. "dateOfDeparture": None,
  912. "entryType": "",
  913. "eoiVisaType": "",
  914. "passportType": "",
  915. "vfsReferenceNumber": "",
  916. "familyReunificationCerificateNumber": "",
  917. "PVRequestRefNumber": "",
  918. "PVStatus": "",
  919. "PVStatusDescription": "",
  920. "PVCanAllowRetry": True,
  921. "PVisVerified": False,
  922. "eefRegistrationNumber": "",
  923. "isAutoRefresh": True,
  924. "helloVerifyNumber": "",
  925. "OfflineCClink": "",
  926. "idenfystatuscheck": False,
  927. "vafStatus": None,
  928. "SpecialAssistance": "",
  929. "AdditionalRefNo": None,
  930. "juridictionCode": "",
  931. "canInitiateVAF": False,
  932. "canEditVAF": False,
  933. "canDeleteVAF": False,
  934. "canDownloadVAF": False,
  935. "Retryleft": "",
  936. # 这里的 IP 应该已经在 create_session 时获取到了
  937. "ipAddress": self.real_ip
  938. }
  939. if enable_ref:
  940. applicant["referenceNumber"] = str(user_inputs.get("cover_letter_id", "")).strip()
  941. else:
  942. applicant["referenceNumber"] = None
  943. if ocr_enabled:
  944. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  945. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  946. applicant["GUID"] = str(user_inputs.get("guid", ""))
  947. payload = {
  948. "countryCode": self.free_config.get("country_code"),
  949. "missionCode": self.free_config.get("mission_code"),
  950. "centerCode": apt_config.get("vac_code"),
  951. "loginUser": self.config.account.username,
  952. "visaCategoryCode": apt_config.get("subcategory_code"),
  953. "applicantList": [applicant],
  954. "languageCode": "en-US",
  955. "isWaitlist": is_waitlist,
  956. "isEdit": False,
  957. "feeEntryTypeCode": None, "feeExemptionTypeCode": None,
  958. "feeExemptionDetailsCode": None, "juridictionCode": None, "regionCode": None
  959. }
  960. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  961. urn = resp.json().get("urn")
  962. if not urn:
  963. err_msg = resp.json().get('error')
  964. raise BizLogicError(message=str(err_msg))
  965. return urn
  966. def _applicant_otp_send(self, apt_config, urn) -> bool:
  967. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  968. headers = self._get_common_headers(with_auth=True)
  969. data = {
  970. "urn": urn,
  971. "loginUser": self.config.account.username,
  972. "missionCode": self.free_config.get("mission_code"),
  973. "countryCode": self.free_config.get("country_code"),
  974. "centerCode": apt_config.get("vac_code"),
  975. "OTP": "",
  976. "otpAction": "GENERATE",
  977. "languageCode": "en-US"
  978. }
  979. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  980. return resp.json().get("isOTPGenerated", False)
  981. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  982. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  983. headers = self._get_common_headers(with_auth=True)
  984. # VFS 这里的 header 有时需要 datacenter,原代码有就加上
  985. headers["datacenter"] = "GERMANY"
  986. data = {
  987. "urn": urn,
  988. "loginUser": self.config.account.username,
  989. "missionCode": self.free_config.get("mission_code"),
  990. "countryCode": self.free_config.get("country_code"),
  991. "centerCode": apt_config.get("vac_code"),
  992. "OTP": otp,
  993. "otpAction": "VALIDATE",
  994. "languageCode": "en-US"
  995. }
  996. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  997. return resp.json().get("isOTPValidated", False)
  998. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  999. url = "https://lift-api.vfsglobal.com/appointment/calendar"
  1000. headers = self._get_common_headers(with_auth=True)
  1001. # 将 YYYY-MM-DD 转为 DD/MM/YYYY 用于 API
  1002. dt_m = datetime.strptime(from_date, "%Y-%m-%d")
  1003. converted_date = dt_m.strftime("%d/%m/%Y")
  1004. data = {
  1005. "missionCode": self.free_config.get("mission_code"),
  1006. "countryCode": self.free_config.get("country_code"),
  1007. "centerCode": apt_config.get("vac_code"),
  1008. "loginUser": self.config.account.username,
  1009. "visaCategoryCode": apt_config.get("subcategory_code"),
  1010. "fromDate": converted_date,
  1011. "urn": urn,
  1012. "payCode": ""
  1013. }
  1014. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1015. calendars = resp.json().get("calendars")
  1016. ads_out = []
  1017. if calendars:
  1018. for item in calendars:
  1019. # API 返回可能是 MM/DD/YYYY 或 DD/MM/YYYY,VFS 比较乱
  1020. # 通常是 MM/DD/YYYY
  1021. raw = item.get("date")
  1022. ads_out.append(to_yyyymmdd(raw, "%m/%d/%Y"))
  1023. return ads_out
  1024. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  1025. url = "https://lift-api.vfsglobal.com/appointment/timeslot"
  1026. headers = self._get_common_headers(with_auth=True)
  1027. dt_m = datetime.strptime(slot_date, "%Y-%m-%d")
  1028. converted_date = dt_m.strftime("%d/%m/%Y")
  1029. data = {
  1030. "missionCode": self.free_config.get("mission_code"),
  1031. "countryCode": self.free_config.get("country_code"),
  1032. "centerCode": apt_config.get("vac_code"),
  1033. "loginUser": self.config.account.username,
  1034. "visaCategoryCode": apt_config.get("subcategory_code"),
  1035. "slotDate": converted_date,
  1036. "urn": urn
  1037. }
  1038. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1039. return resp.json().get("slots", [])
  1040. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  1041. url = "https://lift-api.vfsglobal.com/appointment/saveuseractionaudit"
  1042. headers = self._get_common_headers(with_auth=True)
  1043. dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  1044. data = {
  1045. "missionCode": self.free_config.get("mission_code"),
  1046. "countryCode": self.free_config.get("country_code"),
  1047. "centerCode": apt_config.get("vac_code"),
  1048. "loginUser": self.config.account.username,
  1049. "urn": urn,
  1050. "firstEarliestSlotDate": dt.strftime("%d/%m/%Y"),
  1051. "action": "schedule",
  1052. "ipAddress": self.real_ip,
  1053. "eadAppointmentDetail": dt.strftime("%Y-%m-%dT%H:%M:%S")
  1054. }
  1055. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1056. return resp.json().get("isSavedSuccess", False)
  1057. def _submit_no_addition_service(self, urn):
  1058. url = "https://lift-api.vfsglobal.com/vas/mapvas"
  1059. headers = self._get_common_headers(with_auth=True)
  1060. data = {
  1061. "loginUser": self.config.account.username,
  1062. "missionCode": self.free_config.get("mission_code"),
  1063. "countryCode": self.free_config.get("country_code"),
  1064. "urn": urn,
  1065. "applicants": []
  1066. }
  1067. self._perform_request("POST", url, headers=headers, json_data=data)
  1068. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  1069. url = "https://lift-api.vfsglobal.com/appointment/fees"
  1070. headers = self._get_common_headers(with_auth=True)
  1071. data = {
  1072. "missionCode": self.free_config.get("mission_code"),
  1073. "countryCode": self.free_config.get("country_code"),
  1074. "centerCode": apt_config.get("vac_code"),
  1075. "loginUser": self.config.account.username,
  1076. "urn": urn,
  1077. "languageCode": "en-US"
  1078. }
  1079. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1080. j = resp.json()
  1081. total = j.get("totalamount", 0.0)
  1082. currency = "EUR"
  1083. if j.get("feeDetails"):
  1084. currency = j["feeDetails"][0].get("currency", "EUR")
  1085. return total, currency
  1086. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  1087. url = "https://lift-api.vfsglobal.com/appointment/schedule"
  1088. headers = self._get_common_headers(with_auth=True)
  1089. data = {
  1090. "missionCode": self.free_config.get("mission_code"),
  1091. "countryCode": self.free_config.get("country_code"),
  1092. "centerCode": apt_config.get("vac_code"),
  1093. "loginUser": self.config.account.username,
  1094. "urn": urn,
  1095. "notificationType": "none",
  1096. "paymentdetails": {
  1097. "paymentmode": "Online",
  1098. "RequestRefNo": "",
  1099. "clientId": "",
  1100. "merchantId": "",
  1101. "amount": amount,
  1102. "currency": currency
  1103. },
  1104. "allocationId": str(slot_id),
  1105. "CanVFSReachoutToApplicant": True
  1106. }
  1107. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1108. return resp.json()
  1109. def _pay_request(self, payload) -> str:
  1110. """
  1111. 解析支付重定向 URL (DrissionPage 新标签页版)
  1112. """
  1113. start_url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={payload}"
  1114. final_url = ""
  1115. try:
  1116. self._log("Resolving payment redirect...")
  1117. # 使用新标签页去跑,以免当前会话状态丢失
  1118. pay_tab = self.page.new_tab(start_url)
  1119. # 等待跳转完成 (通常会跳到 Stripe, WorldPay 或其他支付网关)
  1120. # 等待直到 URL 不再是 PayRequest
  1121. pay_tab.wait.url_change(start_url, timeout=15)
  1122. final_url = pay_tab.url
  1123. self._log(f"Payment URL resolved: {final_url}")
  1124. pay_tab.close()
  1125. except Exception as e:
  1126. self._log(f"[WARN] Failed to resolve payment URL: {e}")
  1127. try:
  1128. pay_tab.close()
  1129. except:
  1130. pass
  1131. return final_url
  1132. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  1133. url = "https://lift-api.vfsglobal.com/appointment/ConfirmWaitlist"
  1134. headers = self._get_common_headers(with_auth=True)
  1135. data = {
  1136. "missionCode": self.free_config.get("mission_code"),
  1137. "countryCode": self.free_config.get("country_code"),
  1138. "centerCode": apt_config.get("vac_code"),
  1139. "loginUser": self.config.account.username,
  1140. "urn": urn,
  1141. "notificationType": "none",
  1142. "CanVFSReachoutToApplicant": True
  1143. }
  1144. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1145. return resp.json().get("isConfirmed", False)
  1146. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  1147. if not start_str or not end_str:
  1148. return dates
  1149. valid_dates = []
  1150. try:
  1151. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  1152. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  1153. for date_str in dates:
  1154. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  1155. if s_date <= curr_date <= e_date:
  1156. valid_dates.append(date_str)
  1157. random.shuffle(valid_dates)
  1158. return valid_dates
  1159. except:
  1160. return dates
  1161. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  1162. fmt = "%Y-%m-%d"
  1163. try:
  1164. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  1165. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.now().replace(year=datetime.now().year + 1)
  1166. try:
  1167. dt_from = datetime.strptime(from_date, fmt)
  1168. except:
  1169. dt_from = datetime.now()
  1170. except:
  1171. return []
  1172. dt_start = dt_start.replace(day=1)
  1173. dt_end = dt_end.replace(day=1)
  1174. dt_from = dt_from.replace(day=1)
  1175. curr = max(dt_start, dt_from)
  1176. months = []
  1177. while curr <= dt_end:
  1178. months.append(curr.strftime(fmt))
  1179. if curr.month == 12:
  1180. curr = curr.replace(year=curr.year + 1, month=1)
  1181. else:
  1182. curr = curr.replace(month=curr.month + 1)
  1183. return months
  1184. # --- 资源清理核心方法 ---
  1185. def cleanup(self):
  1186. """
  1187. 销毁浏览器并彻底删除临时文件
  1188. """
  1189. # 1. 关闭浏览器
  1190. if self.page:
  1191. try:
  1192. self.page.quit() # 这会关闭 Chrome 进程
  1193. except Exception:
  1194. pass # 忽略已关闭的错误
  1195. self.page = None
  1196. # 2. 删除文件
  1197. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  1198. if os.path.exists(self.root_workspace):
  1199. for _ in range(3):
  1200. try:
  1201. time.sleep(0.2)
  1202. shutil.rmtree(self.root_workspace, ignore_errors=True)
  1203. break
  1204. except Exception as e:
  1205. # 如果删除失败(通常是Windows文件占用),重试
  1206. self._log(f"Cleanup retry: {e}")
  1207. time.sleep(0.5)
  1208. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  1209. if os.path.exists(self.root_workspace):
  1210. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  1211. # 3. [新增] 关闭代理隧道
  1212. if self.tunnel:
  1213. try: self.tunnel.stop()
  1214. except: pass
  1215. self.tunnel = None
  1216. def __del__(self):
  1217. """
  1218. 析构函数:当对象被垃圾回收时自动调用
  1219. """
  1220. self.cleanup()