vfs_plugin2.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  24. # ----------------- 静态常量与辅助数据 -----------------
  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 create_proxy_auth_extension(ip, port, username, password, plugin_path):
  74. """
  75. 创建一个 Chrome 插件来自动处理代理认证
  76. """
  77. if not os.path.exists(plugin_path):
  78. os.makedirs(plugin_path)
  79. # 1. manifest.json
  80. manifest_json = """
  81. {
  82. "version": "1.0.0",
  83. "manifest_version": 2,
  84. "name": "Chrome Proxy Auth Extension",
  85. "permissions": [
  86. "proxy",
  87. "tabs",
  88. "unlimitedStorage",
  89. "storage",
  90. "<all_urls>",
  91. "webRequest",
  92. "webRequestBlocking"
  93. ],
  94. "background": {
  95. "scripts": ["background.js"]
  96. },
  97. "minimum_chrome_version": "22.0.0"
  98. }
  99. """
  100. # 2. background.js
  101. background_js = f"""
  102. var config = {{
  103. mode: "fixed_servers",
  104. rules: {{
  105. singleProxy: {{
  106. scheme: "http",
  107. host: "{ip}",
  108. port: parseInt({port})
  109. }},
  110. bypassList: ["localhost"]
  111. }}
  112. }};
  113. chrome.proxy.settings.set({{value: config, scope: "regular"}}, function() {{}});
  114. function callbackFn(details) {{
  115. return {{
  116. authCredentials: {{
  117. username: "{username}",
  118. password: "{password}"
  119. }}
  120. }};
  121. }}
  122. chrome.webRequest.onAuthRequired.addListener(
  123. callbackFn,
  124. {{urls: ["<all_urls>"]}},
  125. ['blocking']
  126. );
  127. """
  128. with open(os.path.join(plugin_path, "manifest.json"), "w") as f:
  129. f.write(manifest_json)
  130. with open(os.path.join(plugin_path, "background.js"), "w") as f:
  131. f.write(background_js)
  132. return os.path.abspath(plugin_path)
  133. # --- 模拟 Requests Response 对象 ---
  134. class BrowserResponse:
  135. def __init__(self, result_dict):
  136. result_dict = result_dict or {}
  137. self.status_code = result_dict.get('status', 0)
  138. self.text = result_dict.get('body', '')
  139. self.headers = result_dict.get('headers', {})
  140. self.url = result_dict.get('url', '')
  141. self._json = None
  142. def json(self):
  143. if self._json is None:
  144. if not self.text:
  145. return {}
  146. try:
  147. self._json = json.loads(self.text)
  148. except:
  149. self._json = {}
  150. return self._json
  151. @property
  152. def content(self):
  153. return self.text.encode('utf-8')
  154. class VfsPlugin2(IVSPlg):
  155. def __init__(self, group_id: str):
  156. self.group_id = group_id
  157. self.config: Optional[VSPlgConfig] = None
  158. self.free_config: Dict[str, Any] = {}
  159. self.logger = None
  160. # 替换 requests.Session 为 DrissionPage
  161. self.page: Optional[ChromiumPage] = None
  162. self.jwt_token: str = ""
  163. self.real_ip: str = ""
  164. self.is_healthy: bool = True
  165. self.center_conf = None
  166. self.category_conf: Dict = {}
  167. self.subcategory_conf: Dict = {}
  168. self.public_key = serialization.load_pem_public_key(
  169. VFS_PUBLIC_KEY_PEM.encode(),
  170. backend=default_backend()
  171. )
  172. # --- [核心修改] 并发隔离与资源管理 ---
  173. # 生成唯一实例 ID
  174. self.instance_id = uuid.uuid4().hex[:8]
  175. self.root_workspace = os.path.abspath(os.path.join("temp_browser_data", f"{self.group_id}_{self.instance_id}"))
  176. # 定义子目录:代理插件目录 & 浏览器用户数据目录
  177. self.proxy_ext_path = os.path.join(self.root_workspace, "proxy_ext")
  178. self.user_data_path = os.path.join(self.root_workspace, "user_data")
  179. # 确保根目录存在 (子目录由具体逻辑创建)
  180. if not os.path.exists(self.root_workspace):
  181. os.makedirs(self.root_workspace)
  182. self.session_create_time: float = 0
  183. def get_group_id(self) -> str:
  184. return self.group_id
  185. def set_config(self, config: VSPlgConfig):
  186. self.config = config
  187. self.free_config = config.free_config or {}
  188. def set_log(self, logger: Callable[[str], None]) -> None:
  189. self.logger = logger
  190. def _log(self, message):
  191. if self.logger:
  192. self.logger(f'[VfsPlugin] [{self.group_id}] {message}')
  193. else:
  194. print(f'[VfsPlugin] [{self.group_id}] {message}')
  195. def health_check(self) -> bool:
  196. if not self.is_healthy:
  197. return False
  198. if self.page is None:
  199. return False
  200. # 检查页面是否还活着
  201. try:
  202. if not self.page.run_js("return 1;"):
  203. return False
  204. except:
  205. return False
  206. if self.config.session_max_life > 0:
  207. current_time = time.time()
  208. elapsed_time = current_time - self.session_create_time
  209. if elapsed_time > self.config.session_max_life * 60:
  210. self._log(f"Session expired.")
  211. return False
  212. return True
  213. def create_session(self) -> None:
  214. """
  215. 使用 DrissionPage 创建会话:
  216. 1. 启动浏览器
  217. 2. 导航到登录页
  218. 3. 自动过盾并提取 Token (集成 CloudflareBypasser)
  219. 4. JS fetch 登录
  220. """
  221. self._log(f"Initializing Session (ID: {self.instance_id})...")
  222. # 0. 配置浏览器
  223. co = ChromiumOptions()
  224. co.auto_port()
  225. # --- [关键配置] 设置独立的用户数据目录 ---
  226. # 这样每个实例的 Cache, Cookies, LocalStorage 都是完全隔离的
  227. # 同时也防止了多进程争抢同一个 Default 文件夹导致的崩溃
  228. co.set_user_data_path(self.user_data_path)
  229. # 代理配置
  230. if self.config.proxy and self.config.proxy.ip:
  231. p = self.config.proxy
  232. if p.username and p.password:
  233. self._log(f"Configuring authenticated proxy: {p.ip}:{p.port}")
  234. # [关键调用] 生成该实例独享的插件
  235. plugin_path = create_proxy_auth_extension(
  236. p.ip, p.port, p.username, p.password,
  237. self.proxy_ext_path # 传入唯一路径
  238. )
  239. co.add_extension(plugin_path)
  240. else:
  241. self._log(f"Configuring standard proxy: {p.ip}:{p.port}")
  242. co.set_proxy(f"{p.scheme}://{p.ip}:{p.port}")
  243. co.headless(False)
  244. co.set_argument('--no-sandbox')
  245. co.set_argument('--disable-gpu')
  246. co.set_argument('--window-size=1920,1080')
  247. co.set_argument('--disable-blink-features=AutomationControlled')
  248. try:
  249. self.page = ChromiumPage(co)
  250. # 1. 导航到登录页面
  251. mission = self.free_config.get("mission_code", "")
  252. country = self.free_config.get("country_code", "")
  253. lang = self.free_config.get("language", "en")
  254. if not mission or not country:
  255. raise BizLogicError("Missing mission/country code config")
  256. login_page_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
  257. self._log(f"Navigating to {login_page_url}...")
  258. self.page.get(login_page_url)
  259. # -------------------------------------------------------------
  260. # [核心修改] 2. 智能 Cloudflare 过盾逻辑
  261. # -------------------------------------------------------------
  262. self._log("Handling Cloudflare challenge...")
  263. # 初始化过盾助手
  264. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  265. cf_token = ""
  266. # 循环检测 (40秒超时)
  267. for i in range(40):
  268. time.sleep(1)
  269. # A. 优先处理 Cookie 遮挡 (VFS 必须步骤)
  270. # 如果不关掉 cookie banner,验证码可能点不到
  271. self._handle_cookie_banner()
  272. # B. 尝试从 DOM 获取 Token (无感验证可能自动通过)
  273. try:
  274. ele = self.page.ele('@name=cf-turnstile-response')
  275. if ele and ele.value:
  276. cf_token = ele.value
  277. self._log("Cloudflare Turnstile token extracted.")
  278. break
  279. except:
  280. pass
  281. # C. 如果前 3 秒没自动出 Token,开始尝试点击
  282. if i > 2:
  283. try:
  284. # 开启 DFS 深度搜索模式 (防止 Shadow DOM 嵌套太深找不到)
  285. # 在第 10 秒后开启深度搜索,前期用快速搜索
  286. use_dfs = (i > 10)
  287. cf_bypasser.click_verification_button(is_dfs=use_dfs)
  288. except Exception as e:
  289. # 点击错误忽略,继续下一轮
  290. pass
  291. # D. 检查是否已经看到了登录框 (有时候 Token 提取慢了,但页面已经变了)
  292. if self.page.ele('tag:form') or self.page.ele('#mat-input-0'):
  293. self._log("Login form detected.")
  294. # 继续尝试提取一次 Token,如果实在没有也不要死循环
  295. if i > 5 and not cf_token:
  296. self._log("Form visible but token not found yet...")
  297. # -------------------------------------------------------------
  298. if not cf_token:
  299. # 最后尝试一次强取
  300. try:
  301. cf_token = self.page.ele('@name=cf-turnstile-response').value
  302. except:
  303. pass
  304. if not cf_token:
  305. self._log("[WARN] Could not extract Turnstile token.")
  306. raise BizLogicError(f"Could not extract Turnstile token.")
  307. # 3. 准备登录 API 参数
  308. email = self.config.account.username
  309. password = self.config.account.password
  310. enc_password = self._encrypt_password(password)
  311. client_src = self._get_client_source()
  312. orange_src = self._get_orange_source(email)
  313. url = "https://lift-api.vfsglobal.com/user/login"
  314. headers = self._get_common_headers(with_auth=False)
  315. headers.update({
  316. "clientsource": client_src,
  317. "orangex": orange_src
  318. })
  319. data = {
  320. "username": email,
  321. "password": enc_password,
  322. "missioncode": mission,
  323. "countrycode": country,
  324. "languageCode": "en-US",
  325. "captcha_version": "cloudflare-v1",
  326. "captcha_api_key": cf_token
  327. }
  328. self._log("Sending Login Request via Browser Fetch...")
  329. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  330. resp_json = resp.json()
  331. # 分支 1: 登录成功
  332. if resp_json.get('accessToken'):
  333. self.jwt_token = resp_json["accessToken"]
  334. self._log("Login successful, JWT obtained.")
  335. # 分支 2: OTP
  336. elif resp_json.get("enableOTPAuthentication"):
  337. self._log("Login requires OTP.")
  338. # 注意:_submit_login_otp 内部也会调用 _refresh_turnstile_token
  339. # 所以这里旧的 cf_token 其实用处不大,传过去也没事
  340. otp = self._read_otp_email()
  341. self._submit_login_otp(cf_token, otp)
  342. else:
  343. raise BizLogicError(f"Login failed: {resp.text[:200]}")
  344. self.session_create_time = time.time()
  345. try:
  346. self.real_ip = self._get_realnetwork_ip()
  347. except:
  348. self.real_ip = "0.0.0.0"
  349. except Exception as e:
  350. self._log(f"Create Session Failed: {e}")
  351. self.cleanup()
  352. raise e
  353. def query(self) -> VSQueryResult:
  354. """查询可预约 Slot"""
  355. result = VSQueryResult()
  356. appt_types = self.free_config.get("appointment_types", [])
  357. if not appt_types:
  358. raise NotFoundError(message="No matching appointment configuration found.")
  359. apt_config = random.choice(appt_types)
  360. try:
  361. self._fetch_configurations(apt_config)
  362. earliest_date = self._query_earliest_slot(apt_config)
  363. result.success = False
  364. result.availability_status = AvailabilityStatus.NoneAvailable
  365. result.visa_type = apt_config.get("visa_type", "")
  366. result.city = apt_config.get("city", "")
  367. result.routing_key = apt_config.get("routing_key", "")
  368. if earliest_date:
  369. result.success = True
  370. if "WaitList" in earliest_date:
  371. result.availability_status = AvailabilityStatus.Waitlist
  372. else:
  373. result.availability_status = AvailabilityStatus.Available
  374. result.earliest_date = earliest_date
  375. result.availability = [DateAvailability(date=earliest_date, times=[])]
  376. self._log(f"Slot Found! Date: {earliest_date}")
  377. else:
  378. self._log("No slots available.")
  379. except Exception as e:
  380. self._log(f"Query Error: {e}")
  381. raise e
  382. return result
  383. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  384. """
  385. 核心方法:在 DrissionPage 浏览器上下文中注入 JS 执行 fetch
  386. """
  387. if not self.page:
  388. raise BizLogicError("Browser session not initialized")
  389. # 1. 确保在正确的上下文 (VFS 登录页或 API 域名)
  390. # create_session 已经打开了页面,这里通常不需要额外跳转
  391. # 如果页面崩溃或跳转了,可能需要恢复
  392. # 2. 构造参数
  393. if params:
  394. if '?' in url:
  395. url += '&' + urllib.parse.urlencode(params)
  396. else:
  397. url += '?' + urllib.parse.urlencode(params)
  398. fetch_options = {
  399. "method": method.upper(),
  400. "headers": headers or {},
  401. "credentials": "include" # 关键:带上浏览器 Cookie
  402. }
  403. if json_data:
  404. fetch_options['body'] = json.dumps(json_data)
  405. fetch_options['headers']['Content-Type'] = 'application/json'
  406. elif data:
  407. if isinstance(data, dict):
  408. fetch_options['body'] = urllib.parse.urlencode(data)
  409. fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  410. else:
  411. fetch_options['body'] = data
  412. # 3. 注入 JS
  413. js_script = f"""
  414. const url = "{url}";
  415. const options = {json.dumps(fetch_options)};
  416. return fetch(url, options)
  417. .then(async response => {{
  418. const text = await response.text();
  419. const headers = {{}};
  420. response.headers.forEach((value, key) => headers[key] = value);
  421. return {{
  422. status: response.status,
  423. body: text,
  424. headers: headers,
  425. url: response.url
  426. }};
  427. }})
  428. .catch(error => {{
  429. return {{
  430. status: 0,
  431. body: error.toString(),
  432. headers: {{}},
  433. url: url
  434. }};
  435. }});
  436. """
  437. if self.config.debug:
  438. self._log(f"[Browser Fetch] {method} {url}")
  439. try:
  440. # run_js 直接返回 return 的对象
  441. res_dict = self.page.run_js(js_script, timeout=30)
  442. except Exception as e:
  443. raise BizLogicError(f"Browser JS Execution Error: {e}")
  444. resp = BrowserResponse(res_dict)
  445. # 4. 统一处理状态码
  446. if resp.status_code == 200:
  447. return resp
  448. elif resp.status_code == 401:
  449. self.is_healthy = False
  450. raise SessionExpiredOrInvalidError(f"401 Unauthorized: {resp.text[:100]}")
  451. elif resp.status_code == 403:
  452. raise PermissionDeniedError(f"403 Forbidden: {resp.text[:100]}")
  453. elif resp.status_code == 429:
  454. self.is_healthy = False
  455. raise RateLimiteddError(f"429 Rate Limit: {resp.text[:100]}")
  456. elif resp.status_code == 0:
  457. raise BizLogicError(f"Network Error (Fetch Failed): {resp.text}")
  458. else:
  459. # 允许 400 业务错误通过,交给上层解析 (例如登录失败)
  460. if url.endswith("/login") and resp.status_code == 400:
  461. return resp
  462. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  463. def _handle_cookie_banner(self):
  464. """
  465. 处理 OneTrust Cookie 遮挡
  466. 策略:尝试点击“接受所有”,如果点不到就直接移除 DOM
  467. """
  468. try:
  469. # 使用 JS 处理最快,且不会因为元素运动报错
  470. js = """
  471. try {
  472. // 1. 尝试点击 '接受所有' 按钮
  473. var acceptBtn = document.getElementById('onetrust-accept-btn-handler');
  474. if (acceptBtn) {
  475. acceptBtn.click();
  476. return true;
  477. }
  478. // 2. 如果没有按钮,或者还在遮挡,直接把整个 banner 删掉
  479. var banner = document.getElementById('onetrust-banner-sdk');
  480. if (banner) {
  481. banner.style.display = 'none'; // 隐藏
  482. banner.remove(); // 或者移除
  483. return true;
  484. }
  485. } catch(e) {}
  486. return false;
  487. """
  488. self.page.run_js(js)
  489. except:
  490. pass
  491. def _get_proxy_url(self):
  492. if self.config.proxy and self.config.proxy.ip:
  493. s = self.config.proxy
  494. if s.username:
  495. return f"{s.scheme}://{s.username}:{s.password}@{s.ip}:{s.port}"
  496. else:
  497. return f"{s.scheme}://{s.ip}:{s.port}"
  498. return None
  499. def _get_realnetwork_ip(self):
  500. """
  501. 通过新建标签页获取 IP
  502. 解决 CORS 403 问题:新标签页请求属于 Top-Level Navigation,
  503. 不带 Origin: visa.vfsglobal.com,也不带 credentials,符合 ipify 规则。
  504. """
  505. try:
  506. # 1. 新建一个标签页 (后台静默打开)
  507. tab = self.page.new_tab("https://api.ipify.org/?format=json")
  508. # 2. 获取页面内容 (DrissionPage 会自动等待页面加载)
  509. # ipify 返回的是纯 JSON 文本,通常在 body 或 pre 标签里
  510. if tab.ele('tag:pre'):
  511. json_text = tab.ele('tag:pre').text
  512. else:
  513. json_text = tab.ele('tag:body').text
  514. # 3. 提取 IP
  515. ip = json.loads(json_text)['ip']
  516. # 4. 务必关闭标签页,释放资源
  517. tab.close()
  518. self._log(f"Real Network IP: {ip}")
  519. return ip
  520. except Exception as e:
  521. self._log(f"[WARN] Failed to check IP via new tab: {e}")
  522. # 尝试清理可能没关掉的标签页
  523. try:
  524. if self.page.tabs_count > 1:
  525. tab.close()
  526. except:
  527. pass
  528. return "0.0.0.0"
  529. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  530. # DrissionPage 浏览器会自动带上 Origin, Referer, User-Agent, Sec-CH-UA 等
  531. # 这里只需要补充业务特定的 Headers
  532. mission = self.free_config.get("mission_code", "")
  533. country = self.free_config.get("country_code", "")
  534. lang = self.free_config.get("language", "en")
  535. route = f"{country}/{lang}/{mission}"
  536. h = {
  537. "accept": "application/json, text/plain, */*",
  538. # "origin": ... 浏览器自动处理
  539. # "referer": ... 浏览器自动处理
  540. "route": route
  541. }
  542. # 即使是浏览器环境,VFS 也需要这两个加密参数
  543. # 注意:这里可能需要从 JS 获取,或者保持 Python 生成
  544. # 如果 Python 生成的总是报错,可以考虑把加密逻辑移到 JS 里跑
  545. h["clientsource"] = self._get_client_source()
  546. if with_auth and self.jwt_token:
  547. h["authorize"] = self.jwt_token
  548. return h
  549. def _encrypt_password(self, password: str) -> str:
  550. ciphertext = self.public_key.encrypt(
  551. password.encode(),
  552. padding.OAEP(
  553. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  554. algorithm=hashes.SHA256(),
  555. label=None
  556. )
  557. )
  558. return base64.b64encode(ciphertext).decode()
  559. def _get_orange_source(self, email: str) -> str:
  560. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  561. payload = f"{email};{timestamp}"
  562. return self._encrypt_password(payload)
  563. def _get_client_source(self) -> str:
  564. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  565. payload = f"GA;{timestamp}Z"
  566. return self._encrypt_password(payload)
  567. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  568. url = "https://lift-api.vfsglobal.com/appointment/CheckIsSlotAvailable"
  569. data = {
  570. "missioncode": self.free_config.get("mission_code"),
  571. "countrycode": self.free_config.get("country_code"),
  572. "vacCode": apt_config.get("vac_code"),
  573. "visaCategoryCode": apt_config.get("subcategory_code"),
  574. "roleName": "Individual",
  575. "loginUser": self.config.account.username,
  576. "payCode": ""
  577. }
  578. headers = self._get_common_headers(with_auth=True)
  579. # fetch 不需要显式 content-type application/json,json_data会自动处理
  580. # DrissionPage 不需要手动处理 403 绕盾,因为浏览器本身就在盾后面
  581. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  582. if "WaitList" in resp.text:
  583. return "WaitList"
  584. j = resp.json()
  585. if j.get("earliestSlotLists"):
  586. raw_date = j["earliestSlotLists"][0]["date"]
  587. return to_yyyymmdd(raw_date, "%m/%d/%Y %H:%M:%S")
  588. return ""
  589. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  590. if not self.center_conf:
  591. self.center_conf = self._query_center()
  592. vac_code = apt_config.get("vac_code")
  593. category_code = apt_config.get("category_code")
  594. if category_code not in self.category_conf:
  595. visa_categories = self._query_visa_category(vac_code)
  596. found = False
  597. for vc in visa_categories:
  598. if vc.get("code") == category_code:
  599. self.category_conf[category_code] = vc
  600. found = True
  601. break
  602. if not found:
  603. self._log(f"WARN: Category {category_code} not found")
  604. sub_category_code = apt_config.get("subcategory_code")
  605. if sub_category_code not in self.subcategory_conf:
  606. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  607. found = False
  608. for svc in visa_subcategories:
  609. if svc.get("code") == sub_category_code:
  610. self.subcategory_conf[sub_category_code] = svc
  611. found = True
  612. break
  613. if not found:
  614. self._log(f"WARN: SubCategory {sub_category_code} not found")
  615. def _query_center(self) -> List:
  616. mission = self.free_config.get("mission_code")
  617. country = self.free_config.get("country_code")
  618. url = f"https://lift-api.vfsglobal.com/master/center/{mission}/{country}/en-US"
  619. headers = self._get_common_headers(with_auth=False)
  620. resp = self._perform_request("GET", url, headers=headers)
  621. return resp.json()
  622. def _query_visa_category(self, center_code: str) -> List:
  623. mission = self.free_config.get("mission_code")
  624. country = self.free_config.get("country_code")
  625. enc_center = urllib.parse.quote(center_code)
  626. url = f"https://lift-api.vfsglobal.com/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  627. headers = self._get_common_headers(with_auth=False)
  628. resp = self._perform_request("GET", url, headers=headers)
  629. return resp.json()
  630. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  631. mission = self.free_config.get("mission_code")
  632. country = self.free_config.get("country_code")
  633. enc_center = urllib.parse.quote(center_code)
  634. enc_cat = urllib.parse.quote(category_code)
  635. url = f"https://lift-api.vfsglobal.com/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  636. headers = self._get_common_headers(with_auth=False)
  637. resp = self._perform_request("GET", url, headers=headers)
  638. return resp.json()
  639. def _read_otp_email(self) -> str:
  640. # 保持原样,这部分使用云API读取邮件,不依赖本地网络库
  641. master_email = "visafly666@gmail.com"
  642. recipient = self.config.account.username
  643. sender = "donotreply at vfshelpline.com"
  644. subject_keywords = "One Time Password"
  645. body_keywords = "OTP"
  646. now_utc = datetime.utcnow()
  647. formatted_utc_time = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  648. self._log(f"Waiting for OTP email...")
  649. for i in range(12):
  650. content_out = VSCloudApi.Instance().fetch_mail_content(
  651. master_email, sender, recipient, subject_keywords, body_keywords, formatted_utc_time, 300
  652. )
  653. if content_out:
  654. match = re.search(r'\b\d{6}\b', content_out)
  655. if match:
  656. return match.group(0)
  657. time.sleep(5)
  658. raise NotFoundError(message="OTP email not found")
  659. def _submit_login_otp(self, old_cf_token: str, otp: str):
  660. self._log("Submitting Login OTP...")
  661. # --- [新增] 必须刷新 Token ---
  662. # 旧的 old_cf_token 已经在第一步登录时失效了
  663. new_cf_token = self._refresh_turnstile_token()
  664. # ---------------------------
  665. email = self.config.account.username
  666. password = self.config.account.password
  667. enc_password = self._encrypt_password(password)
  668. mission = self.free_config.get("mission_code", "")
  669. country = self.free_config.get("country_code", "")
  670. client_src = self._get_client_source()
  671. orange_src = self._get_orange_source(email)
  672. url = "https://lift-api.vfsglobal.com/user/login"
  673. headers = self._get_common_headers(with_auth=False)
  674. headers.update({
  675. "clientsource": client_src,
  676. "orangex": orange_src
  677. })
  678. data = {
  679. "username": email,
  680. "password": enc_password,
  681. "missioncode": mission,
  682. "countrycode": country,
  683. "languageCode": "en-US",
  684. "captcha_version": "cloudflare-v1",
  685. "captcha_api_key": new_cf_token, # <--- 使用新 Token
  686. "otp": otp
  687. }
  688. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  689. resp_json = resp.json()
  690. if resp_json.get("accessToken"):
  691. self.jwt_token = resp_json["accessToken"]
  692. self._log("OTP Login successful.")
  693. return
  694. # 增加错误详情日志
  695. error_desc = resp_json.get("description", resp.text)
  696. raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
  697. def _refresh_turnstile_token(self) -> str:
  698. """
  699. 强制刷新 Cloudflare Turnstile 并获取新 Token (集成 CloudflareBypasser 版)
  700. """
  701. self._log("Refreshing Cloudflare Turnstile token...")
  702. # 1. JS 强制重置 (保持不变)
  703. js_reset = """
  704. try {
  705. var input = document.querySelector('input[name="cf-turnstile-response"]');
  706. if (input) input.value = "";
  707. window.turnstile.reset();
  708. } catch(e) {
  709. console.log("Turnstile reset error:", e);
  710. }
  711. """
  712. self.page.run_js(js_reset)
  713. # 2. 初始化过盾助手
  714. # 假设 CloudflareBypasser 类已在当前文件中定义
  715. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
  716. # 3. 轮询等待 (30秒)
  717. for i in range(60):
  718. time.sleep(0.5)
  719. # A. 检查 Token 是否已生成
  720. # 使用 DrissionPage 的方式获取 value 比较稳定
  721. try:
  722. ele = self.page.ele('@name=cf-turnstile-response')
  723. if ele and ele.value:
  724. self._log("Turnstile token refreshed successfully.")
  725. return ele.value
  726. except:
  727. pass
  728. # B. 尝试点击验证框
  729. # 策略:前2秒等待,之后开始尝试点击
  730. if i > 4:
  731. # [重要] VFS 经常有 Cookie 弹窗遮挡,先尝试清理一下
  732. self._handle_cookie_banner()
  733. try:
  734. # 使用 CloudflareBypasser 的高级点击逻辑
  735. # is_dfs=True 表示如果普通搜索找不到,就递归搜索 iframe (更耗时但更强)
  736. # 我们在尝试 10 次 (5秒) 后开启 DFS 模式
  737. use_dfs = (i > 14)
  738. cf_bypasser.click_verification_button(is_dfs=use_dfs)
  739. except Exception as e:
  740. # 点击过程报错不要中断主循环
  741. pass
  742. raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
  743. # -------------------------------------------------------------
  744. # 核心预约逻辑 (DrissionPage 版)
  745. # -------------------------------------------------------------
  746. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  747. """
  748. 执行完整的预约流程
  749. """
  750. self._log("Starting booking process...")
  751. # 1. 准备数据
  752. user_email = user_inputs.get('email')
  753. # 生成别名邮箱 (防止邮箱被 VFS 黑名单)
  754. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="gmail-app.com")
  755. res = VSBookResult()
  756. slot_routing_key = slot_info.routing_key
  757. # 如果没有 earliest_date,默认从今天开始
  758. from_date = slot_info.earliest_date if slot_info.earliest_date else datetime.now().strftime("%Y-%m-%d")
  759. # 2. 查找对应的配置
  760. apt_config = None
  761. appt_types = self.free_config.get("appointment_types", [])
  762. for apt in appt_types:
  763. if apt.get("routing_key") == slot_routing_key:
  764. apt_config = apt
  765. break
  766. if not apt_config:
  767. raise NotFoundError(message="Book: Config missing for this routing key.")
  768. # 确保配置已加载 (SubCategory 等)
  769. self._fetch_configurations(apt_config)
  770. sub_cc = apt_config.get("subcategory_code")
  771. sub_conf = self.subcategory_conf.get(sub_cc, {})
  772. # 3. OCR 识别 / 文档上传 (如果需要)
  773. # 上传结果存入 user_inputs 供后续使用
  774. ocr_enabled = sub_conf.get("isOCREnable", False)
  775. if ocr_enabled:
  776. self._log("OCR Enabled, uploading documents...")
  777. upload_res = self._upload_applicant_documents(apt_config, user_inputs)
  778. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  779. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes")
  780. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  781. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  782. # 4. 添加申请人 (核心步骤 1)
  783. final_urn = None
  784. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  785. # 重试机制:添加申请人有时候会因为并发冲突失败
  786. MAX_RETRY = 3
  787. for i in range(MAX_RETRY):
  788. try:
  789. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  790. if final_urn:
  791. break
  792. except Exception as e:
  793. self._log(f"Add Applicant retry {i+1}/{MAX_RETRY}: {e}")
  794. time.sleep(2)
  795. if not final_urn:
  796. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken or API error)")
  797. self._log(f"Applicant Added. URN: {final_urn}")
  798. # 5. 申请人 OTP 验证 (核心步骤 2 - 视配置而定)
  799. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  800. if otp_enabled:
  801. self._log("Applicant OTP Required.")
  802. if not self._applicant_otp_send(apt_config, final_urn):
  803. raise BizLogicError(message='Applicant OTP send failed')
  804. # 复用之前的读邮件逻辑
  805. otp_code = self._read_otp_email()
  806. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  807. raise BizLogicError(message='Applicant OTP verify failed')
  808. # 6. Waitlist 模式直接返回
  809. if is_waitlist:
  810. if self._confirm_waitlist(apt_config, final_urn):
  811. res.success = True
  812. res.urn = final_urn
  813. self._log("Waitlist confirmed.")
  814. return res
  815. raise BizLogicError(message='Confirm waitlist failed')
  816. # 7. 寻找具体的时间槽 (核心步骤 3)
  817. expected_start = user_inputs.get("expected_start_date", "")
  818. expected_end = user_inputs.get("expected_end_date", "")
  819. # 计算需要扫描的月份
  820. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  821. self._log(f"Scanning months: {months} (Start looking from: {from_date})")
  822. selected_slot_id = ""
  823. selected_slot_date = ""
  824. selected_slot_time_range = ""
  825. all_ads = set()
  826. forbidden_dates = set()
  827. found_slot = False
  828. for m_str in months:
  829. self._log(f"Checking calendar for {m_str}...")
  830. # 查询日历
  831. ads = self._query_slot_calendar(apt_config, final_urn, m_str)
  832. # 去重
  833. new_ads = [d for d in ads if d not in all_ads]
  834. all_ads.update(new_ads)
  835. # 尝试选中一个日期
  836. # 这里做一个简单循环,如果选中日期没时间了,就换一个日期
  837. for _ in range(3):
  838. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  839. # 根据用户期望过滤
  840. sel_dates = self._filter_dates(avail_candidates, expected_start, expected_end)
  841. if not sel_dates:
  842. break # 当前月没有符合要求的日期,去下一个月
  843. tmp_date = sel_dates[0] # 取第一个(通常 _filter_dates 里已经 shuffle 过了)
  844. forbidden_dates.add(tmp_date) # 标记为已尝试
  845. # 关键:Audit Log (锁定日期)
  846. # VFS 要求在查 timeslot 之前必须先发这个请求
  847. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  848. self._log(f"Audit failed for {tmp_date}, skipping...")
  849. time.sleep(1)
  850. continue
  851. # 查询具体时间
  852. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  853. if not ats:
  854. self._log(f"No timeslots for {tmp_date}")
  855. continue
  856. # 随机选一个时间
  857. sel_tm = random.choice(ats)
  858. selected_slot_id = sel_tm.get("allocationId")
  859. selected_slot_date = tmp_date
  860. selected_slot_time_range = sel_tm.get("slot")
  861. found_slot = True
  862. break
  863. if found_slot:
  864. break
  865. if not found_slot:
  866. self._log("No valid slots found after scanning.")
  867. res.success = False
  868. return res
  869. self._log(f"Slot Selected: {selected_slot_date} {selected_slot_time_range} (ID: {selected_slot_id})")
  870. # 8. 服务与费用 (核心步骤 4)
  871. self._submit_no_addition_service(final_urn)
  872. amount, currency = self._query_fee(apt_config, final_urn)
  873. # 9. 最终提交
  874. self._log("Submitting schedule...")
  875. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  876. if not schedule_res.get("IsAppointmentBooked"):
  877. self._log(f"Booking failed: {schedule_res}")
  878. res.success = False
  879. return res
  880. # 10. 构造成功结果
  881. res.success = True
  882. res.account = self.config.account.username
  883. res.book_date = selected_slot_date
  884. res.book_time = selected_slot_time_range
  885. res.urn = final_urn
  886. res.fee_amount = int(amount * 100)
  887. res.fee_currency = currency
  888. # 11. 处理支付链接
  889. if schedule_res.get("IsPaymentRequired", False):
  890. payload = schedule_res.get("payLoad", "")
  891. if payload:
  892. self._log("Processing payment link...")
  893. payment_url = self._pay_request(payload)
  894. if payment_url:
  895. res.payment_link = payment_url
  896. return res
  897. # -------------------------------------------------------------
  898. # 辅助方法实现 (DrissionPage 适配版)
  899. # -------------------------------------------------------------
  900. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  901. """上传图片:先下载外部图片,再通过浏览器上传到 VFS"""
  902. import requests as standard_requests # 使用标准库下载外部资源
  903. url = "https://lift-api.vfsglobal.com/appointment/UploadApplicantDocument"
  904. passport_url = user_inputs.get("passport_image_url")
  905. if not passport_url:
  906. raise NotFoundError(message="Missing passport_image_url")
  907. # 下载图片 (不走代理或走系统代理,不使用 DrissionPage,因为是外部链接)
  908. try:
  909. img_resp = standard_requests.get(passport_url, timeout=30)
  910. if img_resp.status_code != 200:
  911. raise BizLogicError(message=f"Failed to download passport image: {img_resp.status_code}")
  912. b64_str = base64.b64encode(img_resp.content).decode('utf-8')
  913. except Exception as e:
  914. raise BizLogicError(message=f"Image download error: {e}")
  915. headers = self._get_common_headers(with_auth=True)
  916. # DrissionPage fetch 不需要显式 content-type application/json,json_data会自动处理
  917. data = {
  918. "missioncode": self.free_config.get("mission_code"),
  919. "countryCode": self.free_config.get("country_code"),
  920. "centerCode": apt_config.get("vac_code"),
  921. "loginUser": self.config.account.username,
  922. "languageCode": "en-US",
  923. "visaCategoryCode": apt_config.get("subcategory_code"),
  924. "fileBytes": b64_str,
  925. "selfiImageFileBytes": ""
  926. }
  927. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  928. result = resp.json()
  929. # 补充返回数据供后续使用
  930. result["passportImageFilename"] = "passport_img.jpg"
  931. result["passportImageFileBytes"] = b64_str
  932. return result
  933. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  934. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  935. """构造申请人 payload 并提交"""
  936. url = "https://lift-api.vfsglobal.com/appointment/applicants"
  937. headers = self._get_common_headers(with_auth=True)
  938. gender_str = str(user_inputs.get("gender", "")).lower()
  939. gender_code = 1 if gender_str == "male" else 2
  940. raw_dial = user_inputs.get("phone_country_code", "86")
  941. dial_code = str(raw_dial)
  942. # 日期格式转换 YYYY-MM-DD -> DD/MM/YYYY
  943. def _to_ddmmyyyy(d_str):
  944. try:
  945. return datetime.strptime(str(d_str), "%Y-%m-%d").strftime("%d/%m/%Y")
  946. except:
  947. return str(d_str)
  948. dob = _to_ddmmyyyy(user_inputs.get("birthday", ""))
  949. ppt_exp = _to_ddmmyyyy(user_inputs.get("passport_expiry_date", ""))
  950. applicant = {
  951. "urn": "",
  952. "arn": "",
  953. "loginUser": self.config.account.username,
  954. "firstName": str(user_inputs.get("first_name", "")).upper(),
  955. "middleName": "",
  956. "lastName": str(user_inputs.get("last_name", "")).upper(),
  957. "employerFirstName": "",
  958. "employerLastName": "",
  959. "salutation": "",
  960. "gender": gender_code,
  961. "contactNumber": str(user_inputs.get("phone", "")),
  962. "dialCode": dial_code,
  963. "employerContactNumber": "",
  964. "employerDialCode": "",
  965. "emailId": str(user_inputs.get("alias_email", "")).upper(),
  966. "employerEmailId": "",
  967. "passportNumber": str(user_inputs.get("passport_no", "")).upper(),
  968. "confirmPassportNumber": "",
  969. "passportExpirtyDate": ppt_exp,
  970. "dateOfBirth": dob,
  971. "nationalId": None,
  972. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  973. "state": None, "city": None, "addressline1": None, "addressline2": None, "pincode": None,
  974. "isEndorsedChild": False, "applicantType": 0, "vlnNumber": None, "applicantGroupId": 0,
  975. "parentPassportNumber": "", "parentPassportExpiry": "", "dateOfDeparture": None,
  976. "entryType": "", "eoiVisaType": "", "passportType": "", "vfsReferenceNumber": "",
  977. "familyReunificationCerificateNumber": "", "PVRequestRefNumber": "", "PVStatus": "",
  978. "PVStatusDescription": "", "PVCanAllowRetry": True, "PVisVerified": False,
  979. "eefRegistrationNumber": "", "isAutoRefresh": True, "helloVerifyNumber": "",
  980. "OfflineCClink": "", "idenfystatuscheck": False, "vafStatus": None,
  981. "SpecialAssistance": "", "AdditionalRefNo": None, "juridictionCode": "",
  982. "canInitiateVAF": False, "canEditVAF": False, "canDeleteVAF": False,
  983. "canDownloadVAF": False, "Retryleft": "",
  984. # 这里的 IP 应该已经在 create_session 时获取到了
  985. "ipAddress": self.real_ip
  986. }
  987. if enable_ref:
  988. applicant["referenceNumber"] = str(user_inputs.get("cover_letter", ""))
  989. else:
  990. applicant["referenceNumber"] = None
  991. if ocr_enabled:
  992. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  993. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  994. applicant["GUID"] = str(user_inputs.get("guid", ""))
  995. payload = {
  996. "countryCode": self.free_config.get("country_code"),
  997. "missionCode": self.free_config.get("mission_code"),
  998. "centerCode": apt_config.get("vac_code"),
  999. "loginUser": self.config.account.username,
  1000. "visaCategoryCode": apt_config.get("subcategory_code"),
  1001. "applicantList": [applicant],
  1002. "languageCode": "en-US",
  1003. "isWaitlist": is_waitlist,
  1004. "isEdit": False,
  1005. "feeEntryTypeCode": None, "feeExemptionTypeCode": None,
  1006. "feeExemptionDetailsCode": None, "juridictionCode": None, "regionCode": None
  1007. }
  1008. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  1009. return resp.json().get("urn")
  1010. def _applicant_otp_send(self, apt_config, urn) -> bool:
  1011. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  1012. headers = self._get_common_headers(with_auth=True)
  1013. data = {
  1014. "urn": urn,
  1015. "loginUser": self.config.account.username,
  1016. "missionCode": self.free_config.get("mission_code"),
  1017. "countryCode": self.free_config.get("country_code"),
  1018. "centerCode": apt_config.get("vac_code"),
  1019. "OTP": "",
  1020. "otpAction": "GENERATE",
  1021. "languageCode": "en-US"
  1022. }
  1023. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1024. return resp.json().get("isOTPGenerated", False)
  1025. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  1026. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  1027. headers = self._get_common_headers(with_auth=True)
  1028. # VFS 这里的 header 有时需要 datacenter,原代码有就加上
  1029. headers["datacenter"] = "GERMANY"
  1030. data = {
  1031. "urn": urn,
  1032. "loginUser": self.config.account.username,
  1033. "missionCode": self.free_config.get("mission_code"),
  1034. "countryCode": self.free_config.get("country_code"),
  1035. "centerCode": apt_config.get("vac_code"),
  1036. "OTP": otp,
  1037. "otpAction": "VALIDATE",
  1038. "languageCode": "en-US"
  1039. }
  1040. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1041. return resp.json().get("isOTPValidated", False)
  1042. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  1043. url = "https://lift-api.vfsglobal.com/appointment/calendar"
  1044. headers = self._get_common_headers(with_auth=True)
  1045. # 将 YYYY-MM-DD 转为 DD/MM/YYYY 用于 API
  1046. dt_m = datetime.strptime(from_date, "%Y-%m-%d")
  1047. converted_date = dt_m.strftime("%d/%m/%Y")
  1048. data = {
  1049. "missionCode": self.free_config.get("mission_code"),
  1050. "countryCode": self.free_config.get("country_code"),
  1051. "centerCode": apt_config.get("vac_code"),
  1052. "loginUser": self.config.account.username,
  1053. "visaCategoryCode": apt_config.get("subcategory_code"),
  1054. "fromDate": converted_date,
  1055. "urn": urn,
  1056. "payCode": ""
  1057. }
  1058. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1059. calendars = resp.json().get("calendars")
  1060. ads_out = []
  1061. if calendars:
  1062. for item in calendars:
  1063. # API 返回可能是 MM/DD/YYYY 或 DD/MM/YYYY,VFS 比较乱
  1064. # 通常是 MM/DD/YYYY
  1065. raw = item.get("date")
  1066. ads_out.append(to_yyyymmdd(raw, "%m/%d/%Y"))
  1067. return ads_out
  1068. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  1069. url = "https://lift-api.vfsglobal.com/appointment/timeslot"
  1070. headers = self._get_common_headers(with_auth=True)
  1071. dt_m = datetime.strptime(slot_date, "%Y-%m-%d")
  1072. converted_date = dt_m.strftime("%d/%m/%Y")
  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. "visaCategoryCode": apt_config.get("subcategory_code"),
  1079. "slotDate": converted_date,
  1080. "urn": urn
  1081. }
  1082. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1083. return resp.json().get("slots", [])
  1084. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  1085. url = "https://lift-api.vfsglobal.com/appointment/saveuseractionaudit"
  1086. headers = self._get_common_headers(with_auth=True)
  1087. dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  1088. data = {
  1089. "missionCode": self.free_config.get("mission_code"),
  1090. "countryCode": self.free_config.get("country_code"),
  1091. "centerCode": apt_config.get("vac_code"),
  1092. "loginUser": self.config.account.username,
  1093. "urn": urn,
  1094. "firstEarliestSlotDate": dt.strftime("%d/%m/%Y"),
  1095. "action": "schedule",
  1096. "ipAddress": self.real_ip,
  1097. "eadAppointmentDetail": dt.strftime("%Y-%m-%dT%H:%M:%S")
  1098. }
  1099. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1100. return resp.json().get("isSavedSuccess", False)
  1101. def _submit_no_addition_service(self, urn):
  1102. url = "https://lift-api.vfsglobal.com/vas/mapvas"
  1103. headers = self._get_common_headers(with_auth=True)
  1104. data = {
  1105. "loginUser": self.config.account.username,
  1106. "missionCode": self.free_config.get("mission_code"),
  1107. "countryCode": self.free_config.get("country_code"),
  1108. "urn": urn,
  1109. "applicants": []
  1110. }
  1111. # 只要不报错即可
  1112. self._perform_request("POST", url, headers=headers, json_data=data)
  1113. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  1114. url = "https://lift-api.vfsglobal.com/appointment/fees"
  1115. headers = self._get_common_headers(with_auth=True)
  1116. data = {
  1117. "missionCode": self.free_config.get("mission_code"),
  1118. "countryCode": self.free_config.get("country_code"),
  1119. "centerCode": apt_config.get("vac_code"),
  1120. "loginUser": self.config.account.username,
  1121. "urn": urn,
  1122. "languageCode": "en-US"
  1123. }
  1124. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1125. j = resp.json()
  1126. total = j.get("totalamount", 0.0)
  1127. currency = "EUR"
  1128. if j.get("feeDetails"):
  1129. currency = j["feeDetails"][0].get("currency", "EUR")
  1130. return total, currency
  1131. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  1132. url = "https://lift-api.vfsglobal.com/appointment/schedule"
  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. "paymentdetails": {
  1142. "paymentmode": "Online",
  1143. "RequestRefNo": "",
  1144. "clientId": "",
  1145. "merchantId": "",
  1146. "amount": amount,
  1147. "currency": currency
  1148. },
  1149. "allocationId": str(slot_id),
  1150. "CanVFSReachoutToApplicant": True
  1151. }
  1152. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1153. return resp.json()
  1154. def _pay_request(self, payload) -> str:
  1155. """
  1156. 解析支付重定向 URL (DrissionPage 新标签页版)
  1157. """
  1158. # 初始 URL,通常是一个 Redirect 接口
  1159. start_url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={payload}"
  1160. final_url = ""
  1161. try:
  1162. self._log("Resolving payment redirect...")
  1163. # 使用新标签页去跑,以免当前会话状态丢失
  1164. pay_tab = self.page.new_tab(start_url)
  1165. # 等待跳转完成 (通常会跳到 Stripe, WorldPay 或其他支付网关)
  1166. # 等待直到 URL 不再是 PayRequest
  1167. pay_tab.wait.url_change(start_url, timeout=15)
  1168. final_url = pay_tab.url
  1169. self._log(f"Payment URL resolved: {final_url}")
  1170. # 关闭标签页
  1171. pay_tab.close()
  1172. except Exception as e:
  1173. self._log(f"[WARN] Failed to resolve payment URL: {e}")
  1174. try:
  1175. pay_tab.close()
  1176. except:
  1177. pass
  1178. return final_url
  1179. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  1180. url = "https://lift-api.vfsglobal.com/appointment/ConfirmWaitlist"
  1181. headers = self._get_common_headers(with_auth=True)
  1182. data = {
  1183. "missionCode": self.free_config.get("mission_code"),
  1184. "countryCode": self.free_config.get("country_code"),
  1185. "centerCode": apt_config.get("vac_code"),
  1186. "loginUser": self.config.account.username,
  1187. "urn": urn,
  1188. "notificationType": "none",
  1189. "CanVFSReachoutToApplicant": True
  1190. }
  1191. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1192. return resp.json().get("isConfirmed", False)
  1193. def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
  1194. if not start_str or not end_str:
  1195. return dates
  1196. valid_dates = []
  1197. try:
  1198. s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
  1199. e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
  1200. for date_str in dates:
  1201. curr_date = datetime.strptime(date_str, "%Y-%m-%d")
  1202. if s_date <= curr_date <= e_date:
  1203. valid_dates.append(date_str)
  1204. random.shuffle(valid_dates)
  1205. return valid_dates
  1206. except:
  1207. return dates
  1208. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  1209. fmt = "%Y-%m-%d"
  1210. try:
  1211. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  1212. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.now().replace(year=datetime.now().year + 1)
  1213. try:
  1214. dt_from = datetime.strptime(from_date, fmt)
  1215. except:
  1216. dt_from = datetime.now()
  1217. except:
  1218. return []
  1219. dt_start = dt_start.replace(day=1)
  1220. dt_end = dt_end.replace(day=1)
  1221. dt_from = dt_from.replace(day=1)
  1222. curr = max(dt_start, dt_from)
  1223. months = []
  1224. while curr <= dt_end:
  1225. months.append(curr.strftime(fmt))
  1226. if curr.month == 12:
  1227. curr = curr.replace(year=curr.year + 1, month=1)
  1228. else:
  1229. curr = curr.replace(month=curr.month + 1)
  1230. return months
  1231. # --- 资源清理核心方法 ---
  1232. def cleanup(self):
  1233. """
  1234. 销毁浏览器并彻底删除临时文件
  1235. """
  1236. # 1. 关闭浏览器
  1237. if self.page:
  1238. try:
  1239. self.page.quit() # 这会关闭 Chrome 进程
  1240. except Exception:
  1241. pass # 忽略已关闭的错误
  1242. self.page = None
  1243. # 2. 删除文件
  1244. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  1245. if os.path.exists(self.root_workspace):
  1246. for _ in range(3):
  1247. try:
  1248. time.sleep(0.2)
  1249. shutil.rmtree(self.root_workspace, ignore_errors=True)
  1250. break
  1251. except Exception as e:
  1252. # 如果删除失败(通常是Windows文件占用),重试
  1253. if self.logger: self.logger(f"Cleanup retry: {e}")
  1254. time.sleep(0.5)
  1255. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  1256. if os.path.exists(self.root_workspace) and self.logger:
  1257. self.logger(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  1258. def __del__(self):
  1259. """
  1260. 析构函数:当对象被垃圾回收时自动调用
  1261. """
  1262. self.cleanup()