vfs_plugin.py 53 KB

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