vfs_plugin.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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 _check_page_blocked(self, stage: str = "login page"):
  175. """
  176. 检查当前页面是否出现 403 / Cloudflare WAF / VFS 403201 等 IP 拦截。
  177. 如果页面直接返回 {"code": "403201"} 或提示 403/Block,立即抛出 PermissionDeniedError 快速失败,触发上层销毁实例并轮换代理。
  178. """
  179. if not self.page:
  180. return
  181. try:
  182. # 1. 检查页面是否直接返回了 JSON 拦截对象 (如 {"code": "403201", "description": ""})
  183. page_json = getattr(self.page, "json", None)
  184. if isinstance(page_json, dict):
  185. code = str(page_json.get("code", "")).strip()
  186. if code in ("403201", "403202") or "40320" in code:
  187. self._log(f"🛡️ [IP Blocked] VFS {stage} returned JSON block code '{code}': {page_json}")
  188. raise PermissionDeniedError(f"IP Blocked (VFS {code}): {page_json}")
  189. # 2. 检查页面正文是否为 JSON 格式的拦截响应
  190. body_text = ""
  191. try:
  192. body_el = self.page.ele("tag:body")
  193. if body_el:
  194. body_text = (body_el.text or "").strip()
  195. except Exception:
  196. pass
  197. if body_text and body_text.startswith("{") and body_text.endswith("}"):
  198. try:
  199. data = json.loads(body_text)
  200. if isinstance(data, dict):
  201. code = str(data.get("code", "")).strip()
  202. if code in ("403201", "403202") or "40320" in code:
  203. self._log(f"🛡️ [IP Blocked] VFS {stage} body JSON block '{code}': {body_text}")
  204. raise PermissionDeniedError(f"IP Blocked (VFS {code}): {body_text}")
  205. except Exception:
  206. pass
  207. # 3. 检查响应状态码(若支持)
  208. resp = getattr(self.page, "response", None)
  209. if resp and getattr(resp, "status_code", None) == 403:
  210. self._log(f"🛡️ [IP Blocked] HTTP 403 response detected on {stage}.")
  211. raise PermissionDeniedError(f"HTTP 403 Forbidden: Blocked on {stage}")
  212. # 4. 检查页面 Title
  213. title = (self.page.title or "").strip()
  214. title_lower = title.lower()
  215. if "403" in title_lower or "forbidden" in title_lower or "access denied" in title_lower:
  216. self._log(f"🛡️ [IP Blocked] 403 / Access Denied detected in title '{title}' on {stage}.")
  217. raise PermissionDeniedError(f"403 Forbidden detected in page title: '{title}'")
  218. # 5. 检查页面 HTML / 文本特征
  219. html = (getattr(self.page, "html", "") or "").lower()
  220. raw_html = (getattr(self.page, "raw_html", "") or "").lower()
  221. combined_html = f"{html} {raw_html}"
  222. block_signatures = [
  223. "403201",
  224. "403202",
  225. "\"code\": \"403201\"",
  226. "\"code\":\"403201\"",
  227. "\"code\": \"403202\"",
  228. "\"code\":\"403202\"",
  229. "sorry, you have been blocked",
  230. "403 forbidden",
  231. "you are unable to access vfsglobal.com",
  232. "has banned your ip address",
  233. "the owner of this website has banned your ip address",
  234. "error code 1020",
  235. "error code 1015",
  236. "error 403",
  237. ]
  238. for sig in block_signatures:
  239. if sig in combined_html or (body_text and sig in body_text.lower()):
  240. self._log(f"🛡️ [IP Blocked] Block signature '{sig}' detected on {stage}.")
  241. raise PermissionDeniedError(f"IP Blocked: VFS returned '{sig}' on {stage}")
  242. # 6. 检查 Cloudflare 拦截综合特征
  243. if ("attention required" in title_lower or "cloudflare" in title_lower) and ("blocked" in combined_html or "access denied" in combined_html):
  244. self._log(f"🛡️ [IP Blocked] Cloudflare attention/block page detected on {stage}.")
  245. raise PermissionDeniedError(f"403 Forbidden: Blocked by Cloudflare WAF on {stage}")
  246. except PermissionDeniedError:
  247. raise
  248. except Exception:
  249. pass
  250. def _prepare_clean_page(self):
  251. """进入极轻量 404 页面并注入独占 Turnstile 容器 (绕过复杂首页)"""
  252. if self.injected:
  253. self._log("Resetting existing Turnstile widget...")
  254. self.page.run_js("""
  255. window.cf_token = null;
  256. var st = document.getElementById('status');
  257. if(st) { st.innerText = 'Resetting verification...'; st.style.color = '#666'; }
  258. try {
  259. if (window.turnstile) {
  260. if (window.my_widget_id !== undefined) {
  261. window.turnstile.reset(window.my_widget_id);
  262. } else {
  263. window.turnstile.reset();
  264. }
  265. }
  266. } catch(e) {}
  267. """)
  268. return
  269. # 1. 先打开 login 建立会话上下文与 Cloudflare 信任凭证
  270. mission = self.free_config.get("mission_code", "")
  271. country = self.free_config.get("country_code", "")
  272. lang = self.free_config.get("language", "en")
  273. if country and mission:
  274. login_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
  275. else:
  276. login_url = "https://visa.vfsglobal.com/irl/en/dnk/login"
  277. self._log(f"Establishing session context via login portal: {login_url}")
  278. self.page.set.timeouts(page_load=30, script=20)
  279. try:
  280. self.page.get(login_url)
  281. time.sleep(3)
  282. # 打开 login 页面如果提示 403 / Block,立即抛出异常快速失败,无需继续
  283. self._check_page_blocked("login portal")
  284. # 处理 Cloudflare 等待室
  285. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else True)
  286. cf_bypasser.handle_waiting_room()
  287. # 再次确认等待室后是否被拦截
  288. self._check_page_blocked("login portal after waiting room")
  289. # 处理 OneTrust Cookie 弹窗
  290. cookie_btn = self.page.ele('#onetrust-accept-btn-handler', timeout=3)
  291. if cookie_btn and cookie_btn.states.is_displayed:
  292. cookie_btn.click()
  293. self._log("Accepted OneTrust cookie consent.")
  294. time.sleep(0.5)
  295. except PermissionDeniedError:
  296. raise
  297. except Exception as e:
  298. self._log(f"Handling login portal context warning: {e}")
  299. # 再次确认是否被拦截
  300. self._check_page_blocked("login portal final")
  301. # 强力清除任何可能阻挡交互的遮罩层
  302. try:
  303. self.page.run_js("""
  304. var ot = document.getElementById('onetrust-consent-sdk');
  305. if (ot) ot.remove();
  306. var ov = document.querySelector('.onetrust-pc-dark-filter');
  307. if (ov) ov.remove();
  308. """)
  309. except Exception:
  310. pass
  311. # 2. 建立上下文后,进入轻量页面准备注入 Turnstile
  312. self._log(f"Loading lightweight origin endpoint: {VFS_CLEAN_ENTRY_URL}")
  313. self.page.set.timeouts(page_load=15, script=15)
  314. self.page.get(VFS_CLEAN_ENTRY_URL)
  315. time.sleep(1)
  316. self._log("Injecting standalone Cloudflare Turnstile into empty page...")
  317. inject_js = f"""
  318. if (!document.body) {{
  319. var b = document.createElement('body');
  320. if (document.documentElement) {{
  321. document.documentElement.appendChild(b);
  322. }} else {{
  323. document.appendChild(b);
  324. }}
  325. }}
  326. document.body.innerHTML = `
  327. <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;">
  328. <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;">
  329. <h2 style="margin:0 0 10px 0;color:#1e293b;font-size:20px;">VFS Pure Turnstile</h2>
  330. <p style="margin:0 0 25px 0;color:#64748b;font-size:13px;">Domain Origin: visa.vfsglobal.com</p>
  331. <div id="my-turnstile" style="display:flex;justify-content:center;margin-bottom:20px;"></div>
  332. <div id="status" style="font-size:14px;font-weight:500;color:#64748b;">Initializing Turnstile...</div>
  333. </div>
  334. </div>
  335. `;
  336. window.cf_token = null;
  337. window.my_widget_id = undefined;
  338. function initTurnstile() {{
  339. try {{
  340. window.my_widget_id = window.turnstile.render('#my-turnstile', {{
  341. sitekey: '{self.sitekey}',
  342. callback: function(token) {{
  343. window.cf_token = token;
  344. var st = document.getElementById('status');
  345. if (st) {{
  346. st.innerText = '✅ Verified! Token obtained.';
  347. st.style.color = '#16a34a';
  348. }}
  349. }},
  350. 'error-callback': function() {{
  351. var st = document.getElementById('status');
  352. if (st) {{
  353. st.innerText = '❌ Verification failed. Retrying...';
  354. st.style.color = '#dc2626';
  355. }}
  356. }}
  357. }});
  358. var st = document.getElementById('status');
  359. if (st) st.innerText = 'Please complete verification...';
  360. }} catch(e) {{
  361. console.error("Render error:", e);
  362. }}
  363. }}
  364. if (window.turnstile) {{
  365. initTurnstile();
  366. }} else {{
  367. var script = document.createElement('script');
  368. script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
  369. script.onload = initTurnstile;
  370. document.head.appendChild(script);
  371. }}
  372. """
  373. self.page.run_js(inject_js)
  374. self.injected = True
  375. self._log("Turnstile injected successfully.")
  376. def _get_turnstile_token(self, timeout_sec: int = 60) -> Optional[str]:
  377. """等待或自动点击 Turnstile 获取 token"""
  378. self._log("Waiting for Turnstile verification...")
  379. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else True)
  380. start_t = time.time()
  381. last_click_t = 0.0
  382. while time.time() - start_t < timeout_sec:
  383. try:
  384. js_check = """
  385. if (window.cf_token) return window.cf_token;
  386. var el = document.querySelector('input[name="cf-turnstile-response"]');
  387. if (el && el.value) return el.value;
  388. return null;
  389. """
  390. token = self.page.run_js(js_check)
  391. if token:
  392. self._log("✅ Turnstile token acquired!")
  393. return token
  394. except Exception:
  395. pass
  396. try:
  397. ele = self.page.ele('@name=cf-turnstile-response', timeout=0.1)
  398. if ele and ele.value:
  399. self._log("✅ Turnstile token acquired from input tag!")
  400. return ele.value
  401. except Exception:
  402. pass
  403. # 尝试点击验证复选框 (点击后至少保持 6 秒冷静期避免打断正在计算的验证)
  404. now = time.time()
  405. if now - start_t > 3 and now - last_click_t > 6:
  406. try:
  407. res = cf_bypasser.click_verification_button(is_dfs=False)
  408. if res:
  409. last_click_t = now
  410. except Exception:
  411. pass
  412. time.sleep(0.8)
  413. return None
  414. @property
  415. def bypass_landing_page(self) -> bool:
  416. """是否绕过首页加载(默认 True,兼容 bypass_landing_page 与 bypass_loading_page 配置)"""
  417. if "bypass_landing_page" in self.free_config:
  418. return bool(self.free_config.get("bypass_landing_page"))
  419. if "bypass_loading_page" in self.free_config:
  420. return bool(self.free_config.get("bypass_loading_page"))
  421. return True
  422. def create_session(self) -> None:
  423. """
  424. 使用 DrissionPage 创建会话:
  425. 1. 启动浏览器
  426. 2. 根据 bypass_landing_page 开关选择建立登录会话上下文并进入轻量页面或官方登录首页
  427. 3. 提取 Turnstile Token
  428. 4. JS fetch 登录
  429. """
  430. co, self.tunnel = init_chromium_options(
  431. user_data_path=self.user_data_path,
  432. username_seed=self.config.account.username if self.config and self.config.account else None,
  433. proxy=self.config.proxy if self.config else None,
  434. headless=False,
  435. window_size="1920,1080",
  436. logger=self._log
  437. )
  438. self.page = ChromiumPage(co)
  439. self.page.set.timeouts(15)
  440. mission = self.free_config.get("mission_code", "")
  441. country = self.free_config.get("country_code", "")
  442. if not mission or not country:
  443. raise BizLogicError("Missing mission/country code config")
  444. if self.bypass_landing_page:
  445. self._log("Using bypass landing mode: opening login to establish context, then jumping to bypass landing page...")
  446. # 1. 建立登录上下文并跳转至极轻量页面注入独占 Turnstile 容器
  447. self._prepare_clean_page()
  448. # 2. 获取 Turnstile Token
  449. cf_token = self._get_turnstile_token(timeout_sec=60)
  450. else:
  451. lang = self.free_config.get("language", "en")
  452. login_page_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
  453. self._log(f"Using traditional landing page mode. Navigating to {login_page_url}...")
  454. self.page.get(login_page_url)
  455. time.sleep(3)
  456. # 打开 login 页面如果提示 403 / Block,立即抛出异常快速失败,无需继续
  457. self._check_page_blocked("login page")
  458. self._log("Handling Cloudflare challenge...")
  459. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else True)
  460. cf_bypasser.handle_waiting_room()
  461. time.sleep(random.uniform(2, 3))
  462. # 再次确认挑战后是否被拦截
  463. self._check_page_blocked("login page after challenge")
  464. cf_token = self._extract_turnstile_token_from_landing_page(timeout_sec=40, reset_first=False)
  465. if not cf_token:
  466. self._log("[WARN] Could not extract Turnstile token.")
  467. raise PermissionDeniedError("Could not extract Turnstile token (Cloudflare challenge failed).")
  468. email = self.config.account.username
  469. password = self.config.account.password
  470. enc_password = self._encrypt_password(password)
  471. client_src = self._get_client_source()
  472. orange_src = self._get_orange_source(email)
  473. url = f"https://{self.vfs_api_domain}/user/login"
  474. headers = self._get_common_headers(with_auth=False)
  475. headers.update({
  476. "clientsource": client_src,
  477. "orangex": orange_src
  478. })
  479. data = {
  480. "username": email,
  481. "password": enc_password,
  482. "missioncode": mission,
  483. "countrycode": country,
  484. "languageCode": "en-US",
  485. "captcha_version": "cloudflare-v1",
  486. "captcha_api_key": cf_token
  487. }
  488. now_utc = datetime.utcnow()
  489. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  490. self._log("Sending Login Request via Browser Fetch...")
  491. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  492. resp_json = resp.json()
  493. if resp_json.get('accessToken'):
  494. self.jwt_token = resp_json["accessToken"]
  495. self._log("Login successful, JWT obtained.")
  496. elif resp_json.get("enableOTPAuthentication"):
  497. self._log("Login requires OTP.")
  498. otp = self._read_otp_email(sent_at=sent_at)
  499. self._submit_login_otp(cf_token, otp)
  500. else:
  501. raise BizLogicError(f"Login failed: {resp.text[:200]}")
  502. self.session_create_time = time.time()
  503. try:
  504. self.real_ip = self._get_realnetwork_ip()
  505. except:
  506. self.real_ip = self.config.proxy.ip
  507. def query(self, apt_type: AppointmentType) -> QueryResult:
  508. """查询可预约 Slot"""
  509. result = QueryResult()
  510. apt_config = self.free_config.get("apt_configs", {}).get(apt_type.routing_key)
  511. self._fetch_configurations(apt_config)
  512. query_result = self._query_earliest_slot(apt_config)
  513. result.success = False
  514. result.availability_status = AvailabilityStatus.NoneAvailable
  515. if query_result:
  516. result.success = True
  517. if "WaitList" in query_result:
  518. result.availability_status = AvailabilityStatus.Waitlist
  519. else:
  520. earliest_dt = datetime.strptime(query_result, "%Y-%m-%d")
  521. result.availability_status = AvailabilityStatus.Available
  522. result.earliest_date = earliest_dt
  523. result.availability = [DateAvailability(date=earliest_dt, times=[])]
  524. self._log(f"Slot Found! -> {query_result}")
  525. else:
  526. self._log("No slots available.")
  527. return result
  528. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
  529. """
  530. 核心方法:在 DrissionPage 浏览器上下文中注入 JS 执行 fetch
  531. 并记录详细的 Traffic 日志用于分析
  532. """
  533. if not self.page:
  534. raise BizLogicError("Browser session not initialized")
  535. if self.config.debug:
  536. self._log(f"┌── [TRAFFIC REQUEST] {method} {url}")
  537. self._log(f"├── Headers: {json.dumps(headers or {})}")
  538. self._log(f"└── Body: {json_data if json_data is not None else data}")
  539. else:
  540. self._log(f"[TRAFFIC REQUEST] {method} {url}")
  541. try:
  542. resp = perform_browser_fetch(
  543. self.page,
  544. method=method,
  545. url=url,
  546. headers=headers,
  547. data=data,
  548. json_data=json_data,
  549. params=params,
  550. timeout=60
  551. )
  552. except Exception as e:
  553. self._log(f"[TRAFFIC ERROR] JS Execution failed: {e}")
  554. raise BizLogicError(f"Browser JS Execution Error: {e}")
  555. resp_preview = resp.text[:1000] + "..." if len(resp.text) > 1000 else resp.text
  556. if self.config.debug:
  557. self._log(f"┌── [TRAFFIC RESPONSE] Status: {resp.status_code}")
  558. self._log(f"└── Body: {resp_preview}")
  559. else:
  560. self._log(f"[TRAFFIC RESPONSE] {method} {url} -> Status: {resp.status_code}")
  561. if resp.status_code == 200:
  562. return resp
  563. elif resp.status_code == 401:
  564. self.is_healthy = False
  565. raise SessionExpiredOrInvalidError(f"401 Unauthorized: {resp.text[:100]}")
  566. elif resp.status_code == 403:
  567. if "Just a moment" in resp.text or "cloudflare" in resp.text.lower():
  568. self._log(f"[TRAFFIC] HTTP 403 (Cloudflare) detected. Re-verifying (Try {retry_count+1}/3)...")
  569. if retry_count < 3 and method.upper() in ('GET', 'HEAD'):
  570. new_token = self._refresh_turnstile_token()
  571. if new_token:
  572. self._log("[TRAFFIC] In-page verification success. Retrying...")
  573. if json_data and "captcha_api_key" in json_data:
  574. json_data["captcha_api_key"] = new_token
  575. return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
  576. raise PermissionDeniedError(f"HTTP 403 Forbidden: {resp.text[:100]}")
  577. elif resp.status_code == 429:
  578. self.is_healthy = False
  579. raise RateLimiteddError(f"429 Rate Limit: {resp.text[:100]}")
  580. elif resp.status_code == 0:
  581. raise PermissionDeniedError(f"Network Error (Fetch Failed / WAF Blocked): {resp.text}")
  582. else:
  583. if url.endswith("/login") and resp.status_code == 400:
  584. return resp
  585. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  586. def _get_realnetwork_ip(self):
  587. """
  588. 通过新建标签页获取 IP
  589. 解决 CORS 403 问题:新标签页请求属于 Top-Level Navigation,
  590. 不带 Origin: visa.vfsglobal.com,也不带 credentials,符合 ipify 规则。
  591. """
  592. try:
  593. tab = self.page.new_tab("https://api.ipify.org/?format=json")
  594. if tab.ele('tag:pre'):
  595. json_text = tab.ele('tag:pre').text
  596. else:
  597. json_text = tab.ele('tag:body').text
  598. ip = json.loads(json_text)['ip']
  599. tab.close()
  600. self._log(f"Real Network IP: {ip}")
  601. return ip
  602. except Exception as e:
  603. self._log(f"[WARN] Failed to check IP via new tab: {e}")
  604. try:
  605. if self.page.tabs_count > 1:
  606. tab.close()
  607. except:
  608. pass
  609. return "0.0.0.0"
  610. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  611. # DrissionPage 浏览器会自动带上 Origin, Referer, User-Agent, Sec-CH-UA 等,这里只需要补充业务特定的 Headers
  612. mission = self.free_config.get("mission_code", "")
  613. country = self.free_config.get("country_code", "")
  614. lang = self.free_config.get("language", "en")
  615. route = f"{country}/{lang}/{mission}"
  616. h = {
  617. "accept": "application/json, text/plain, */*",
  618. "route": route
  619. }
  620. h["clientsource"] = self._get_client_source()
  621. if with_auth and self.jwt_token:
  622. h["authorize"] = self.jwt_token
  623. return h
  624. def _encrypt_password(self, password: str) -> str:
  625. ciphertext = self.public_key.encrypt(
  626. password.encode(),
  627. padding.OAEP(
  628. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  629. algorithm=hashes.SHA256(),
  630. label=None
  631. )
  632. )
  633. return base64.b64encode(ciphertext).decode()
  634. def _get_orange_source(self, email: str) -> str:
  635. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  636. payload = f"{email};{timestamp}"
  637. return self._encrypt_password(payload)
  638. def _get_client_source(self) -> str:
  639. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  640. payload = f"GA;{timestamp}Z"
  641. return self._encrypt_password(payload)
  642. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  643. url = f"https://{self.vfs_api_domain}/appointment/CheckIsSlotAvailable"
  644. data = {
  645. "missioncode": self.free_config.get("mission_code"),
  646. "countrycode": self.free_config.get("country_code"),
  647. "vacCode": apt_config.get("vac_code"),
  648. "visaCategoryCode": apt_config.get("subcategory_code"),
  649. "roleName": "Individual",
  650. "loginUser": self.config.account.username,
  651. "payCode": ""
  652. }
  653. headers = self._get_common_headers(with_auth=True)
  654. resp = self._perform_request("POST", url, headers=headers, json_data=data, retry_count=2)
  655. if "WaitList" in resp.text:
  656. return "WaitList"
  657. j = resp.json()
  658. if j.get("earliestSlotLists"):
  659. raw_date = j["earliestSlotLists"][0]["date"]
  660. return to_yyyymmdd(raw_date, "%m/%d/%Y %H:%M:%S")
  661. return ""
  662. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  663. if not self.center_conf:
  664. self.center_conf = self._query_center()
  665. vac_code = apt_config.get("vac_code")
  666. category_code = apt_config.get("category_code")
  667. if category_code not in self.category_conf:
  668. visa_categories = self._query_visa_category(vac_code)
  669. found = False
  670. for vc in visa_categories:
  671. if vc.get("code") == category_code:
  672. self.category_conf[category_code] = vc
  673. found = True
  674. break
  675. if not found:
  676. self._log(f"WARN: Category {category_code} not found")
  677. sub_category_code = apt_config.get("subcategory_code")
  678. if sub_category_code not in self.subcategory_conf:
  679. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  680. found = False
  681. for svc in visa_subcategories:
  682. if svc.get("code") == sub_category_code:
  683. self.subcategory_conf[sub_category_code] = svc
  684. found = True
  685. break
  686. if not found:
  687. self._log(f"WARN: SubCategory {sub_category_code} not found")
  688. def _query_center(self) -> List:
  689. mission = self.free_config.get("mission_code")
  690. country = self.free_config.get("country_code")
  691. url = f"https://{self.vfs_api_domain}/master/center/{mission}/{country}/en-US"
  692. headers = self._get_common_headers(with_auth=False)
  693. resp = self._perform_request("GET", url, headers=headers)
  694. return resp.json()
  695. def _query_visa_category(self, center_code: str) -> List:
  696. mission = self.free_config.get("mission_code")
  697. country = self.free_config.get("country_code")
  698. enc_center = urllib.parse.quote(center_code)
  699. url = f"https://{self.vfs_api_domain}/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  700. headers = self._get_common_headers(with_auth=False)
  701. resp = self._perform_request("GET", url, headers=headers)
  702. return resp.json()
  703. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  704. mission = self.free_config.get("mission_code")
  705. country = self.free_config.get("country_code")
  706. enc_center = urllib.parse.quote(center_code)
  707. enc_cat = urllib.parse.quote(category_code)
  708. url = f"https://{self.vfs_api_domain}/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  709. headers = self._get_common_headers(with_auth=False)
  710. resp = self._perform_request("GET", url, headers=headers)
  711. return resp.json()
  712. def _read_otp_email(self, sent_at='', sender='VFS Global') -> str:
  713. # 保持原样,这部分使用云API读取邮件,不依赖本地网络库
  714. master_email = "hujiarui8@gmail.com"
  715. recipient = self.config.account.username
  716. subject_keywords = "One Time Password"
  717. body_keywords = "OTP"
  718. if not sent_at:
  719. now_utc = datetime.utcnow()
  720. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  721. self._log(f"Waiting for OTP email...")
  722. content_out = CloudApi.Instance().fetch_mail_content(
  723. master_email, sender, recipient, subject_keywords, body_keywords, sent_at, 300, only_text=False
  724. )
  725. if content_out:
  726. parts = content_out.split("\n")
  727. text_parts = [p for p in parts if not p.startswith("data:image")]
  728. email_text = " ".join(text_parts)
  729. image_urls = [p for p in parts if p.startswith("data:image")]
  730. match = re.search(r'\b\d{6}\b', email_text)
  731. if match:
  732. self._log("Found OTP from email text via Regex.")
  733. return match.group(0)
  734. if image_urls:
  735. self._log("OTP not found in text, trying LLM image recognition...")
  736. target_image_b64 = image_urls[0]
  737. vfs_otp_prompt = "图片中有多组验证码,其中OTP箭头指向的验证码为真,其余为假。只输出真实验证码的内容,不要任何多余的汉字或标点符号。"
  738. try:
  739. otp_code = self.captcha_breaker.break_captcha(target_image_b64, prompt=vfs_otp_prompt)
  740. if otp_code:
  741. self._log(f"Successfully extracted OTP from image: {otp_code}")
  742. return otp_code
  743. except CaptchaBreakerError as e:
  744. self._log(f"LLM OTP extraction failed: {e}")
  745. raise BizLogicError(message="OTP code not found")
  746. def _submit_login_otp(self, old_cf_token: str, otp: str):
  747. self._log("Submitting Login OTP...")
  748. new_cf_token = self._refresh_turnstile_token()
  749. email = self.config.account.username
  750. password = self.config.account.password
  751. enc_password = self._encrypt_password(password)
  752. mission = self.free_config.get("mission_code", "")
  753. country = self.free_config.get("country_code", "")
  754. client_src = self._get_client_source()
  755. orange_src = self._get_orange_source(email)
  756. url = f"https://{self.vfs_api_domain}/user/login"
  757. headers = self._get_common_headers(with_auth=False)
  758. headers.update({
  759. "clientsource": client_src,
  760. "orangex": orange_src
  761. })
  762. data = {
  763. "username": email,
  764. "password": enc_password,
  765. "missioncode": mission,
  766. "countrycode": country,
  767. "languageCode": "en-US",
  768. "captcha_version": "cloudflare-v1",
  769. "captcha_api_key": new_cf_token,
  770. "otp": otp
  771. }
  772. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  773. resp_json = resp.json()
  774. if resp_json.get("accessToken"):
  775. self.jwt_token = resp_json["accessToken"]
  776. self._log("OTP Login successful.")
  777. return
  778. error_desc = resp_json.get("description", resp.text)
  779. raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
  780. def _extract_turnstile_token_from_landing_page(self, timeout_sec: int = 40, reset_first: bool = False) -> str:
  781. """
  782. [旧方式] 从官方页面中提取或重置刷新 Cloudflare Turnstile Token
  783. """
  784. if reset_first:
  785. self._log("Resetting Cloudflare Turnstile in landing page...")
  786. js_reset = """
  787. try {
  788. var input = document.querySelector('input[name="cf-turnstile-response"]');
  789. if (input) input.value = "";
  790. if (window.turnstile && window.turnstile.reset) {
  791. window.turnstile.reset();
  792. }
  793. } catch(e) {}
  794. """
  795. self.page.run_js(js_reset)
  796. cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else True)
  797. total_cycles = int(timeout_sec * 2)
  798. for i in range(total_cycles):
  799. time.sleep(0.5)
  800. handle_cookie_consent(self.page, logger=self._log)
  801. try:
  802. ele = self.page.ele('@name=cf-turnstile-response', timeout=0.5)
  803. if ele and ele.value:
  804. self._log("Cloudflare Turnstile token extracted successfully.")
  805. return ele.value
  806. except Exception:
  807. pass
  808. if i > 4:
  809. try:
  810. cf_bypasser.click_verification_button(is_dfs=False)
  811. except Exception:
  812. pass
  813. return ""
  814. def _extract_turnstile_token(self, timeout_sec: int = 40, reset_first: bool = False) -> str:
  815. """
  816. 统一提取或重置刷新 Cloudflare Turnstile Token(根据 bypass_landing_page 开关自动路由)
  817. """
  818. if self.bypass_landing_page:
  819. if reset_first or not self.injected:
  820. self._prepare_clean_page()
  821. token = self._get_turnstile_token(timeout_sec=timeout_sec)
  822. return token or ""
  823. else:
  824. return self._extract_turnstile_token_from_landing_page(timeout_sec=timeout_sec, reset_first=reset_first)
  825. def _refresh_turnstile_token(self) -> str:
  826. """
  827. 强制刷新 Cloudflare Turnstile 并获取新 Token
  828. """
  829. self._log("Refreshing Cloudflare Turnstile token...")
  830. token = self._extract_turnstile_token(timeout_sec=30, reset_first=True)
  831. if not token:
  832. raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
  833. return token
  834. def book(self, slot_info: QueryResult, user_inputs) -> BookResult:
  835. """
  836. 执行完整的预约流程
  837. """
  838. self._log("Starting booking process...")
  839. user_email = user_inputs.get('email')
  840. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="text.skin")
  841. res = BookResult()
  842. app_type = slot_info.apt_type
  843. from_date = slot_info.earliest_date.strftime("%Y-%m-%d") if slot_info.earliest_date else datetime.now().strftime("%Y-%m-%d")
  844. expected_start = user_inputs.get("expected_start_date", "2000-01-01")
  845. expected_end = user_inputs.get("expected_end_date") or ''
  846. if expected_end and from_date > expected_end:
  847. self._log("No valid slots in date preference.")
  848. res.success = False
  849. return res
  850. apt_config = self.free_config.get("apt_configs", {}).get(app_type.routing_key)
  851. if not apt_config:
  852. raise NotFoundError(message="Book: Config missing for this routing key.")
  853. self._fetch_configurations(apt_config)
  854. sub_cc = apt_config.get("subcategory_code")
  855. sub_conf = self.subcategory_conf.get(sub_cc, {})
  856. ocr_enabled = sub_conf.get("isOCREnable", False)
  857. if ocr_enabled:
  858. self._log("OCR Enabled, uploading documents...")
  859. upload_res = self._upload_applicant_documents(apt_config, user_inputs)
  860. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  861. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes")
  862. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  863. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  864. final_urn = None
  865. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  866. if not self.booking_wait_applied:
  867. self._log("pre-booking wait: sleeping 20s before booking to avoid risk control")
  868. time.sleep(20)
  869. self.booking_wait_applied = True
  870. MAX_RETRY = 2
  871. for i in range(MAX_RETRY):
  872. try:
  873. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  874. break
  875. except BizLogicError as e:
  876. err_msg = str(e)
  877. self._log(f"Add Applicant retry {i+1}/{MAX_RETRY}: {err_msg}")
  878. if 'Capping has exceeded' in err_msg:
  879. raise e
  880. time.sleep(10.0)
  881. if not final_urn:
  882. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken or API error)")
  883. self._log(f"Applicant Added. URN: {final_urn}")
  884. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  885. if otp_enabled:
  886. self._log("Applicant OTP Required.")
  887. now_utc = datetime.utcnow()
  888. sent_at = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  889. if not self._applicant_otp_send(apt_config, final_urn):
  890. raise BizLogicError(message='Applicant OTP send failed')
  891. otp_code = self._read_otp_email(sent_at=sent_at)
  892. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  893. raise BizLogicError(message='Applicant OTP verify failed')
  894. if is_waitlist:
  895. if self._confirm_waitlist(apt_config, final_urn):
  896. res.success = True
  897. res.urn = final_urn
  898. res.account = self.config.account.username
  899. self._log("Waitlist confirmed.")
  900. return res
  901. raise BizLogicError(message='Confirm waitlist failed')
  902. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  903. self._log(f"Scanning months: {months} (Start looking from: {from_date})")
  904. selected_slot_id = ""
  905. selected_slot_date = ""
  906. selected_slot_time_range = ""
  907. all_ads = set()
  908. forbidden_dates = set()
  909. found_slot = False
  910. for m_str in months:
  911. self._log(f"Checking calendar for {m_str}...")
  912. ads = self._query_slot_calendar(apt_config, final_urn, m_str)
  913. new_ads = [d for d in ads if d not in all_ads]
  914. all_ads.update(new_ads)
  915. for _ in range(3):
  916. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  917. sel_dates = filter_dates_in_range(avail_candidates, expected_start, expected_end, shuffle=True)
  918. if not sel_dates:
  919. break
  920. tmp_date = sel_dates[0]
  921. forbidden_dates.add(tmp_date)
  922. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  923. self._log(f"Audit failed for {tmp_date}, skipping...")
  924. time.sleep(1)
  925. continue
  926. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  927. if not ats:
  928. self._log(f"No timeslots for {tmp_date}")
  929. continue
  930. sel_tm = random.choice(ats)
  931. selected_slot_id = sel_tm.get("allocationId")
  932. selected_slot_date = tmp_date
  933. selected_slot_time_range = sel_tm.get("slot")
  934. found_slot = True
  935. break
  936. if found_slot:
  937. break
  938. if not found_slot:
  939. self._log("No valid slots found after scanning.")
  940. res.success = False
  941. return res
  942. self._log(f"Slot Selected: {selected_slot_date} {selected_slot_time_range} (ID: {selected_slot_id})")
  943. self._submit_no_addition_service(final_urn)
  944. amount, currency = self._query_fee(apt_config, final_urn)
  945. self._log("Submitting schedule...")
  946. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  947. if not schedule_res.get("IsAppointmentBooked"):
  948. self._log(f"Booking failed: {schedule_res}")
  949. res.success = False
  950. return res
  951. res.success = True
  952. res.account = self.config.account.username
  953. res.book_date = selected_slot_date
  954. res.book_time = selected_slot_time_range
  955. res.urn = final_urn
  956. lowered_schedule = {str(k).lower(): v for k, v in schedule_res.items()} if isinstance(schedule_res, dict) else {}
  957. if lowered_schedule.get("ispaymentrequired", False):
  958. self._log("Processing payment link...")
  959. try:
  960. payment_url = self._pay_request(schedule_res)
  961. except Exception as exc:
  962. self._log(f'Booking confirmed; payment URL recovery needed: {exc}')
  963. payment_url = ''
  964. if payment_url:
  965. res.payment_link = payment_url
  966. return res
  967. def _get_application(self):
  968. url = f"https://{self.vfs_api_domain}/appointment/application"
  969. headers = self._get_common_headers(with_auth=True)
  970. data = {
  971. 'countryCode': self.free_config.get("country_code"),
  972. 'missionCode': self.free_config.get("mission_code"),
  973. 'loginUser': self.config.account.username,
  974. 'languageCode': 'en-US',
  975. }
  976. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  977. return resp.json()
  978. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  979. """上传图片:根据前缀判断是下载外部图片还是读取本地文件,并上传到 VFS"""
  980. import requests as standard_requests
  981. url = f"https://{self.vfs_api_domain}/appointment/UploadApplicantDocument"
  982. passport_path_or_url = user_inputs.get("passport_image_url")
  983. if not passport_path_or_url:
  984. raise NotFoundError(message="Missing passport_image_url")
  985. if passport_path_or_url.startswith("http://") or passport_path_or_url.startswith("https://"):
  986. img_resp = standard_requests.get(passport_path_or_url, timeout=30)
  987. if img_resp.status_code != 200:
  988. raise BizLogicError(message=f"Failed to download passport image: {img_resp.status_code}")
  989. img_data = img_resp.content
  990. else:
  991. if not os.path.exists(passport_path_or_url):
  992. raise BizLogicError(message=f"Local passport image file not found: {passport_path_or_url}")
  993. with open(passport_path_or_url, "rb") as f:
  994. img_data = f.read()
  995. b64_str = base64.b64encode(img_data).decode('utf-8')
  996. headers = self._get_common_headers(with_auth=True)
  997. data = {
  998. "missioncode": self.free_config.get("mission_code"),
  999. "countryCode": self.free_config.get("country_code"),
  1000. "centerCode": apt_config.get("vac_code"),
  1001. "loginUser": self.config.account.username,
  1002. "languageCode": "en-US",
  1003. "visaCategoryCode": apt_config.get("subcategory_code"),
  1004. "fileBytes": b64_str,
  1005. "selfiImageFileBytes": ""
  1006. }
  1007. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1008. result = resp.json()
  1009. result["passportImageFilename"] = "passport_img.jpg"
  1010. result["passportImageFileBytes"] = b64_str
  1011. return result
  1012. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  1013. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  1014. """构造申请人 payload 并提交"""
  1015. url = f"https://{self.vfs_api_domain}/appointment/applicants"
  1016. headers = self._get_common_headers(with_auth=True)
  1017. gender_str = str(user_inputs.get("gender", "")).lower()
  1018. gender_code = 1 if gender_str == "male" else 2
  1019. raw_dial = user_inputs.get("phone_country_code", "86")
  1020. dial_code = str(raw_dial)
  1021. # 日期格式转换 YYYY-MM-DD -> DD/MM/YYYY
  1022. def _to_ddmmyyyy(d_str):
  1023. try:
  1024. return datetime.strptime(str(d_str), "%Y-%m-%d").strftime("%d/%m/%Y")
  1025. except:
  1026. return str(d_str)
  1027. dob = _to_ddmmyyyy(user_inputs.get("birthday", ""))
  1028. ppt_exp = _to_ddmmyyyy(user_inputs.get("passport_expiry_date", ""))
  1029. applicant = {
  1030. "urn": "",
  1031. "arn": "",
  1032. "loginUser": self.config.account.username,
  1033. "firstName": str(user_inputs.get("first_name", "")).strip().upper(),
  1034. "middleName": "",
  1035. "lastName": str(user_inputs.get("last_name", "")).strip().upper(),
  1036. "employerFirstName": "",
  1037. "employerLastName": "",
  1038. "salutation": "",
  1039. "Subclasscode": None,
  1040. "VisaToken": None,
  1041. "centerClassCode": None,
  1042. "dateOfApplication": None,
  1043. "selectedSubvisaCategory": None,
  1044. "gender": gender_code,
  1045. "contactNumber": str(user_inputs.get("phone", "")).strip().lstrip("0"),
  1046. "dialCode": dial_code,
  1047. "employerContactNumber": "",
  1048. "employerDialCode": "",
  1049. "emailId": str(user_inputs.get("alias_email", "")).strip().upper(),
  1050. "employerEmailId": "",
  1051. "passportNumber": str(user_inputs.get("passport_no", "")).strip().upper(),
  1052. "confirmPassportNumber": "",
  1053. "passportExpirtyDate": ppt_exp,
  1054. "dateOfBirth": dob,
  1055. "nationalId": None,
  1056. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  1057. "state": user_inputs.get("state"),
  1058. "city": user_inputs.get("city"),
  1059. "addressline1": user_inputs.get("addressline1"),
  1060. "addressline2": user_inputs.get("addressline2"),
  1061. "pincode": None,
  1062. "isEndorsedChild": False,
  1063. "applicantType": 0,
  1064. "vlnNumber": None,
  1065. "applicantGroupId": 0,
  1066. "parentPassportNumber": "",
  1067. "parentPassportExpiry": "",
  1068. "dateOfDeparture": None,
  1069. "entryType": "",
  1070. "eoiVisaType": "",
  1071. "passportType": "",
  1072. "vfsReferenceNumber": "",
  1073. "familyReunificationCerificateNumber": "",
  1074. "PVRequestRefNumber": "",
  1075. "PVStatus": "",
  1076. "PVStatusDescription": "",
  1077. "PVCanAllowRetry": True,
  1078. "PVisVerified": False,
  1079. "eefRegistrationNumber": "",
  1080. "isAutoRefresh": True,
  1081. "helloVerifyNumber": "",
  1082. "OfflineCClink": "",
  1083. "idenfystatuscheck": False,
  1084. "vafStatus": None,
  1085. "SpecialAssistance": "",
  1086. "AdditionalRefNo": None,
  1087. "juridictionCode": "",
  1088. "canInitiateVAF": False,
  1089. "canEditVAF": False,
  1090. "canDeleteVAF": False,
  1091. "canDownloadVAF": False,
  1092. "Retryleft": "",
  1093. # 这里的 IP 应该已经在 create_session 时获取到了
  1094. "ipAddress": self.real_ip
  1095. }
  1096. if enable_ref:
  1097. applicant["referenceNumber"] = str(user_inputs.get("cover_letter_id", "")).strip()
  1098. else:
  1099. applicant["referenceNumber"] = None
  1100. if ocr_enabled:
  1101. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  1102. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  1103. applicant["GUID"] = str(user_inputs.get("guid", ""))
  1104. payload = {
  1105. "countryCode": self.free_config.get("country_code"),
  1106. "missionCode": self.free_config.get("mission_code"),
  1107. "centerCode": apt_config.get("vac_code"),
  1108. "loginUser": self.config.account.username,
  1109. "visaCategoryCode": apt_config.get("subcategory_code"),
  1110. "applicantList": [applicant],
  1111. "languageCode": "en-US",
  1112. "isWaitlist": is_waitlist,
  1113. "isEdit": False,
  1114. "feeEntryTypeCode": None, "feeExemptionTypeCode": None,
  1115. "feeExemptionDetailsCode": None, "juridictionCode": None, "regionCode": None
  1116. }
  1117. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  1118. urn = resp.json().get("urn")
  1119. if not urn:
  1120. err_msg = resp.json().get('error')
  1121. raise BizLogicError(message=str(err_msg))
  1122. return urn
  1123. def _applicant_otp_send(self, apt_config, urn) -> bool:
  1124. url = f"https://{self.vfs_api_domain}/appointment/applicantotp"
  1125. headers = self._get_common_headers(with_auth=True)
  1126. data = {
  1127. "urn": urn,
  1128. "loginUser": self.config.account.username,
  1129. "missionCode": self.free_config.get("mission_code"),
  1130. "countryCode": self.free_config.get("country_code"),
  1131. "centerCode": apt_config.get("vac_code"),
  1132. "OTP": "",
  1133. "otpAction": "GENERATE",
  1134. "languageCode": "en-US"
  1135. }
  1136. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1137. return resp.json().get("isOTPGenerated", False)
  1138. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  1139. url = f"https://{self.vfs_api_domain}/appointment/applicantotp"
  1140. headers = self._get_common_headers(with_auth=True)
  1141. # VFS 这里的 header 有时需要 datacenter,原代码有就加上
  1142. headers["datacenter"] = "GERMANY"
  1143. data = {
  1144. "urn": urn,
  1145. "loginUser": self.config.account.username,
  1146. "missionCode": self.free_config.get("mission_code"),
  1147. "countryCode": self.free_config.get("country_code"),
  1148. "centerCode": apt_config.get("vac_code"),
  1149. "OTP": otp,
  1150. "otpAction": "VALIDATE",
  1151. "languageCode": "en-US"
  1152. }
  1153. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1154. return resp.json().get("isOTPValidated", False)
  1155. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  1156. url = f"https://{self.vfs_api_domain}/appointment/calendar"
  1157. headers = self._get_common_headers(with_auth=True)
  1158. # 将 YYYY-MM-DD 转为 DD/MM/YYYY 用于 API
  1159. dt_m = datetime.strptime(from_date, "%Y-%m-%d")
  1160. converted_date = dt_m.strftime("%d/%m/%Y")
  1161. data = {
  1162. "missionCode": self.free_config.get("mission_code"),
  1163. "countryCode": self.free_config.get("country_code"),
  1164. "centerCode": apt_config.get("vac_code"),
  1165. "loginUser": self.config.account.username,
  1166. "visaCategoryCode": apt_config.get("subcategory_code"),
  1167. "fromDate": converted_date,
  1168. "urn": urn,
  1169. "payCode": ""
  1170. }
  1171. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1172. calendars = resp.json().get("calendars")
  1173. ads_out = []
  1174. if calendars:
  1175. for item in calendars:
  1176. # 通常是 MM/DD/YYYY
  1177. raw = item.get("date")
  1178. ads_out.append(to_yyyymmdd(raw, "%m/%d/%Y"))
  1179. return ads_out
  1180. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  1181. url = f"https://{self.vfs_api_domain}/appointment/timeslot"
  1182. headers = self._get_common_headers(with_auth=True)
  1183. dt_m = datetime.strptime(slot_date, "%Y-%m-%d")
  1184. converted_date = dt_m.strftime("%d/%m/%Y")
  1185. data = {
  1186. "missionCode": self.free_config.get("mission_code"),
  1187. "countryCode": self.free_config.get("country_code"),
  1188. "centerCode": apt_config.get("vac_code"),
  1189. "loginUser": self.config.account.username,
  1190. "visaCategoryCode": apt_config.get("subcategory_code"),
  1191. "slotDate": converted_date,
  1192. "urn": urn
  1193. }
  1194. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1195. return resp.json().get("slots", [])
  1196. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  1197. url = f"https://{self.vfs_api_domain}/appointment/saveuseractionaudit"
  1198. headers = self._get_common_headers(with_auth=True)
  1199. dt = datetime.strptime(earliest_date, "%Y-%m-%d")
  1200. data = {
  1201. "missionCode": self.free_config.get("mission_code"),
  1202. "countryCode": self.free_config.get("country_code"),
  1203. "centerCode": apt_config.get("vac_code"),
  1204. "loginUser": self.config.account.username,
  1205. "urn": urn,
  1206. "firstEarliestSlotDate": dt.strftime("%d/%m/%Y"),
  1207. "action": "schedule",
  1208. "ipAddress": self.real_ip,
  1209. "eadAppointmentDetail": dt.strftime("%Y-%m-%dT%H:%M:%S")
  1210. }
  1211. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1212. return resp.json().get("isSavedSuccess", False)
  1213. def _submit_no_addition_service(self, urn):
  1214. url = f"https://{self.vfs_api_domain}/vas/mapvas"
  1215. headers = self._get_common_headers(with_auth=True)
  1216. data = {
  1217. "loginUser": self.config.account.username,
  1218. "missionCode": self.free_config.get("mission_code"),
  1219. "countryCode": self.free_config.get("country_code"),
  1220. "urn": urn,
  1221. "applicants": []
  1222. }
  1223. self._perform_request("POST", url, headers=headers, json_data=data)
  1224. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  1225. url = f"https://{self.vfs_api_domain}/appointment/fees"
  1226. headers = self._get_common_headers(with_auth=True)
  1227. data = {
  1228. "missionCode": self.free_config.get("mission_code"),
  1229. "countryCode": self.free_config.get("country_code"),
  1230. "centerCode": apt_config.get("vac_code"),
  1231. "loginUser": self.config.account.username,
  1232. "urn": urn,
  1233. "languageCode": "en-US"
  1234. }
  1235. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1236. j = resp.json()
  1237. total = j.get("totalamount", 0.0)
  1238. currency = "EUR"
  1239. if j.get("feeDetails"):
  1240. currency = j["feeDetails"][0].get("currency", "EUR")
  1241. return total, currency
  1242. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  1243. url = f"https://{self.vfs_api_domain}/appointment/schedule"
  1244. headers = self._get_common_headers(with_auth=True)
  1245. data = {
  1246. "missionCode": self.free_config.get("mission_code"),
  1247. "countryCode": self.free_config.get("country_code"),
  1248. "centerCode": apt_config.get("vac_code"),
  1249. "loginUser": self.config.account.username,
  1250. "urn": urn,
  1251. "notificationType": "none",
  1252. "paymentdetails": {
  1253. "paymentmode": "Online",
  1254. "RequestRefNo": "",
  1255. "clientId": "",
  1256. "merchantId": "",
  1257. "amount": amount,
  1258. "currency": currency
  1259. },
  1260. "allocationId": str(slot_id),
  1261. "CanVFSReachoutToApplicant": True
  1262. }
  1263. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1264. return resp.json()
  1265. def _get_payment_start_url(self, schedule_res: Dict[str, Any]) -> str:
  1266. """
  1267. 根据 VFS schedule 响应构建初始支付请求 URL (对齐 main.js getPaymentUrl 逻辑)
  1268. """
  1269. lowered = {str(k).lower(): v for k, v in schedule_res.items()}
  1270. base_url = lowered.get("url") or "https://online.vfsglobal.com/PG-Component/Payment/PayRequest"
  1271. is_pg2 = lowered.get("ispg2enabled", False)
  1272. payload = lowered.get("payload", "")
  1273. # PG2 开启时直接使用 url
  1274. if is_pg2 or not payload:
  1275. return base_url
  1276. # 对 payload 进行严格 URL 编码(安全处理 '|'、'=' 等特殊字符)
  1277. encoded_payload = urllib.parse.quote(str(payload), safe='')
  1278. sep = "&" if "?" in base_url else "?"
  1279. return f"{base_url}{sep}payLoad={encoded_payload}"
  1280. def _pay_request(self, schedule_res_or_payload: Any) -> str:
  1281. """
  1282. 解析支付重定向 URL (DrissionPage 新标签页版,修复 URL 编码与重定向等待逻辑)
  1283. """
  1284. if isinstance(schedule_res_or_payload, dict):
  1285. start_url = self._get_payment_start_url(schedule_res_or_payload)
  1286. else:
  1287. encoded = urllib.parse.quote(str(schedule_res_or_payload), safe='')
  1288. start_url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={encoded}"
  1289. final_url = ""
  1290. pay_tab = None
  1291. try:
  1292. self._log(f"Resolving payment redirect...<{start_url[:120]}...>")
  1293. pay_tab = self.page.new_tab(start_url)
  1294. # 等待重定向离开 PayRequest (最多 15 秒)
  1295. for _ in range(30):
  1296. time.sleep(0.5)
  1297. cur_url = pay_tab.url
  1298. if cur_url and "PayRequest" not in cur_url and cur_url != "about:blank":
  1299. final_url = cur_url
  1300. break
  1301. if not final_url and pay_tab:
  1302. final_url = pay_tab.url
  1303. self._log(f"Payment URL resolved: {final_url}")
  1304. except Exception as e:
  1305. self._log(f"[WARN] Failed to resolve payment URL: {e}")
  1306. finally:
  1307. if pay_tab:
  1308. try:
  1309. pay_tab.close()
  1310. except Exception:
  1311. pass
  1312. return final_url
  1313. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  1314. url = f"https://{self.vfs_api_domain}/appointment/ConfirmWaitlist"
  1315. headers = self._get_common_headers(with_auth=True)
  1316. data = {
  1317. "missionCode": self.free_config.get("mission_code"),
  1318. "countryCode": self.free_config.get("country_code"),
  1319. "centerCode": apt_config.get("vac_code"),
  1320. "loginUser": self.config.account.username,
  1321. "urn": urn,
  1322. "notificationType": "none",
  1323. "CanVFSReachoutToApplicant": True
  1324. }
  1325. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  1326. confirmation = resp.json().get("isConfirmed")
  1327. return confirmation is True
  1328. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  1329. fmt = "%Y-%m-%d"
  1330. try:
  1331. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  1332. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.max
  1333. try:
  1334. dt_from = datetime.strptime(from_date, fmt)
  1335. except:
  1336. dt_from = datetime.now()
  1337. except:
  1338. return []
  1339. dt_start = dt_start.replace(day=1)
  1340. dt_end = dt_end.replace(day=1)
  1341. dt_from = dt_from.replace(day=1)
  1342. curr = max(dt_start, dt_from)
  1343. months = []
  1344. # A hard request budget also applies when callers explicitly ask for
  1345. # a distant end date. Subsequent attempts recheck a bounded window.
  1346. while curr <= dt_end and len(months) < 6:
  1347. months.append(curr.strftime(fmt))
  1348. if len(months) == 6 or (curr.year == 9999 and curr.month == 12):
  1349. break
  1350. if curr.month == 12:
  1351. curr = curr.replace(year=curr.year + 1, month=1)
  1352. else:
  1353. curr = curr.replace(month=curr.month + 1)
  1354. return months
  1355. def cleanup(self):
  1356. """销毁浏览器并彻底删除临时文件"""
  1357. cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
  1358. self.page = None
  1359. self.tunnel = None
  1360. self.injected = False
  1361. def get_plugin_status(self) -> PluginStatus:
  1362. account_name = self.config.account.username if self.config and self.config.account else ""
  1363. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  1364. current_url = ""
  1365. if self.page:
  1366. try:
  1367. current_url = self.page.url
  1368. except Exception:
  1369. pass
  1370. session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
  1371. state = "running" if self.is_healthy else "unhealthy"
  1372. if not self.jwt_token and self.page:
  1373. state = "logging_in"
  1374. return PluginStatus(
  1375. instance_id=self.instance_id,
  1376. is_healthy=self.is_healthy,
  1377. state=state,
  1378. current_url=current_url,
  1379. account=account_name,
  1380. proxy=proxy_info,
  1381. session_age_sec=session_age,
  1382. last_active_at=utc_now_str(),
  1383. )
  1384. def __del__(self):
  1385. """
  1386. 析构函数:当对象被垃圾回收时自动调用
  1387. """
  1388. self.cleanup()