vfs_plugin.py 59 KB

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