vfs_plugin2.py 62 KB

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