vfs_plugin.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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 cryptography.hazmat.primitives import serialization, hashes
  16. from cryptography.hazmat.primitives.asymmetric import padding
  17. from cryptography.hazmat.backends import default_backend
  18. import configure
  19. from vs_plg import IVSPlg
  20. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str
  21. from toolkit.vs_cloud_api import VSCloudApi
  22. from toolkit.mihomo_tunnel import MihomoTunnel
  23. from toolkit.captcha_breaker import recognize_vfs_captcha_with_qwen
  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 = "text.skin") -> str:
  74. """
  75. 将邮箱域名替换为指定域名(默认 text.skin)
  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. name = "vfs_plugin"
  104. version = "1.0.0"
  105. description = "VFS Global全球多国签证预约插件 (支持多中心、多签证类型与CF破解)"
  106. def __init__(self, group_id: str):
  107. self.group_id = group_id
  108. self.config: Optional[VSPlgConfig] = None
  109. self.free_config: Dict[str, Any] = {}
  110. self.logger = None
  111. self.page: Optional[ChromiumPage] = None
  112. self.jwt_token: str = ""
  113. self.real_ip: str = ""
  114. self.is_healthy: bool = True
  115. self.center_conf = None
  116. self.category_conf: Dict = {}
  117. self.subcategory_conf: Dict = {}
  118. self.booking_wait_applied = False
  119. self.public_key = serialization.load_pem_public_key(
  120. VFS_PUBLIC_KEY_PEM.encode(),
  121. backend=default_backend()
  122. )
  123. self.instance_id = uuid.uuid4().hex[:8]
  124. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  125. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  126. self.vfs_api_domain = 'lift-api.vfsglobal.com'
  127. if not os.path.exists(self.root_workspace):
  128. os.makedirs(self.root_workspace)
  129. self.tunnel = None
  130. self.session_create_time: float = 0
  131. def set_config(self, config: VSPlgConfig):
  132. self.config = config
  133. self.free_config = config.free_config or {}
  134. if self.free_config.get('country_code') == 'chn':
  135. self.vfs_api_domain = 'lift-apicn.vfsglobal.com'
  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'[TlsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  141. else:
  142. print(f'[TlsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
  143. def keep_alive(self):
  144. try:
  145. keep_alive_funcs = [
  146. self._get_application,
  147. self._query_center,
  148. ]
  149. random.choice(keep_alive_funcs)()
  150. self._log(f'keep_alive request, status ok')
  151. except Exception as e:
  152. self.is_healthy = False
  153. self._log(f'keep_alive failed: {e}')
  154. def health_check(self) -> bool:
  155. if not self.is_healthy:
  156. return False
  157. if self.page is None:
  158. return False
  159. try:
  160. if not self.page.run_js("return 1;"):
  161. return False
  162. except:
  163. return False
  164. if self.config.session_max_life > 0:
  165. current_time = time.time()
  166. elapsed_time = current_time - self.session_create_time
  167. if elapsed_time > self.config.session_max_life:
  168. self._log(f"Session expired.")
  169. return False
  170. return True
  171. def create_session(self) -> None:
  172. """
  173. 使用 DrissionPage 创建会话:
  174. 1. 启动浏览器
  175. 2. 导航到登录页
  176. 3. 自动过盾并提取 Token (集成 CloudflareBypasser)
  177. 4. JS fetch 登录
  178. """
  179. self._log(f"Initializing Session (ID: {self.instance_id})...")
  180. co = ChromiumOptions()
  181. def get_free_port():
  182. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  183. s.bind(('', 0))
  184. return s.getsockname()[1]
  185. debug_port = get_free_port()
  186. self._log(f"Assigned Debug Port: {debug_port}")
  187. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  188. co.set_local_port(debug_port)
  189. co.set_user_data_path(self.user_data_path)
  190. chrome_path = configure.CHROME_PATH
  191. if not chrome_path:
  192. chrome_path = os.getenv("CHROME_BIN")
  193. if chrome_path and os.path.exists(chrome_path):
  194. co.set_paths(browser_path=chrome_path)
  195. if self.config.proxy and self.config.proxy.ip:
  196. p = self.config.proxy
  197. if p.username and p.password:
  198. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  199. exit_node = {
  200. "name": "ExitNode",
  201. "type": p.proto,
  202. "server": p.ip,
  203. "port": p.port,
  204. "username": p.username,
  205. "password": p.password
  206. }
  207. relay_node = None
  208. if configure.MIHOMO_RELAY_NODES:
  209. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  210. mihomo_path = configure.MIHOMO_BIN_PATH
  211. if not mihomo_path:
  212. mihomo_path = os.getenv("MIHOMO_BIN")
  213. if not mihomo_path:
  214. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  215. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  216. local_proxy = self.tunnel.start()
  217. self._log(f"Tunnel started at {local_proxy}")
  218. co.set_argument(f'--proxy-server={local_proxy}')
  219. else:
  220. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  221. co.set_argument(f'--proxy-server={proxy_str}')
  222. else:
  223. self._log("[WARN] No proxy configured!")
  224. co.headless(False)
  225. co.set_argument('--no-sandbox')
  226. co.set_argument('--disable-gpu')
  227. co.set_argument('--disable-dev-shm-usage')
  228. co.set_argument('--window-size=1920,1080')
  229. co.set_argument('--disable-blink-features=AutomationControlled')
  230. self.page = ChromiumPage(co)
  231. mission = self.free_config.get("mission_code", "")
  232. country = self.free_config.get("country_code", "")
  233. lang = self.free_config.get("language", "en")
  234. if not mission or not country:
  235. raise BizLogicError("Missing mission/country code config")
  236. login_page_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
  237. self._log(f"Navigating to {login_page_url}...")
  238. self.page.get(login_page_url)
  239. self._log("Handling Cloudflare challenge...")
  240. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  241. if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
  242. self._log(f'Block by cloudflare, try refresh...')
  243. self.page.refresh()
  244. self.page.wait.doc_loaded()
  245. time.sleep(random.uniform(3, 5))
  246. cf_bypasser.handle_waiting_room()
  247. cf_token = ""
  248. for i in range(40):
  249. time.sleep(1)
  250. self._handle_cookie_banner()
  251. try:
  252. ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
  253. if ele and ele.value:
  254. cf_token = ele.value
  255. self._log("Cloudflare Turnstile token extracted.")
  256. break
  257. except:
  258. pass
  259. if i > 2:
  260. try:
  261. use_dfs = False
  262. cf_bypasser.click_verification_button(use_dfs)
  263. except Exception as e:
  264. pass
  265. if self.page.ele('tag:form', timeout=0.5) or self.page.ele('#mat-input-0', timeout=0.5):
  266. self._log("Login form detected.")
  267. if i > 5 and not cf_token:
  268. self._log("Form visible but token not found yet...")
  269. if not cf_token:
  270. try:
  271. cf_token = self.page.ele('@name=cf-turnstile-response').value
  272. except:
  273. pass
  274. if not cf_token:
  275. self._log("[WARN] Could not extract Turnstile token.")
  276. raise BizLogicError(f"Could not extract Turnstile token.")
  277. email = self.config.account.username
  278. password = self.config.account.password
  279. enc_password = self._encrypt_password(password)
  280. client_src = self._get_client_source()
  281. orange_src = self._get_orange_source(email)
  282. url = f"https://{self.vfs_api_domain}/user/login"
  283. headers = self._get_common_headers(with_auth=False)
  284. headers.update({
  285. "clientsource": client_src,
  286. "orangex": orange_src
  287. })
  288. data = {
  289. "username": email,
  290. "password": enc_password,
  291. "missioncode": mission,
  292. "countrycode": country,
  293. "languageCode": "en-US",
  294. "captcha_version": "cloudflare-v1",
  295. "captcha_api_key": cf_token
  296. }
  297. now_utc = datetime.utcnow()
  298. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  299. self._log("Sending Login Request via Browser Fetch...")
  300. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  301. resp_json = resp.json()
  302. if resp_json.get('accessToken'):
  303. self.jwt_token = resp_json["accessToken"]
  304. self._log("Login successful, JWT obtained.")
  305. elif resp_json.get("enableOTPAuthentication"):
  306. self._log("Login requires OTP.")
  307. otp = self._read_otp_email(sent_at=sent_at)
  308. self._submit_login_otp(cf_token, otp)
  309. else:
  310. raise BizLogicError(f"Login failed: {resp.text[:200]}")
  311. self.session_create_time = time.time()
  312. try:
  313. self.real_ip = self._get_realnetwork_ip()
  314. except:
  315. self.real_ip = self.config.proxy.ip
  316. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  317. """查询可预约 Slot"""
  318. result = VSQueryResult()
  319. apt_config = self.free_config.get("apt_configs", {}).get(apt_type.routing_key)
  320. self._fetch_configurations(apt_config)
  321. query_result = self._query_earliest_slot(apt_config)
  322. result.success = False
  323. result.availability_status = AvailabilityStatus.NoneAvailable
  324. if query_result:
  325. result.success = True
  326. if "WaitList" in query_result:
  327. result.availability_status = AvailabilityStatus.Waitlist
  328. else:
  329. earliest_dt = datetime.strptime(query_result, "%Y-%m-%d")
  330. result.availability_status = AvailabilityStatus.Available
  331. result.earliest_date = earliest_dt
  332. result.availability = [DateAvailability(date=earliest_dt, times=[])]
  333. self._log(f"Slot Found! -> {query_result}")
  334. else:
  335. self._log("No slots available.")
  336. return result
  337. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  338. """
  339. 核心方法:在 DrissionPage 浏览器上下文中注入 JS 执行 fetch
  340. 并记录详细的 Traffic 日志用于分析
  341. """
  342. if not self.page:
  343. raise BizLogicError("Browser session not initialized")
  344. req_url = url
  345. if params:
  346. sep = '&' if '?' in req_url else '?'
  347. req_url += sep + urllib.parse.urlencode(params)
  348. final_headers = headers or {}
  349. fetch_options = {
  350. "method": method.upper(),
  351. "headers": final_headers,
  352. "credentials": "include" # 关键:带上浏览器 Cookie
  353. }
  354. log_body = "None"
  355. if json_data:
  356. json_str = json.dumps(json_data)
  357. fetch_options['body'] = json_str
  358. fetch_options['headers']['Content-Type'] = 'application/json'
  359. log_body = json_str
  360. elif data:
  361. if isinstance(data, dict):
  362. encoded_data = urllib.parse.urlencode(data)
  363. fetch_options['body'] = encoded_data
  364. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  365. log_body = encoded_data
  366. else:
  367. fetch_options['body'] = data
  368. log_body = str(data)
  369. self._log(f"┌── [TRAFFIC REQUEST] {method} {req_url}")
  370. self._log(f"├── Headers: {json.dumps(final_headers)}")
  371. self._log(f"└── Body: {log_body}")
  372. js_script = f"""
  373. const url = "{req_url}";
  374. const options = {json.dumps(fetch_options)};
  375. const startTime = Date.now();
  376. return fetch(url, options)
  377. .then(async response => {{
  378. const text = await response.text();
  379. const headers = {{}};
  380. response.headers.forEach((value, key) => headers[key] = value);
  381. const endTime = Date.now();
  382. return {{
  383. status: response.status,
  384. body: text,
  385. headers: headers,
  386. url: response.url,
  387. duration: endTime - startTime
  388. }};
  389. }})
  390. .catch(error => {{
  391. return {{
  392. status: 0,
  393. body: error.toString(),
  394. headers: {{}},
  395. url: url,
  396. duration: Date.now() - startTime
  397. }};
  398. }});
  399. """
  400. try:
  401. res_dict = self.page.run_js(js_script, timeout=60)
  402. except Exception as e:
  403. self._log(f"[TRAFFIC ERROR] JS Execution failed: {e}")
  404. raise BizLogicError(f"Browser JS Execution Error: {e}")
  405. resp = BrowserResponse(res_dict)
  406. duration = res_dict.get('duration', 0)
  407. resp_preview = resp.text[:1000] + "..." if len(resp.text) > 1000 else resp.text
  408. self._log(f"┌── [TRAFFIC RESPONSE] Status: {resp.status_code} | Time: {duration}ms")
  409. self._log(f"└── Body: {resp_preview}")
  410. if resp.status_code == 200:
  411. return resp
  412. elif resp.status_code == 401:
  413. self.is_healthy = False
  414. raise SessionExpiredOrInvalidError(f"401 Unauthorized: {resp.text[:100]}")
  415. elif resp.status_code == 403:
  416. if "Just a moment" in resp.text or "cloudflare" in resp.text.lower():
  417. self._log(f"[TRAFFIC] HTTP 403 (Cloudflare) detected. Re-verifying (Try {retry_count+1}/3)...")
  418. if retry_count < 3:
  419. new_token = self._refresh_turnstile_token()
  420. if new_token:
  421. self._log("[TRAFFIC] In-page verification success. Retrying...")
  422. if json_data and "captcha_api_key" in json_data:
  423. json_data["captcha_api_key"] = new_token
  424. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  425. raise PermissionDeniedError(f"HTTP 403 Forbidden: {resp.text[:100]}")
  426. elif resp.status_code == 429:
  427. self.is_healthy = False
  428. raise RateLimiteddError(f"429 Rate Limit: {resp.text[:100]}")
  429. elif resp.status_code == 0:
  430. raise BizLogicError(f"Network Error (Fetch Failed): {resp.text}")
  431. else:
  432. if url.endswith("/login") and resp.status_code == 400:
  433. return resp
  434. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  435. def _handle_cookie_banner(self):
  436. """
  437. 处理 OneTrust Cookie 遮挡
  438. 策略:尝试点击“接受所有”,如果点不到就直接移除 DOM
  439. """
  440. try:
  441. js = """
  442. try {
  443. var acceptBtn = document.getElementById('onetrust-accept-btn-handler');
  444. if (acceptBtn) {
  445. acceptBtn.click();
  446. return true;
  447. }
  448. var banner = document.getElementById('onetrust-banner-sdk');
  449. if (banner) {
  450. banner.style.display = 'none';
  451. banner.remove();
  452. return true;
  453. }
  454. } catch(e) {}
  455. return false;
  456. """
  457. self.page.run_js(js)
  458. except:
  459. pass
  460. def _get_realnetwork_ip(self):
  461. """
  462. 通过新建标签页获取 IP
  463. 解决 CORS 403 问题:新标签页请求属于 Top-Level Navigation,
  464. 不带 Origin: visa.vfsglobal.com,也不带 credentials,符合 ipify 规则。
  465. """
  466. try:
  467. tab = self.page.new_tab("https://api.ipify.org/?format=json")
  468. if tab.ele('tag:pre'):
  469. json_text = tab.ele('tag:pre').text
  470. else:
  471. json_text = tab.ele('tag:body').text
  472. ip = json.loads(json_text)['ip']
  473. tab.close()
  474. self._log(f"Real Network IP: {ip}")
  475. return ip
  476. except Exception as e:
  477. self._log(f"[WARN] Failed to check IP via new tab: {e}")
  478. try:
  479. if self.page.tabs_count > 1:
  480. tab.close()
  481. except:
  482. pass
  483. return "0.0.0.0"
  484. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  485. # DrissionPage 浏览器会自动带上 Origin, Referer, User-Agent, Sec-CH-UA 等,这里只需要补充业务特定的 Headers
  486. mission = self.free_config.get("mission_code", "")
  487. country = self.free_config.get("country_code", "")
  488. lang = self.free_config.get("language", "en")
  489. route = f"{country}/{lang}/{mission}"
  490. h = {
  491. "accept": "application/json, text/plain, */*",
  492. "route": route
  493. }
  494. h["clientsource"] = self._get_client_source()
  495. if with_auth and self.jwt_token:
  496. h["authorize"] = self.jwt_token
  497. return h
  498. def _encrypt_password(self, password: str) -> str:
  499. ciphertext = self.public_key.encrypt(
  500. password.encode(),
  501. padding.OAEP(
  502. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  503. algorithm=hashes.SHA256(),
  504. label=None
  505. )
  506. )
  507. return base64.b64encode(ciphertext).decode()
  508. def _get_orange_source(self, email: str) -> str:
  509. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  510. payload = f"{email};{timestamp}"
  511. return self._encrypt_password(payload)
  512. def _get_client_source(self) -> str:
  513. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  514. payload = f"GA;{timestamp}Z"
  515. return self._encrypt_password(payload)
  516. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  517. url = f"https://{self.vfs_api_domain}/appointment/CheckIsSlotAvailable"
  518. data = {
  519. "missioncode": self.free_config.get("mission_code"),
  520. "countrycode": self.free_config.get("country_code"),
  521. "vacCode": apt_config.get("vac_code"),
  522. "visaCategoryCode": apt_config.get("subcategory_code"),
  523. "roleName": "Individual",
  524. "loginUser": self.config.account.username,
  525. "payCode": ""
  526. }
  527. headers = self._get_common_headers(with_auth=True)
  528. resp = self._perform_request("POST", url, headers=headers, json_data=data, retry_count=2)
  529. if "WaitList" in resp.text:
  530. return "WaitList"
  531. j = resp.json()
  532. if j.get("earliestSlotLists"):
  533. raw_date = j["earliestSlotLists"][0]["date"]
  534. return to_yyyymmdd(raw_date, "%m/%d/%Y %H:%M:%S")
  535. return ""
  536. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  537. if not self.center_conf:
  538. self.center_conf = self._query_center()
  539. vac_code = apt_config.get("vac_code")
  540. category_code = apt_config.get("category_code")
  541. if category_code not in self.category_conf:
  542. visa_categories = self._query_visa_category(vac_code)
  543. found = False
  544. for vc in visa_categories:
  545. if vc.get("code") == category_code:
  546. self.category_conf[category_code] = vc
  547. found = True
  548. break
  549. if not found:
  550. self._log(f"WARN: Category {category_code} not found")
  551. sub_category_code = apt_config.get("subcategory_code")
  552. if sub_category_code not in self.subcategory_conf:
  553. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  554. found = False
  555. for svc in visa_subcategories:
  556. if svc.get("code") == sub_category_code:
  557. self.subcategory_conf[sub_category_code] = svc
  558. found = True
  559. break
  560. if not found:
  561. self._log(f"WARN: SubCategory {sub_category_code} not found")
  562. def _query_center(self) -> List:
  563. mission = self.free_config.get("mission_code")
  564. country = self.free_config.get("country_code")
  565. url = f"https://{self.vfs_api_domain}/master/center/{mission}/{country}/en-US"
  566. headers = self._get_common_headers(with_auth=False)
  567. resp = self._perform_request("GET", url, headers=headers)
  568. return resp.json()
  569. def _query_visa_category(self, center_code: str) -> List:
  570. mission = self.free_config.get("mission_code")
  571. country = self.free_config.get("country_code")
  572. enc_center = urllib.parse.quote(center_code)
  573. url = f"https://{self.vfs_api_domain}/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  574. headers = self._get_common_headers(with_auth=False)
  575. resp = self._perform_request("GET", url, headers=headers)
  576. return resp.json()
  577. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  578. mission = self.free_config.get("mission_code")
  579. country = self.free_config.get("country_code")
  580. enc_center = urllib.parse.quote(center_code)
  581. enc_cat = urllib.parse.quote(category_code)
  582. url = f"https://{self.vfs_api_domain}/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  583. headers = self._get_common_headers(with_auth=False)
  584. resp = self._perform_request("GET", url, headers=headers)
  585. return resp.json()
  586. def _read_otp_email(self, sent_at='', sender='VFS Global') -> str:
  587. # 保持原样,这部分使用云API读取邮件,不依赖本地网络库
  588. master_email = "hujiarui8@gmail.com"
  589. recipient = self.config.account.username
  590. subject_keywords = "One Time Password"
  591. body_keywords = "OTP"
  592. if not sent_at:
  593. now_utc = datetime.utcnow()
  594. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  595. self._log(f"Waiting for OTP email...")
  596. content_out = VSCloudApi.Instance().fetch_mail_content(
  597. master_email, sender, recipient, subject_keywords, body_keywords, sent_at, 300, only_text=False
  598. )
  599. if content_out:
  600. parts = content_out.split("\n")
  601. text_parts = [p for p in parts if not p.startswith("data:image")]
  602. email_text = " ".join(text_parts)
  603. image_urls = [p for p in parts if p.startswith("data:image")]
  604. match = re.search(r'\b\d{6}\b', email_text)
  605. if match:
  606. self._log("Found OTP from email text via Regex.")
  607. return match.group(0)
  608. if image_urls:
  609. self._log("OTP not found in text, trying LLM image recognition...")
  610. target_image_b64 = image_urls[0]
  611. otp_code = recognize_vfs_captcha_with_qwen(target_image_b64)
  612. if otp_code:
  613. self._log(f"Successfully extracted OTP from image: {otp_code}")
  614. return otp_code
  615. raise BizLogicError(message="OTP code not found")
  616. def _submit_login_otp(self, old_cf_token: str, otp: str):
  617. self._log("Submitting Login OTP...")
  618. new_cf_token = self._refresh_turnstile_token()
  619. email = self.config.account.username
  620. password = self.config.account.password
  621. enc_password = self._encrypt_password(password)
  622. mission = self.free_config.get("mission_code", "")
  623. country = self.free_config.get("country_code", "")
  624. client_src = self._get_client_source()
  625. orange_src = self._get_orange_source(email)
  626. url = f"https://{self.vfs_api_domain}/user/login"
  627. headers = self._get_common_headers(with_auth=False)
  628. headers.update({
  629. "clientsource": client_src,
  630. "orangex": orange_src
  631. })
  632. data = {
  633. "username": email,
  634. "password": enc_password,
  635. "missioncode": mission,
  636. "countrycode": country,
  637. "languageCode": "en-US",
  638. "captcha_version": "cloudflare-v1",
  639. "captcha_api_key": new_cf_token,
  640. "otp": otp
  641. }
  642. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  643. resp_json = resp.json()
  644. if resp_json.get("accessToken"):
  645. self.jwt_token = resp_json["accessToken"]
  646. self._log("OTP Login successful.")
  647. return
  648. error_desc = resp_json.get("description", resp.text)
  649. raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
  650. def _refresh_turnstile_token(self) -> str:
  651. """
  652. 强制刷新 Cloudflare Turnstile 并获取新 Token (集成 CloudflareBypasser 版)
  653. """
  654. self._log("Refreshing Cloudflare Turnstile token...")
  655. js_reset = """
  656. try {
  657. var input = document.querySelector('input[name="cf-turnstile-response"]');
  658. if (input) input.value = "";
  659. window.turnstile.reset();
  660. } catch(e) {
  661. console.log("Turnstile reset error:", e);
  662. }
  663. """
  664. self.page.run_js(js_reset)
  665. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  666. for i in range(60):
  667. time.sleep(0.5)
  668. try:
  669. ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
  670. if ele and ele.value:
  671. self._log("Turnstile token refreshed successfully.")
  672. return ele.value
  673. except:
  674. pass
  675. if i > 4:
  676. self._handle_cookie_banner()
  677. try:
  678. use_dfs = False
  679. cf_bypasser.click_verification_button(use_dfs)
  680. except Exception as e:
  681. pass
  682. raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
  683. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  684. """
  685. 执行完整的预约流程
  686. """
  687. self._log("Starting booking process...")
  688. user_email = user_inputs.get('email')
  689. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="text.skin")
  690. res = VSBookResult()
  691. app_type = slot_info.apt_type
  692. from_date = slot_info.earliest_date.strftime("%Y-%m-%d") if slot_info.earliest_date else datetime.now().strftime("%Y-%m-%d")
  693. expected_start = user_inputs.get("expected_start_date", "2000-01-01")
  694. expected_end = user_inputs.get("expected_end_date", "2100-01-01")
  695. if from_date >= expected_end:
  696. self._log("No valid slots in date preference.")
  697. res.success = False
  698. return res
  699. apt_config = self.free_config.get("apt_configs", {}).get(app_type.routing_key)
  700. if not apt_config:
  701. raise NotFoundError(message="Book: Config missing for this routing key.")
  702. self._fetch_configurations(apt_config)
  703. sub_cc = apt_config.get("subcategory_code")
  704. sub_conf = self.subcategory_conf.get(sub_cc, {})
  705. ocr_enabled = sub_conf.get("isOCREnable", False)
  706. if ocr_enabled:
  707. self._log("OCR Enabled, uploading documents...")
  708. upload_res = self._upload_applicant_documents(apt_config, user_inputs)
  709. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  710. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes")
  711. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  712. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  713. final_urn = None
  714. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  715. if not self.booking_wait_applied:
  716. self._log("pre-booking wait: sleeping 20s before booking to avoid risk control")
  717. time.sleep(20)
  718. self.booking_wait_applied = True
  719. MAX_RETRY = 2
  720. for i in range(MAX_RETRY):
  721. try:
  722. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  723. break
  724. except BizLogicError as e:
  725. err_msg = str(e)
  726. self._log(f"Add Applicant retry {i+1}/{MAX_RETRY}: {err_msg}")
  727. if 'Capping has exceeded' in err_msg:
  728. raise e
  729. time.sleep(10.0)
  730. if not final_urn:
  731. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken or API error)")
  732. self._log(f"Applicant Added. URN: {final_urn}")
  733. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  734. if otp_enabled:
  735. self._log("Applicant OTP Required.")
  736. now_utc = datetime.utcnow()
  737. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  738. if not self._applicant_otp_send(apt_config, final_urn):
  739. raise BizLogicError(message='Applicant OTP send failed')
  740. otp_code = self._read_otp_email(sent_at=sent_at)
  741. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  742. raise BizLogicError(message='Applicant OTP verify failed')
  743. if is_waitlist:
  744. if self._confirm_waitlist(apt_config, final_urn):
  745. res.success = True
  746. res.urn = final_urn
  747. res.account = self.config.account.username
  748. self._log("Waitlist confirmed.")
  749. return res
  750. raise BizLogicError(message='Confirm waitlist failed')
  751. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  752. self._log(f"Scanning months: {months} (Start looking from: {from_date})")
  753. selected_slot_id = ""
  754. selected_slot_date = ""
  755. selected_slot_time_range = ""
  756. all_ads = set()
  757. forbidden_dates = set()
  758. found_slot = False
  759. for m_str in months:
  760. self._log(f"Checking calendar for {m_str}...")
  761. ads = self._query_slot_calendar(apt_config, final_urn, m_str)
  762. new_ads = [d for d in ads if d not in all_ads]
  763. all_ads.update(new_ads)
  764. for _ in range(3):
  765. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  766. sel_dates = self._filter_dates(avail_candidates, expected_start, expected_end)
  767. if not sel_dates:
  768. break
  769. tmp_date = sel_dates[0]
  770. forbidden_dates.add(tmp_date)
  771. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  772. self._log(f"Audit failed for {tmp_date}, skipping...")
  773. time.sleep(1)
  774. continue
  775. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  776. if not ats:
  777. self._log(f"No timeslots for {tmp_date}")
  778. continue
  779. sel_tm = random.choice(ats)
  780. selected_slot_id = sel_tm.get("allocationId")
  781. selected_slot_date = tmp_date
  782. selected_slot_time_range = sel_tm.get("slot")
  783. found_slot = True
  784. break
  785. if found_slot:
  786. break
  787. if not found_slot:
  788. self._log("No valid slots found after scanning.")
  789. res.success = False
  790. return res
  791. self._log(f"Slot Selected: {selected_slot_date} {selected_slot_time_range} (ID: {selected_slot_id})")
  792. self._submit_no_addition_service(final_urn)
  793. amount, currency = self._query_fee(apt_config, final_urn)
  794. self._log("Submitting schedule...")
  795. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  796. if not schedule_res.get("IsAppointmentBooked"):
  797. self._log(f"Booking failed: {schedule_res}")
  798. res.success = False
  799. return res
  800. res.success = True
  801. res.account = self.config.account.username
  802. res.book_date = selected_slot_date
  803. res.book_time = selected_slot_time_range
  804. res.urn = final_urn
  805. if schedule_res.get("IsPaymentRequired", False):
  806. payload = schedule_res.get("payLoad", "")
  807. if payload:
  808. self._log("Processing payment link...")
  809. payment_url = self._pay_request(payload)
  810. if payment_url:
  811. res.payment_link = payment_url
  812. return res
  813. def _get_application(self):
  814. url = f"https://{self.vfs_api_domain}/appointment/application"
  815. headers = self._get_common_headers(with_auth=True)
  816. data = {
  817. 'countryCode': self.free_config.get("country_code"),
  818. 'missionCode': self.free_config.get("mission_code"),
  819. 'loginUser': self.config.account.username,
  820. 'languageCode': 'en-US',
  821. }
  822. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  823. return resp.json()
  824. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  825. """上传图片:根据前缀判断是下载外部图片还是读取本地文件,并上传到 VFS"""
  826. import requests as standard_requests
  827. url = f"https://{self.vfs_api_domain}/appointment/UploadApplicantDocument"
  828. passport_path_or_url = user_inputs.get("passport_image_url")
  829. if not passport_path_or_url:
  830. raise NotFoundError(message="Missing passport_image_url")
  831. if passport_path_or_url.startswith("http://") or passport_path_or_url.startswith("https://"):
  832. img_resp = standard_requests.get(passport_path_or_url, timeout=30)
  833. if img_resp.status_code != 200:
  834. raise BizLogicError(message=f"Failed to download passport image: {img_resp.status_code}")
  835. img_data = img_resp.content
  836. else:
  837. if not os.path.exists(passport_path_or_url):
  838. raise BizLogicError(message=f"Local passport image file not found: {passport_path_or_url}")
  839. with open(passport_path_or_url, "rb") as f:
  840. img_data = f.read()
  841. b64_str = base64.b64encode(img_data).decode('utf-8')
  842. headers = self._get_common_headers(with_auth=True)
  843. data = {
  844. "missioncode": self.free_config.get("mission_code"),
  845. "countryCode": self.free_config.get("country_code"),
  846. "centerCode": apt_config.get("vac_code"),
  847. "loginUser": self.config.account.username,
  848. "languageCode": "en-US",
  849. "visaCategoryCode": apt_config.get("subcategory_code"),
  850. "fileBytes": b64_str,
  851. "selfiImageFileBytes": ""
  852. }
  853. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  854. result = resp.json()
  855. result["passportImageFilename"] = "passport_img.jpg"
  856. result["passportImageFileBytes"] = b64_str
  857. return result
  858. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  859. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  860. """构造申请人 payload 并提交"""
  861. url = f"https://{self.vfs_api_domain}/appointment/applicants"
  862. headers = self._get_common_headers(with_auth=True)
  863. gender_str = str(user_inputs.get("gender", "")).lower()
  864. gender_code = 1 if gender_str == "male" else 2
  865. raw_dial = user_inputs.get("phone_country_code", "86")
  866. dial_code = str(raw_dial)
  867. # 日期格式转换 YYYY-MM-DD -> DD/MM/YYYY
  868. def _to_ddmmyyyy(d_str):
  869. try:
  870. return datetime.strptime(str(d_str), "%Y-%m-%d").strftime("%d/%m/%Y")
  871. except:
  872. return str(d_str)
  873. dob = _to_ddmmyyyy(user_inputs.get("birthday", ""))
  874. ppt_exp = _to_ddmmyyyy(user_inputs.get("passport_expiry_date", ""))
  875. applicant = {
  876. "urn": "",
  877. "arn": "",
  878. "loginUser": self.config.account.username,
  879. "firstName": str(user_inputs.get("first_name", "")).strip().upper(),
  880. "middleName": "",
  881. "lastName": str(user_inputs.get("last_name", "")).strip().upper(),
  882. "employerFirstName": "",
  883. "employerLastName": "",
  884. "salutation": "",
  885. "Subclasscode": None,
  886. "VisaToken": None,
  887. "centerClassCode": None,
  888. "dateOfApplication": None,
  889. "selectedSubvisaCategory": None,
  890. "gender": gender_code,
  891. "contactNumber": str(user_inputs.get("phone", "")).strip().lstrip("0"),
  892. "dialCode": dial_code,
  893. "employerContactNumber": "",
  894. "employerDialCode": "",
  895. "emailId": str(user_inputs.get("alias_email", "")).strip().upper(),
  896. "employerEmailId": "",
  897. "passportNumber": str(user_inputs.get("passport_no", "")).strip().upper(),
  898. "confirmPassportNumber": "",
  899. "passportExpirtyDate": ppt_exp,
  900. "dateOfBirth": dob,
  901. "nationalId": None,
  902. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  903. "state": user_inputs.get("state"),
  904. "city": user_inputs.get("city"),
  905. "addressline1": user_inputs.get("addressline1"),
  906. "addressline2": user_inputs.get("addressline2"),
  907. "pincode": None,
  908. "isEndorsedChild": False,
  909. "applicantType": 0,
  910. "vlnNumber": None,
  911. "applicantGroupId": 0,
  912. "parentPassportNumber": "",
  913. "parentPassportExpiry": "",
  914. "dateOfDeparture": None,
  915. "entryType": "",
  916. "eoiVisaType": "",
  917. "passportType": "",
  918. "vfsReferenceNumber": "",
  919. "familyReunificationCerificateNumber": "",
  920. "PVRequestRefNumber": "",
  921. "PVStatus": "",
  922. "PVStatusDescription": "",
  923. "PVCanAllowRetry": True,
  924. "PVisVerified": False,
  925. "eefRegistrationNumber": "",
  926. "isAutoRefresh": True,
  927. "helloVerifyNumber": "",
  928. "OfflineCClink": "",
  929. "idenfystatuscheck": False,
  930. "vafStatus": None,
  931. "SpecialAssistance": "",
  932. "AdditionalRefNo": None,
  933. "juridictionCode": "",
  934. "canInitiateVAF": False,
  935. "canEditVAF": False,
  936. "canDeleteVAF": False,
  937. "canDownloadVAF": False,
  938. "Retryleft": "",
  939. # 这里的 IP 应该已经在 create_session 时获取到了
  940. "ipAddress": self.real_ip
  941. }
  942. if enable_ref:
  943. applicant["referenceNumber"] = str(user_inputs.get("cover_letter_id", "")).strip()
  944. else:
  945. applicant["referenceNumber"] = None
  946. if ocr_enabled:
  947. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  948. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  949. applicant["GUID"] = str(user_inputs.get("guid", ""))
  950. payload = {
  951. "countryCode": self.free_config.get("country_code"),
  952. "missionCode": self.free_config.get("mission_code"),
  953. "centerCode": apt_config.get("vac_code"),
  954. "loginUser": self.config.account.username,
  955. "visaCategoryCode": apt_config.get("subcategory_code"),
  956. "applicantList": [applicant],
  957. "languageCode": "en-US",
  958. "isWaitlist": is_waitlist,
  959. "isEdit": False,
  960. "feeEntryTypeCode": None, "feeExemptionTypeCode": None,
  961. "feeExemptionDetailsCode": None, "juridictionCode": None, "regionCode": None
  962. }
  963. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  964. urn = resp.json().get("urn")
  965. if not urn:
  966. err_msg = resp.json().get('error')
  967. raise BizLogicError(message=str(err_msg))
  968. return urn
  969. def _applicant_otp_send(self, apt_config, urn) -> bool:
  970. url = f"https://{self.vfs_api_domain}/appointment/applicantotp"
  971. headers = self._get_common_headers(with_auth=True)
  972. data = {
  973. "urn": urn,
  974. "loginUser": self.config.account.username,
  975. "missionCode": self.free_config.get("mission_code"),
  976. "countryCode": self.free_config.get("country_code"),
  977. "centerCode": apt_config.get("vac_code"),
  978. "OTP": "",
  979. "otpAction": "GENERATE",
  980. "languageCode": "en-US"
  981. }
  982. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  983. return resp.json().get("isOTPGenerated", False)
  984. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  985. url = f"https://{self.vfs_api_domain}/appointment/applicantotp"
  986. headers = self._get_common_headers(with_auth=True)
  987. # VFS 这里的 header 有时需要 datacenter,原代码有就加上
  988. headers["datacenter"] = "GERMANY"
  989. data = {
  990. "urn": urn,
  991. "loginUser": self.config.account.username,
  992. "missionCode": self.free_config.get("mission_code"),
  993. "countryCode": self.free_config.get("country_code"),
  994. "centerCode": apt_config.get("vac_code"),
  995. "OTP": otp,
  996. "otpAction": "VALIDATE",
  997. "languageCode": "en-US"
  998. }
  999. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1000. return resp.json().get("isOTPValidated", False)
  1001. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  1002. url = f"https://{self.vfs_api_domain}/appointment/calendar"
  1003. headers = self._get_common_headers(with_auth=True)
  1004. # 将 YYYY-MM-DD 转为 DD/MM/YYYY 用于 API
  1005. dt_m = datetime.strptime(from_date, "%Y-%m-%d")
  1006. converted_date = dt_m.strftime("%d/%m/%Y")
  1007. data = {
  1008. "missionCode": self.free_config.get("mission_code"),
  1009. "countryCode": self.free_config.get("country_code"),
  1010. "centerCode": apt_config.get("vac_code"),
  1011. "loginUser": self.config.account.username,
  1012. "visaCategoryCode": apt_config.get("subcategory_code"),
  1013. "fromDate": converted_date,
  1014. "urn": urn,
  1015. "payCode": ""
  1016. }
  1017. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1018. calendars = resp.json().get("calendars")
  1019. ads_out = []
  1020. if calendars:
  1021. for item in calendars:
  1022. # 通常是 MM/DD/YYYY
  1023. raw = item.get("date")
  1024. ads_out.append(to_yyyymmdd(raw, "%m/%d/%Y"))
  1025. return ads_out
  1026. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  1027. url = f"https://{self.vfs_api_domain}/appointment/timeslot"
  1028. headers = self._get_common_headers(with_auth=True)
  1029. dt_m = datetime.strptime(slot_date, "%Y-%m-%d")
  1030. converted_date = dt_m.strftime("%d/%m/%Y")
  1031. data = {
  1032. "missionCode": self.free_config.get("mission_code"),
  1033. "countryCode": self.free_config.get("country_code"),
  1034. "centerCode": apt_config.get("vac_code"),
  1035. "loginUser": self.config.account.username,
  1036. "visaCategoryCode": apt_config.get("subcategory_code"),
  1037. "slotDate": converted_date,
  1038. "urn": urn
  1039. }
  1040. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1041. return resp.json().get("slots", [])
  1042. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  1043. url = f"https://{self.vfs_api_domain}/appointment/saveuseractionaudit"
  1044. headers = self._get_common_headers(with_auth=True)
  1045. dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  1046. data = {
  1047. "missionCode": self.free_config.get("mission_code"),
  1048. "countryCode": self.free_config.get("country_code"),
  1049. "centerCode": apt_config.get("vac_code"),
  1050. "loginUser": self.config.account.username,
  1051. "urn": urn,
  1052. "firstEarliestSlotDate": dt.strftime("%d/%m/%Y"),
  1053. "action": "schedule",
  1054. "ipAddress": self.real_ip,
  1055. "eadAppointmentDetail": dt.strftime("%Y-%m-%dT%H:%M:%S")
  1056. }
  1057. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1058. return resp.json().get("isSavedSuccess", False)
  1059. def _submit_no_addition_service(self, urn):
  1060. url = f"https://{self.vfs_api_domain}/vas/mapvas"
  1061. headers = self._get_common_headers(with_auth=True)
  1062. data = {
  1063. "loginUser": self.config.account.username,
  1064. "missionCode": self.free_config.get("mission_code"),
  1065. "countryCode": self.free_config.get("country_code"),
  1066. "urn": urn,
  1067. "applicants": []
  1068. }
  1069. self._perform_request("POST", url, headers=headers, json_data=data)
  1070. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  1071. url = f"https://{self.vfs_api_domain}/appointment/fees"
  1072. headers = self._get_common_headers(with_auth=True)
  1073. data = {
  1074. "missionCode": self.free_config.get("mission_code"),
  1075. "countryCode": self.free_config.get("country_code"),
  1076. "centerCode": apt_config.get("vac_code"),
  1077. "loginUser": self.config.account.username,
  1078. "urn": urn,
  1079. "languageCode": "en-US"
  1080. }
  1081. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1082. j = resp.json()
  1083. total = j.get("totalamount", 0.0)
  1084. currency = "EUR"
  1085. if j.get("feeDetails"):
  1086. currency = j["feeDetails"][0].get("currency", "EUR")
  1087. return total, currency
  1088. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  1089. url = f"https://{self.vfs_api_domain}/appointment/schedule"
  1090. headers = self._get_common_headers(with_auth=True)
  1091. data = {
  1092. "missionCode": self.free_config.get("mission_code"),
  1093. "countryCode": self.free_config.get("country_code"),
  1094. "centerCode": apt_config.get("vac_code"),
  1095. "loginUser": self.config.account.username,
  1096. "urn": urn,
  1097. "notificationType": "none",
  1098. "paymentdetails": {
  1099. "paymentmode": "Online",
  1100. "RequestRefNo": "",
  1101. "clientId": "",
  1102. "merchantId": "",
  1103. "amount": amount,
  1104. "currency": currency
  1105. },
  1106. "allocationId": str(slot_id),
  1107. "CanVFSReachoutToApplicant": True
  1108. }
  1109. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1110. return resp.json()
  1111. def _pay_request(self, payload) -> str:
  1112. """
  1113. 解析支付重定向 URL (DrissionPage 新标签页版)
  1114. """
  1115. start_url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={payload}"
  1116. final_url = ""
  1117. try:
  1118. self._log("Resolving payment redirect...")
  1119. pay_tab = self.page.new_tab(start_url)
  1120. pay_tab.wait.url_change(start_url, timeout=15)
  1121. final_url = pay_tab.url
  1122. self._log(f"Payment URL resolved: {final_url}")
  1123. pay_tab.close()
  1124. except Exception as e:
  1125. self._log(f"[WARN] Failed to resolve payment URL: {e}")
  1126. try:
  1127. pay_tab.close()
  1128. except:
  1129. pass
  1130. return final_url
  1131. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  1132. url = f"https://{self.vfs_api_domain}/appointment/ConfirmWaitlist"
  1133. headers = self._get_common_headers(with_auth=True)
  1134. data = {
  1135. "missionCode": self.free_config.get("mission_code"),
  1136. "countryCode": self.free_config.get("country_code"),
  1137. "centerCode": apt_config.get("vac_code"),
  1138. "loginUser": self.config.account.username,
  1139. "urn": urn,
  1140. "notificationType": "none",
  1141. "CanVFSReachoutToApplicant": True
  1142. }
  1143. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1144. return resp.json().get("isConfirmed", False)
  1145. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  1146. if not start_str or not end_str:
  1147. return dates
  1148. valid_dates = []
  1149. try:
  1150. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  1151. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  1152. for date_str in dates:
  1153. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  1154. if s_date <= curr_date <= e_date:
  1155. valid_dates.append(date_str)
  1156. random.shuffle(valid_dates)
  1157. return valid_dates
  1158. except:
  1159. return dates
  1160. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  1161. fmt = "%Y-%m-%d"
  1162. try:
  1163. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  1164. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.now().replace(year=datetime.now().year + 1)
  1165. try:
  1166. dt_from = datetime.strptime(from_date, fmt)
  1167. except:
  1168. dt_from = datetime.now()
  1169. except:
  1170. return []
  1171. dt_start = dt_start.replace(day=1)
  1172. dt_end = dt_end.replace(day=1)
  1173. dt_from = dt_from.replace(day=1)
  1174. curr = max(dt_start, dt_from)
  1175. months = []
  1176. while curr <= dt_end:
  1177. months.append(curr.strftime(fmt))
  1178. if curr.month == 12:
  1179. curr = curr.replace(year=curr.year + 1, month=1)
  1180. else:
  1181. curr = curr.replace(month=curr.month + 1)
  1182. return months
  1183. def cleanup(self):
  1184. """
  1185. 销毁浏览器并彻底删除临时文件
  1186. """
  1187. if self.page:
  1188. try:
  1189. self.page.quit()
  1190. except Exception:
  1191. pass
  1192. self.page = None
  1193. if os.path.exists(self.root_workspace):
  1194. for _ in range(3):
  1195. try:
  1196. time.sleep(0.2)
  1197. shutil.rmtree(self.root_workspace, ignore_errors=True)
  1198. break
  1199. except Exception as e:
  1200. self._log(f"Cleanup retry: {e}")
  1201. time.sleep(0.5)
  1202. if os.path.exists(self.root_workspace):
  1203. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  1204. if self.tunnel:
  1205. try: self.tunnel.stop()
  1206. except: pass
  1207. self.tunnel = None
  1208. def get_plugin_status(self) -> PluginStatus:
  1209. account_name = self.config.account.username if self.config and self.config.account else ""
  1210. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  1211. current_url = ""
  1212. if self.page:
  1213. try:
  1214. current_url = self.page.url
  1215. except Exception:
  1216. pass
  1217. session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
  1218. state = "running" if self.is_healthy else "unhealthy"
  1219. if not self.jwt_token and self.page:
  1220. state = "logging_in"
  1221. return PluginStatus(
  1222. instance_id=self.instance_id,
  1223. is_healthy=self.is_healthy,
  1224. state=state,
  1225. current_url=current_url,
  1226. account=account_name,
  1227. proxy=proxy_info,
  1228. session_age_sec=session_age,
  1229. last_active_at=utc_now_str(),
  1230. )
  1231. def __del__(self):
  1232. """
  1233. 析构函数:当对象被垃圾回收时自动调用
  1234. """
  1235. self.cleanup()