francevisa_keygen.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. France-Visas (法签申请表系统) 自动化 Keygen / 协议客户端
  5. Target URL: https://application-form.france-visas.gouv.fr/fv-fo-dde/
  6. Authentication Realm: Keycloak Usager (https://connect.france-visas.gouv.fr/realms/usager)
  7. 核心功能:
  8. 1. 账号注册 (Registration) - 访问 OAuth 注册页,填写基本信息并提交验证码,触发邮箱验证
  9. 2. 获取激活邮件与验证 (Email Activation) - 预留空壳/API 钩子,支持自动提取并访问 action-token 完成激活
  10. 3. 重置与设置密码 (Reset / Set Password) - 申请重置密码、读取邮件中的更新密码 token 并提交新密码
  11. 4. 账号登录 (Login) - 完整 OAuth2 / OpenID Connect 授权登录与会话保持 (JSESSIONID)
  12. 5. 填表与新建申请 (Application Creation) - 基于 Jakarta Faces (JSF) 状态机创建申请组/表单
  13. 6. 获取 FRA1 申请号 (Fetch FRA1 Application Reference) - 解析用户主页,提取已生成的所有 FRA1 申请号及状态
  14. 7. 验证码空壳/扩展钩子 (Captcha Hook) - 内置 ddddocr 识别支持,并提供自定义回调/空壳函数
  15. """
  16. import os
  17. import re
  18. import sys
  19. import json
  20. import time
  21. import uuid
  22. import base64
  23. import yaml
  24. import random
  25. import string
  26. import logging
  27. import argparse
  28. from datetime import datetime, timezone, timedelta
  29. from typing import Optional, Dict, Any, List, Tuple, Union
  30. from urllib.parse import urljoin, urlparse, parse_qs, unquote
  31. ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
  32. # 解决 Windows GBK 终端乱码问题
  33. if sys.platform == "win32":
  34. try:
  35. sys.stdout.reconfigure(encoding="utf-8")
  36. sys.stderr.reconfigure(encoding="utf-8")
  37. except Exception:
  38. pass
  39. from curl_cffi import requests
  40. from bs4 import BeautifulSoup
  41. from DrissionPage import ChromiumPage, ChromiumOptions
  42. from toolkit.captcha_breaker import CaptchaBreaker
  43. from toolkit.cloud_api import CloudApi
  44. from core_types import BizLogicError
  45. # ==============================================================================
  46. # 日志配置
  47. # ==============================================================================
  48. logging.basicConfig(
  49. level=logging.INFO,
  50. format='%(asctime)s [%(levelname)s] %(message)s',
  51. datefmt='%H:%M:%S'
  52. )
  53. logger = logging.getLogger("FranceVisa-Keygen")
  54. # ==============================================================================
  55. # 常量定义
  56. # ==============================================================================
  57. BASE_APP_URL = "https://application-form.france-visas.gouv.fr/fv-fo-dde/"
  58. BASE_AUTH_URL = "https://connect.france-visas.gouv.fr"
  59. CLIENT_ID = "fv-fo-keycloak-web"
  60. DEFAULT_USER_AGENT = (
  61. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
  62. "AppleWebKit/537.36 (KHTML, like Gecko) "
  63. "Chrome/128.0.0.0 Safari/537.36"
  64. )
  65. DEFAULT_HEADERS = {
  66. "User-Agent": DEFAULT_USER_AGENT,
  67. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
  68. "Accept-Language": "en-US,en;q=0.9,fr;q=0.8",
  69. "Sec-Ch-Ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
  70. "Sec-Ch-Ua-Mobile": "?0",
  71. "Sec-Ch-Ua-Platform": '"Windows"',
  72. }
  73. # ==============================================================================
  74. # FranceVisaKeygen 核心客户端
  75. # ==============================================================================
  76. class FranceVisaKeygen:
  77. def __init__(
  78. self,
  79. proxy: Optional[str] = None,
  80. email_api_token: Optional[str] = None,
  81. master_email: Optional[str] = "hujiarui8@gmail.com",
  82. account_detail: Optional[Dict[str, Any]] = None,
  83. page: Optional[Any] = None,
  84. timeout: int = 20
  85. ):
  86. """
  87. :param proxy: 代理地址,例如 'http://127.0.0.1:7890' 或 'socks5://127.0.0.1:1080'
  88. :param email_api_token: 邮箱 API Token (如 text.skin),若无则使用空壳/交互输入
  89. :param master_email: 主接收邮箱地址 (默认 'hujiarui8@gmail.com')
  90. :param account_detail: 账号信息字典 (包含 'email', 'password' 等)
  91. :param page: DrissionPage 浏览器页面实例 (可选)
  92. :param timeout: 请求超时秒数
  93. """
  94. self.proxy = proxy
  95. self.email_api_token = email_api_token
  96. self.master_email = master_email or "hujiarui8@gmail.com"
  97. self.account_detail = account_detail or {}
  98. self.page = page
  99. self.timeout = timeout
  100. self.session = self._init_session()
  101. self.logged_in = False
  102. self.current_user = self.account_detail.get("email")
  103. # JSF 状态缓存
  104. self.last_view_state: Optional[str] = None
  105. self.last_csrf_token: Optional[str] = None
  106. # 大模型验证码识别器
  107. self.captcha_breaker = CaptchaBreaker()
  108. def _log(self, msg: str):
  109. now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  110. logger.info(f"[{now}] {msg}")
  111. def _init_session(self):
  112. """初始化 HTTP 会话,使用 curl_cffi 模拟 Chrome 浏览器指纹"""
  113. session = requests.Session(impersonate="chrome120")
  114. if self.proxy:
  115. session.proxies = {
  116. "http": self.proxy,
  117. "https": self.proxy,
  118. }
  119. return session
  120. def _get(self, url: str, **kwargs) -> Any:
  121. """带默认头部和超时的 GET 请求"""
  122. kwargs.setdefault("timeout", self.timeout)
  123. headers = kwargs.pop("headers", {})
  124. merged_headers = dict(DEFAULT_HEADERS)
  125. merged_headers.update(headers)
  126. return self.session.get(url, headers=merged_headers, **kwargs)
  127. def _post(self, url: str, data: Any = None, **kwargs) -> Any:
  128. """带默认头部和超时的 POST 请求"""
  129. kwargs.setdefault("timeout", self.timeout)
  130. headers = kwargs.pop("headers", {})
  131. merged_headers = dict(DEFAULT_HEADERS)
  132. merged_headers.update(headers)
  133. return self.session.post(url, data=data, headers=merged_headers, **kwargs)
  134. # ==========================================================================
  135. # 验证码处理 (使用 toolkit.captcha_breaker.CaptchaBreaker)
  136. # ==========================================================================
  137. def solve_captcha(
  138. self,
  139. image_bytes: Optional[bytes] = None,
  140. image_b64: Optional[str] = None,
  141. uuid_str: Optional[str] = None
  142. ) -> str:
  143. """
  144. 图像验证码识别函数。
  145. 使用 toolkit.captcha_breaker.CaptchaBreaker 多模态视觉大模型进行识别。
  146. 如果获取不了验证码图片或识别失败,调用空壳占位生成函数。
  147. """
  148. image_input = image_bytes or image_b64
  149. if image_input:
  150. try:
  151. breaker = getattr(self, "captcha_breaker", None) or CaptchaBreaker()
  152. result = breaker.break_captcha(
  153. image_input,
  154. prompt="请识别图片中的4-6位英文字母或数字验证码,只输出验证码本身的内容,不要任何空格、标点或额外文字。"
  155. )
  156. if result:
  157. clean_res = re.sub(r'[^a-zA-Z0-9]', '', result).lower()
  158. logger.info(f"[Captcha] CaptchaBreaker 识别结果: {clean_res}")
  159. return clean_res
  160. except Exception as e:
  161. logger.warning(f"[Captcha] CaptchaBreaker 识别出错: {e}")
  162. # 空壳函数备用逻辑:允许外部配置回调或返回模拟/占位
  163. logger.warning("[Captcha] 未获取到有效图片数据或识别失败,调用空壳占位验证码函数")
  164. # 占位生成 4 位伪随机码或固定测试码
  165. return ''.join(random.choices(string.ascii_lowercase + string.digits, k=4))
  166. def fetch_captcha_image(self, referer_url: str) -> Tuple[Optional[str], Optional[bytes], str]:
  167. """
  168. 从 Keycloak captchaEndpoint 拉取验证码图片数据与 UUID。
  169. 实际接口路径为 /fv-fo-captcha-rest/v2/simple-captcha-endpoint
  170. """
  171. captcha_url = f"{BASE_AUTH_URL}/fv-fo-captcha-rest/v2/simple-captcha-endpoint?get=image&c=alphanumerique4to6LightCaptchaFR"
  172. headers = {
  173. "Accept": "application/json, text/plain, */*",
  174. "Referer": referer_url,
  175. "Sec-Fetch-Dest": "empty",
  176. "Sec-Fetch-Mode": "cors",
  177. "Sec-Fetch-Site": "same-origin",
  178. }
  179. uuid_str = str(uuid.uuid4())
  180. try:
  181. resp = self._get(captcha_url, headers=headers)
  182. if resp.status_code == 200:
  183. data = resp.json()
  184. captcha_uuid = data.get("uuid", uuid_str)
  185. img_b64 = data.get("imageb64", "")
  186. logger.info(f"[Captcha] 成功获取验证码图片及 UUID: {captcha_uuid}")
  187. return captcha_uuid, None, img_b64
  188. else:
  189. logger.warning(f"[Captcha] 拉取验证码接口状态异常: {resp.status_code}")
  190. except Exception as e:
  191. logger.warning(f"[Captcha] 拉取验证码异常: {e}")
  192. return uuid_str, None, ""
  193. # ==========================================================================
  194. # 邮件获取与激活处理 (基于 CloudApi fetch_mail_content_from_top 轮询,防 504)
  195. # ==========================================================================
  196. def fetch_email_link(
  197. self,
  198. email: str,
  199. token_type: str = "verify-email",
  200. max_wait_seconds: int = 90,
  201. poll_interval: int = 3
  202. ) -> str:
  203. """
  204. 从 CloudApi 邮箱中提取指定账号的 action-token 验证或重置链接。
  205. 解码 JWT 负载核对 typ (verify-email 或 reset-credentials) 与 eml,防止混淆。
  206. 采用 fetch_mail_content_from_top 轮询机制,避免长轮询超时 504。
  207. """
  208. email_box = self.master_email or 'hujiarui8@gmail.com'
  209. self._log(f"正在通过 CloudApi 轮询 {email_box} 获取收件人 {email} 的邮件 (期望类型: {token_type})...")
  210. def _decode_jwt(link_str: str) -> Dict[str, Any]:
  211. m = re.search(r'key(?:=|=|=)([a-zA-Z0-9_\-\.]+)', link_str)
  212. if not m:
  213. return {}
  214. parts = m.group(1).split('.')
  215. if len(parts) >= 2:
  216. payload_b64 = parts[1]
  217. payload_b64 += '=' * ((4 - len(payload_b64) % 4) % 4)
  218. try:
  219. return json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8', errors='ignore'))
  220. except Exception:
  221. return {}
  222. return {}
  223. start_time = time.time()
  224. while time.time() - start_time < max_wait_seconds:
  225. try:
  226. content = CloudApi.Instance().fetch_mail_content_from_top(
  227. email=email_box,
  228. sender="",
  229. recipient=email,
  230. subject_keywords="",
  231. body_keywords="",
  232. top=10
  233. )
  234. if content:
  235. matches = re.findall(r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token[^\s"\'>]+', content)
  236. for m in matches:
  237. clean_link = m.replace('&amp;#61;', '=').replace('&#61;', '=').replace('&amp;', '&').rstrip('"\'>.,;')
  238. jwt_data = _decode_jwt(clean_link)
  239. typ = jwt_data.get('typ', '')
  240. eml = jwt_data.get('eml', '')
  241. # 严格核对收件人与 token 类型
  242. if eml and eml.lower() != email.lower():
  243. continue
  244. if token_type == "verify-email" and typ == "verify-email":
  245. self._log(f"成功匹配到激活邮件链接: {clean_link}")
  246. return clean_link
  247. elif token_type in ("reset-credentials", "UPDATE_PASSWORD") and typ in ("reset-credentials", "UPDATE_PASSWORD"):
  248. self._log(f"成功匹配到密码重置邮件链接: {clean_link}")
  249. return clean_link
  250. elif not token_type:
  251. return clean_link
  252. except Exception as e:
  253. self._log(f"轮询邮件返回: {e}")
  254. time.sleep(poll_interval)
  255. # 兜底尝试原生 fetch_mail_content
  256. try:
  257. content_out = CloudApi.Instance().fetch_mail_content(
  258. email=email_box,
  259. sender="",
  260. recipient=email,
  261. subject_keywords="",
  262. body_keywords="",
  263. sent_date=(datetime.now(timezone.utc) - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S"),
  264. expiry=30
  265. )
  266. match = re.search(r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token[^\s"\'>]+', content_out or "")
  267. if match:
  268. return match.group(0).replace('&amp;', '&').rstrip('"\'>.,;')
  269. except Exception:
  270. pass
  271. raise BizLogicError(message=f"等待账号 {email} 的邮件超时 (期望类型: {token_type})")
  272. def activate(self, sent_at: Optional[str] = None, email: Optional[str] = None) -> bool:
  273. """
  274. 激活账号邮件:
  275. 使用 CloudApi 轮询拉取邮件并提取激活链接,访问链接完成激活
  276. """
  277. email = email or (self.account_detail.get('email') if self.account_detail else None) or self.current_user
  278. if not email:
  279. raise ValueError("必须提供待激活账号的 email 或在 account_detail 中预设")
  280. activate_link = self.fetch_email_link(email=email, token_type="verify-email")
  281. self._log(f"成功获取激活链接: {activate_link}")
  282. # 若传入了 DrissionPage 浏览器页面实例,则通过浏览器访问并点击激活按钮
  283. if hasattr(self, 'page') and self.page is not None:
  284. self.page.get(activate_link)
  285. btn_selector = "#activation-pending-button"
  286. if hasattr(self.page, 'wait') and self.page.wait.ele_displayed(btn_selector, timeout=10):
  287. self.page.ele(btn_selector).click()
  288. time.sleep(3)
  289. return True
  290. else:
  291. # 纯协议极速激活
  292. resp = self._get(activate_link, allow_redirects=True)
  293. self._log(f"协议访问激活链接响应码: {resp.status_code}")
  294. return resp.status_code in (200, 302)
  295. def fetch_activation_link(self, email: str, max_wait_sec: int = 60) -> Optional[str]:
  296. """
  297. 空壳函数:获取激活邮件中的验证链接。
  298. 如系统支持 text.skin API,将尝试调用云端接口轮询;
  299. 若无配置,则提示用户或返回 None。
  300. """
  301. logger.info(f"[Email-Stub] 正在等待/获取 {email} 的激活邮件...")
  302. # 如果配置了 text.skin 邮箱服务 API,则自动轮询读取
  303. if self.email_api_token:
  304. api_url = "https://api.text.skin/api/email-authorizations/fetch"
  305. headers = {
  306. "Authorization": f"Bearer {self.email_api_token}",
  307. "Content-Type": "application/json"
  308. }
  309. start_time = time.time()
  310. while time.time() - start_time < max_wait_sec:
  311. try:
  312. params = {
  313. "recipient": email,
  314. "subjectKeywords": "France-Visas",
  315. "bodyKeywords": "action-token",
  316. "expiry": str(max_wait_sec)
  317. }
  318. if self.master_email:
  319. params["email"] = self.master_email
  320. resp = requests.post(api_url, headers=headers, params=params, json={}, timeout=10)
  321. if resp.status_code == 200:
  322. data = resp.json()
  323. body = data.get("data", {}).get("body", "")
  324. if body:
  325. match = re.search(
  326. r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token\?key=[^\s"\'>]+',
  327. body
  328. )
  329. if match:
  330. link = match.group(0).replace("&amp;", "&")
  331. logger.info(f"[Email] 从 text.skin 成功获取激活链接: {link}")
  332. return link
  333. except Exception as e:
  334. logger.debug(f"[Email] 轮询异常: {e}")
  335. time.sleep(3)
  336. logger.warning(f"[Email-Stub] 空壳函数未获取到自动激活邮件,请手动传入 action-token 链接。")
  337. return None
  338. def fetch_password_reset_link(self, email: str, max_wait_sec: int = 60) -> Optional[str]:
  339. """
  340. 空壳函数:获取密码重置邮件中的 action-token 链接。
  341. """
  342. logger.info(f"[Email-Stub] 正在等待/获取 {email} 的重置密码邮件...")
  343. # 与 fetch_activation_link 类似,使用相同格式的 action-token
  344. return self.fetch_activation_link(email, max_wait_sec=max_wait_sec)
  345. # ==========================================================================
  346. # 1. 注册功能 (Registration)
  347. # ==========================================================================
  348. def register(
  349. self,
  350. first_name: str,
  351. last_name: str,
  352. email: str,
  353. language: str = "English",
  354. captcha_code: Optional[str] = None,
  355. captcha_uuid: Optional[str] = None
  356. ) -> Dict[str, Any]:
  357. """
  358. 注册法签申请账号:
  359. 1. 访问首页并跳转至 Keycloak 认证页
  360. 2. 获取注册页 URL (registrationUrl) 并拉取表单上下文
  361. 3. 获取/计算验证码及 captchetat-uuid
  362. 4. 提交注册 POST 请求
  363. """
  364. logger.info(f"[Register] 开始注册账号: {email} ({first_name} {last_name})")
  365. # Step 1: 访问主站以进入 Keycloak OAuth 授权流
  366. resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
  367. login_html = resp_entry.text
  368. # 从页面提取 registrationUrl
  369. reg_match = re.search(r'"registrationUrl":\s*"([^"]+)"', login_html)
  370. if not reg_match:
  371. # 兼容 HTML a 标签
  372. soup = BeautifulSoup(login_html, "html.parser")
  373. a_tag = soup.find("a", href=lambda h: h and "registration" in h)
  374. if a_tag:
  375. reg_url = urljoin(resp_entry.url, a_tag["href"])
  376. else:
  377. raise RuntimeError("未能从登录页解析出注册地址 (registrationUrl)")
  378. else:
  379. reg_url = urljoin(resp_entry.url, reg_match.group(1).replace(r"\/", "/"))
  380. logger.info(f"[Register] 打开注册表单页: {reg_url}")
  381. resp_reg = self._get(reg_url)
  382. reg_html = resp_reg.text
  383. # Step 2: 提取注册表单 action (包含 session_code, execution 等参数)
  384. action_match = re.search(r'"registrationAction":\s*"([^"]+)"', reg_html)
  385. if not action_match:
  386. soup = BeautifulSoup(reg_html, "html.parser")
  387. form = soup.find("form", id="kc-register-form") or soup.find("form")
  388. if form and form.get("action"):
  389. action_url = urljoin(resp_reg.url, form["action"])
  390. else:
  391. action_url = reg_url
  392. else:
  393. action_url = action_match.group(1).replace(r"\/", "/")
  394. logger.info(f"[Register] 注册表单 Action: {action_url}")
  395. # Step 3: 获取验证码与 UUID
  396. if not captcha_uuid or not captcha_code:
  397. fetched_uuid, _, img_b64 = self.fetch_captcha_image(referer_url=reg_url)
  398. captcha_uuid = captcha_uuid or fetched_uuid
  399. if not captcha_code:
  400. captcha_code = self.solve_captcha(image_b64=img_b64, uuid_str=captcha_uuid)
  401. # Step 4: 构造 POST 负载提交注册
  402. payload = {
  403. "lastName": last_name,
  404. "firstName": first_name,
  405. "email": email,
  406. "emailVerif": email,
  407. "ddeLanguage": language,
  408. "captchaFormulaireExtInput": captcha_code,
  409. "captchetat-uuid": captcha_uuid
  410. }
  411. headers = {
  412. "Content-Type": "application/x-www-form-urlencoded",
  413. "Origin": BASE_AUTH_URL,
  414. "Referer": reg_url
  415. }
  416. logger.info(f"[Register] 提交注册信息 (Captcha: {captcha_code}, UUID: {captcha_uuid})")
  417. resp_submit = self._post(action_url, data=payload, headers=headers, allow_redirects=False)
  418. # Keycloak 成功注册后会重定向至 required-action?execution=VERIFY_EMAIL
  419. location = resp_submit.headers.get("Location", "")
  420. if resp_submit.status_code in (302, 303) and "VERIFY_EMAIL" in location:
  421. logger.info(f"[Register] 注册成功!已触发邮箱验证邮件,重定向目标: {location}")
  422. # 请求提示页以确认验证状态
  423. self._get(urljoin(action_url, location))
  424. return {
  425. "success": True,
  426. "email": email,
  427. "status": "PENDING_EMAIL_VERIFICATION",
  428. "verify_url": location
  429. }
  430. elif resp_submit.status_code == 200:
  431. # 留在原页面通常代表验证码错误或字段校验失败
  432. soup = BeautifulSoup(resp_submit.text, "html.parser")
  433. err_alert = soup.find(class_=lambda c: c and any(x in c.lower() for x in ["error", "alert", "feedback"]))
  434. err_msg = err_alert.get_text(strip=True) if err_alert else "注册未通过(可能是验证码或邮箱已存在)"
  435. logger.warning(f"[Register] 提交响应未重定向: {err_msg}")
  436. return {
  437. "success": False,
  438. "email": email,
  439. "error": err_msg,
  440. "html_snippet": resp_submit.text[:500]
  441. }
  442. else:
  443. logger.info(f"[Register] 响应状态码: {resp_submit.status_code}, Location: {location}")
  444. return {
  445. "success": resp_submit.status_code in (200, 302),
  446. "email": email,
  447. "status_code": resp_submit.status_code,
  448. "location": location
  449. }
  450. # ==========================================================================
  451. # 2. 邮箱验证激活 (Verify Email via Token)
  452. # ==========================================================================
  453. def verify_email(self, action_token_url_or_key: str) -> bool:
  454. """
  455. 通过 action-token 链接激活邮箱。
  456. :param action_token_url_or_key: 完整的 action-token URL 或其中的 JWT key
  457. """
  458. if "action-token?key=" in action_token_url_or_key:
  459. url = action_token_url_or_key
  460. else:
  461. url = f"{BASE_AUTH_URL}/realms/usager/login-actions/action-token?key={action_token_url_or_key}&client_id={CLIENT_ID}"
  462. logger.info(f"[VerifyEmail] 正在访问激活链接: {url[:100]}...")
  463. resp = self._get(url, allow_redirects=True)
  464. if resp.status_code in (200, 302):
  465. logger.info("[VerifyEmail] 邮箱激活请求完成!")
  466. return True
  467. else:
  468. logger.error(f"[VerifyEmail] 激活失败,HTTP 状态码: {resp.status_code}")
  469. return False
  470. # ==========================================================================
  471. # 3. 重置/设置密码 (Reset / Set Password)
  472. # ==========================================================================
  473. def request_password_reset(
  474. self,
  475. email: str,
  476. captcha_code: Optional[str] = None,
  477. captcha_uuid: Optional[str] = None
  478. ) -> Dict[str, Any]:
  479. """
  480. 申请密码重置邮件:
  481. 1. 获取 reset-credentials 页面
  482. 2. 填写邮箱与验证码
  483. 3. 提交后系统向邮箱发送 UPDATE_PASSWORD token 邮件
  484. """
  485. logger.info(f"[ResetPassword] 正在申请重置密码: {email}")
  486. # 获取重置密码入口
  487. resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
  488. reset_match = re.search(r'"loginResetCredentialsUrl":\s*"([^"]+)"', resp_entry.text)
  489. if reset_match:
  490. reset_url = urljoin(resp_entry.url, reset_match.group(1).replace(r"\/", "/"))
  491. else:
  492. reset_url = f"{BASE_AUTH_URL}/realms/usager/login-actions/reset-credentials?client_id={CLIENT_ID}"
  493. resp_reset = self._get(reset_url)
  494. reset_html = resp_reset.text
  495. # 提取表单 action
  496. action_match = re.search(r'"loginAction":\s*"([^"]+)"', reset_html) or re.search(r'action=["\']([^"\']+)["\']', reset_html)
  497. action_url = action_match.group(1).replace(r"\/", "/") if action_match else reset_url
  498. if not action_url.startswith("http"):
  499. action_url = urljoin(resp_reset.url, action_url)
  500. # 获取/计算验证码
  501. if not captcha_uuid or not captcha_code:
  502. fetched_uuid, _, img_b64 = self.fetch_captcha_image(referer_url=reset_url)
  503. captcha_uuid = captcha_uuid or fetched_uuid
  504. if not captcha_code:
  505. captcha_code = self.solve_captcha(image_b64=img_b64, uuid_str=captcha_uuid)
  506. payload = {
  507. "username": email,
  508. "captchaFormulaireExtInput": captcha_code,
  509. "captchetat-uuid": captcha_uuid
  510. }
  511. headers = {
  512. "Content-Type": "application/x-www-form-urlencoded",
  513. "Origin": BASE_AUTH_URL,
  514. "Referer": reset_url
  515. }
  516. logger.info(f"[ResetPassword] 提交重置申请 (Captcha: {captcha_code}, UUID: {captcha_uuid})")
  517. resp_submit = self._post(action_url, data=payload, headers=headers)
  518. if resp_submit.status_code == 200:
  519. # 校验 Keycloak 响应中是否有错误提示 (防验证码识别偏差导致误判为成功)
  520. m_ctx = re.search(r'kcContext\s*=\s*(\{.+?\});', resp_submit.text, re.DOTALL)
  521. is_error = False
  522. err_msg = ""
  523. if m_ctx:
  524. ctx_str = m_ctx.group(1)
  525. if re.search(r'"type":\s*"error"|"error":\s*true', ctx_str):
  526. is_error = True
  527. m_summary = re.search(r'"summary":\s*"([^"]+)"', ctx_str)
  528. err_msg = m_summary.group(1) if m_summary else "验证码识别不匹配"
  529. soup = BeautifulSoup(resp_submit.text, "html.parser")
  530. err_alert = soup.find(class_=lambda c: c and any(x in str(c).lower() for x in ["error", "alert", "feedback"]))
  531. if err_alert and not is_error:
  532. txt = err_alert.get_text(strip=True)
  533. if txt and len(txt) > 3:
  534. is_error = True
  535. err_msg = txt
  536. if is_error:
  537. logger.warning(f"[ResetPassword] 重置申请未通过 (将自动重试): {err_msg}")
  538. return {"success": False, "error": err_msg}
  539. logger.info("[ResetPassword] 重置请求已提交,邮件已发送!")
  540. return {"success": True, "email": email}
  541. else:
  542. logger.warning(f"[ResetPassword] 提交响应码: {resp_submit.status_code}")
  543. return {"success": False, "status_code": resp_submit.status_code}
  544. def complete_password_reset(self, action_token_url_or_key: str, new_password: str) -> bool:
  545. """
  546. 通过邮件中的 action-token 完成重置并设定新密码:
  547. 1. 访问 action-token 链接 -> 跟随重定向至 required-action?execution=UPDATE_PASSWORD
  548. 2. 从 kcContext 中提取真实的 loginAction URL (包含 session_code)
  549. 3. 提交 password-new 与 password-confirm 完成更新
  550. """
  551. logger.info("[ResetPassword] 正在执行重置密码最终设定...")
  552. if "action-token?key=" in action_token_url_or_key:
  553. token_url = action_token_url_or_key
  554. else:
  555. token_url = f"{BASE_AUTH_URL}/realms/usager/login-actions/action-token?key={action_token_url_or_key}&execution=UPDATE_PASSWORD&client_id={CLIENT_ID}"
  556. # 访问 token URL,通常会经过 302 重定向到 required-action 页面
  557. resp_token = self._get(token_url, allow_redirects=True)
  558. form_html = resp_token.text
  559. pwd_form_url = resp_token.url
  560. # 从 kcContext 中提取真实的 loginAction URL (包含 session_code, execution=UPDATE_PASSWORD)
  561. action_match = (
  562. re.search(r'"loginAction":\s*"([^"]+)"', form_html)
  563. or re.search(r'"registrationAction":\s*"([^"]+)"', form_html)
  564. or re.search(r'action=["\']([^"\']+)["\']', form_html)
  565. )
  566. if action_match:
  567. action_url = action_match.group(1).replace(r"\/", "/").replace("&amp;", "&")
  568. if not action_url.startswith("http"):
  569. action_url = urljoin(pwd_form_url, action_url)
  570. else:
  571. action_url = pwd_form_url
  572. payload = {
  573. "password-new": new_password,
  574. "password-confirm": new_password
  575. }
  576. headers = {
  577. "Content-Type": "application/x-www-form-urlencoded",
  578. "Origin": BASE_AUTH_URL,
  579. "Referer": pwd_form_url
  580. }
  581. logger.info(f"[ResetPassword] 正在向 {action_url} 提交新密码...")
  582. resp_pwd = self._post(action_url, data=payload, headers=headers, allow_redirects=False)
  583. # 成功更新密码后,Keycloak 通常返回 302 重定向到前端或返回无错误的确认页面
  584. if resp_pwd.status_code in (302, 303):
  585. logger.info("[ResetPassword] 密码重置成功 (302 Redirect)!")
  586. return True
  587. elif resp_pwd.status_code == 200:
  588. # 检查是否有错误提示
  589. soup = BeautifulSoup(resp_pwd.text, "html.parser")
  590. err = soup.find(class_=lambda c: c and any(x in str(c).lower() for x in ["error", "alert", "feedback"]))
  591. if err:
  592. logger.error(f"[ResetPassword] 密码重置未通过: {err.get_text(strip=True)}")
  593. return False
  594. logger.info("[ResetPassword] 密码重置成功!")
  595. return True
  596. else:
  597. logger.error(f"[ResetPassword] 提交密码失败,状态码: {resp_pwd.status_code}")
  598. return False
  599. def set_initial_password(self, email: str, password: str, max_retries: int = 3) -> bool:
  600. """
  601. 为新注册的账号设置初始密码:
  602. 1. 申请重置密码(利用 CaptchaBreaker 破解验证码)
  603. 2. 通过 CloudApi 轮询接收包含 UPDATE_PASSWORD 的 action-token 邮件
  604. 3. 提交 password-new 与 password-confirm 完成设定
  605. """
  606. self._log(f"开始为账号 {email} 设定初始登录密码...")
  607. # 1. 提交重置密码申请 (如遇验证码识别失败自动重试)
  608. reset_ok = False
  609. for attempt in range(1, max_retries + 1):
  610. try:
  611. reset_req = self.request_password_reset(email)
  612. if reset_req.get("success"):
  613. reset_ok = True
  614. break
  615. except Exception as e:
  616. self._log(f"密码重置申请第 {attempt} 次失败: {e}")
  617. time.sleep(2)
  618. if not reset_ok:
  619. raise BizLogicError(message=f"账号 {email} 申请密码重置失败")
  620. # 2. 等待重置邮件
  621. self._log(f"正在通过 CloudApi 等待密码重置邮件...")
  622. reset_link = self.fetch_email_link(email=email, token_type="reset-credentials")
  623. self._log(f"成功获取重置链接: {reset_link}")
  624. # 3. 提交新密码
  625. return self.complete_password_reset(reset_link, password)
  626. # ==========================================================================
  627. # 4. 登录功能 (Login)
  628. # ==========================================================================
  629. def login(self, username: str, password: str) -> bool:
  630. """
  631. 执行完整 OAuth2 / Keycloak 登录认证流程:
  632. 1. 访问主系统入口,触发 OAuth2 授权重定向并获取 state/nonce
  633. 2. 提取 Keycloak authenticate 表单 action
  634. 3. POST 提交用户名和密码
  635. 4. 跟随 302 重定向回到应用回调地址,获取并持久化 JSESSIONID
  636. 5. 验证登录后的主控面板 (accueil.xhtml)
  637. """
  638. logger.info(f"[Login] 开始登录账号: {username}")
  639. self.logged_in = False
  640. self.current_user = None
  641. # Step 1: 访问首页触发 OAuth2 认证流
  642. resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
  643. login_html = resp_entry.text
  644. # Step 2: 提取 authenticate 动作地址
  645. action_match = re.search(r'"loginAction":\s*"([^"]+)"', login_html)
  646. if action_match:
  647. auth_action_url = action_match.group(1).replace(r"\/", "/")
  648. else:
  649. soup = BeautifulSoup(login_html, "html.parser")
  650. form = soup.find("form", id="kc-form-login") or soup.find("form")
  651. if form and form.get("action"):
  652. auth_action_url = urljoin(resp_entry.url, form["action"])
  653. else:
  654. auth_action_url = resp_entry.url
  655. logger.info(f"[Login] 登录认证 Action: {auth_action_url}")
  656. # Step 3: 提交登录凭证
  657. payload = {
  658. "username": username,
  659. "password": password,
  660. "credentialId": ""
  661. }
  662. headers = {
  663. "Content-Type": "application/x-www-form-urlencoded",
  664. "Origin": BASE_AUTH_URL,
  665. "Referer": resp_entry.url
  666. }
  667. resp_auth = self._post(auth_action_url, data=payload, headers=headers, allow_redirects=False)
  668. redirect_url = resp_auth.headers.get("Location")
  669. # Keycloak 登录成功后会 302 重定向到 application-form.../login/oauth2/code/keycloak
  670. if resp_auth.status_code in (302, 303) and redirect_url:
  671. logger.info(f"[Login] 认证成功,跟随 OAuth2 回调: {redirect_url[:80]}...")
  672. # Step 4: 访问 OAuth2 回调并换取业务 JSESSIONID
  673. resp_cb = self._get(redirect_url, allow_redirects=True)
  674. logger.info(f"[Login] 登录完成,当前 URL: {resp_cb.url}")
  675. # Step 5: 验证登录状态
  676. dashboard_html = resp_cb.text
  677. if "formAccueilUsager" in dashboard_html or "accueil.xhtml" in resp_cb.url or "déconnexion" in dashboard_html.lower() or "logout" in dashboard_html.lower():
  678. self.logged_in = True
  679. self.current_user = username
  680. self._extract_jsf_state(dashboard_html)
  681. logger.info(f"[Login] 账号 {username} 成功登录法签申请表系统!")
  682. return True
  683. else:
  684. logger.warning("[Login] 回调后页面未见主页表单,登录状态待确认")
  685. self.logged_in = True
  686. self.current_user = username
  687. return True
  688. else:
  689. logger.error(f"[Login] 登录失败!HTTP 状态码: {resp_auth.status_code}")
  690. if resp_auth.status_code == 200:
  691. soup = BeautifulSoup(resp_auth.text, "html.parser")
  692. err = soup.find(class_=lambda c: c and ("error" in c.lower() or "alert" in c.lower()))
  693. if err:
  694. logger.error(f"[Login] 错误提示: {err.get_text(strip=True)}")
  695. return False
  696. def _extract_jsf_state(self, html: str):
  697. """解析 Jakarta Faces / JSF 页面中的 ViewState 与 CSRF Token"""
  698. soup = BeautifulSoup(html, "html.parser")
  699. # ViewState
  700. vs_input = soup.find("input", {"name": "jakarta.faces.ViewState"})
  701. if vs_input and vs_input.get("value"):
  702. self.last_view_state = vs_input["value"]
  703. # CSRF Token
  704. csrf_input = soup.find("input", {"name": "_csrf"})
  705. if csrf_input and csrf_input.get("value"):
  706. self.last_csrf_token = csrf_input["value"]
  707. # ==========================================================================
  708. # 5. 填表与新建申请组 (Application Creation)
  709. # ==========================================================================
  710. def create_application_group(self) -> Dict[str, Any]:
  711. """
  712. 在主页发起新建申请组/申请表:
  713. 1. GET /fv-fo-dde/accueil.xhtml 提取 ViewState 与 _csrf
  714. 2. POST /fv-fo-dde/accueil.xhtml 提交 formAccueilUsager:ajouterGroupe
  715. 3. 重定向到 step1.xhtml 并初始化表单会话
  716. """
  717. if not self.logged_in:
  718. raise RuntimeError("请先调用 login() 成功登录后再进行填表操作!")
  719. logger.info("[Application] 正在主页发起新建申请组 (ajouterGroupe)...")
  720. accueil_url = urljoin(BASE_APP_URL, "accueil.xhtml")
  721. resp_accueil = self._get(accueil_url)
  722. self._extract_jsf_state(resp_accueil.text)
  723. if not self.last_view_state or not self.last_csrf_token:
  724. logger.warning("[Application] 未能在主页解析到完整的 JSF ViewState 或 _csrf,尝试使用正则提取")
  725. vs_m = re.search(r'name=["\']jakarta\.faces\.ViewState["\']\s+value=["\']([^"\']+)["\']', resp_accueil.text)
  726. csrf_m = re.search(r'name=["\']_csrf["\']\s+value=["\']([^"\']+)["\']', resp_accueil.text)
  727. if vs_m:
  728. self.last_view_state = vs_m.group(1)
  729. if csrf_m:
  730. self.last_csrf_token = csrf_m.group(1)
  731. payload = {
  732. "formAccueilUsager": "formAccueilUsager",
  733. "formAccueilUsager:ajouterGroupe": "",
  734. "_csrf": self.last_csrf_token or "",
  735. "jakarta.faces.ViewState": self.last_view_state or ""
  736. }
  737. headers = {
  738. "Content-Type": "application/x-www-form-urlencoded",
  739. "Origin": "https://application-form.france-visas.gouv.fr",
  740. "Referer": accueil_url
  741. }
  742. resp_create = self._post(accueil_url, data=payload, headers=headers, allow_redirects=False)
  743. location = resp_create.headers.get("Location", "")
  744. logger.info(f"[Application] 新建申请组响应状态: {resp_create.status_code}, 重定向: {location}")
  745. if "step1.xhtml" in location or resp_create.status_code in (302, 303):
  746. step1_url = urljoin(BASE_APP_URL, location if location else "step1.xhtml")
  747. resp_step1 = self._get(step1_url)
  748. self._extract_jsf_state(resp_step1.text)
  749. logger.info(f"[Application] 成功进入申请表 Step 1 (Plans) 页面: {step1_url}")
  750. return {
  751. "success": True,
  752. "current_step": "step1",
  753. "step_url": step1_url
  754. }
  755. else:
  756. return {
  757. "success": False,
  758. "status_code": resp_create.status_code,
  759. "location": location
  760. }
  761. def fill_step1_and_create_application(
  762. self,
  763. applicant_data: Optional[Dict[str, Any]] = None
  764. ) -> Dict[str, Any]:
  765. """
  766. 自动化填表 (Step 1 - Your plans) 并生成/提取 FRA1 申请编号:
  767. 1. 启动/复用 Chromium 浏览器页面 (带代理配置)
  768. 2. 登录账号进入法签系统
  769. 3. 发起新建申请组 (Create a new application in a new group of applications)
  770. 4. 级联填写 Step 1 必填信息:
  771. - 国籍 (Nationality): 默认 CHN
  772. - 欧盟亲属 (hasNationalFamily): 默认 No
  773. - 递签国家 (Place of submission): 默认 CHN
  774. - 停留类型 (Stay duration): 默认 C (Short-stay <= 90 days)
  775. - 主目的地 (Destination): 默认 MET (France)
  776. - 递签城市 (Town): 默认 1PE (Beijing) 或指定城市
  777. - 护照签发国 (Authority): 默认 CHN (China)
  778. - 旅行证件类型 (Travel document): 默认 10 (Ordinary passport)
  779. - 护照号与起止有效期
  780. - 申请主目的与子目的 (Purpose category & Purpose): 默认 TOUR (Tourism) / 134 或 1
  781. 5. 点击 Verify 校验表单
  782. 6. 点击 Next 弹出护照号确认弹窗
  783. 7. 确认弹窗中的 Yes (formStep1:btnValiderModal),完成第一步锁定并提交
  784. 8. 确认成功跳转至 Step 2 (Your information)
  785. 9. 返回主页 accueil.xhtml 提取正式生成的 FRA1 申请编号 (如 FRA1PE20267100927)
  786. """
  787. applicant_data = applicant_data or {}
  788. email = (
  789. applicant_data.get("email")
  790. or applicant_data.get("username")
  791. or self.account_detail.get("email")
  792. or self.current_user
  793. )
  794. password = (
  795. applicant_data.get("password")
  796. or self.account_detail.get("password")
  797. )
  798. if not email or not password:
  799. raise ValueError("必须提供账号 email 与 password 才能进行填表生成 FRA1!")
  800. logger.info(f"[Application] 开始为账号 {email} 执行自动化填表 (Step 1) 与 FRA1 申请号生成流程...")
  801. nationality = applicant_data.get("nationality", "CHN")
  802. has_family = applicant_data.get("has_family", False)
  803. if isinstance(has_family, str):
  804. has_family = has_family.lower() in ("true", "1", "yes")
  805. deposit_country = applicant_data.get("deposit_country", "CHN")
  806. stay_duration = applicant_data.get("stay_duration", "C")
  807. destination = applicant_data.get("destination", "MET")
  808. town = applicant_data.get("town") or applicant_data.get("city", "1PE")
  809. authority = applicant_data.get("authority", "CHN")
  810. doc_type = applicant_data.get("doc_type", "10")
  811. # 护照号与有效期
  812. passport_no = applicant_data.get("passport_number") or applicant_data.get("passport_no")
  813. if not passport_no:
  814. rand_digits = ''.join(random.choices(string.digits, k=8))
  815. passport_no = f"E{rand_digits}"
  816. release_date = applicant_data.get("release_date", "01/01/2022")
  817. expiration_date = applicant_data.get("expiration_date", "01/01/2032")
  818. purpose_cat = applicant_data.get("purpose_category", "TOUR")
  819. purpose = applicant_data.get("purpose")
  820. own_page = False
  821. page = getattr(self, "page", None)
  822. if not page:
  823. co = ChromiumOptions()
  824. if self.proxy:
  825. co.set_proxy(self.proxy)
  826. co.headless(True)
  827. co.set_argument('--no-sandbox')
  828. co.set_argument('--disable-gpu')
  829. page = ChromiumPage(co)
  830. own_page = True
  831. try:
  832. logger.info("[Application] 访问法签主系统入口...")
  833. page.get(BASE_APP_URL)
  834. time.sleep(2)
  835. # 若遇到登录表单则自动登录
  836. user_inp = page.ele('@name:username')
  837. pwd_inp = page.ele('@name:password')
  838. if user_inp and pwd_inp:
  839. logger.info(f"[Application] 自动提交登录: {email}")
  840. user_inp.input(email)
  841. pwd_inp.input(password)
  842. btn_login = page.ele('@id:kc-login') or page.ele('@type:submit')
  843. if btn_login:
  844. btn_login.click()
  845. time.sleep(4)
  846. # 检查是否有未完成的申请需要编辑,或者新建申请
  847. btn_add = page.ele('#formAccueilUsager\\:ajouterGroupe') or page.ele('text:Create a new application')
  848. if btn_add:
  849. logger.info("[Application] 点击新建申请组 (ajouterGroupe)...")
  850. btn_add.click()
  851. time.sleep(3)
  852. # 如果已经在 step1 或需要编辑进入
  853. if "step1.xhtml" not in page.url:
  854. btn_edit = page.ele('css:a[title*="Edit"], a[title*="Modif"]') or page.ele('css:a.ui-commandlink')
  855. if btn_edit:
  856. btn_edit.click()
  857. time.sleep(3)
  858. # 填充 Step 1 字段
  859. logger.info(f"[Application] 填充基本信息: 国籍={nationality}, 递签国={deposit_country}, 城市={town}, 护照={passport_no}")
  860. # 1. 国籍
  861. page.run_js(f"""
  862. let el = document.querySelector("select[name='formStep1:visas-selected-nationality_input']");
  863. if (el) {{ el.value = '{nationality}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
  864. """)
  865. time.sleep(1)
  866. # 2. 欧盟亲属: Yes/No (0: Yes, 1: No)
  867. family_radio_idx = 0 if has_family else 1
  868. page.run_js(f"""
  869. let el = document.getElementById('formStep1:hasNationalFamily:{family_radio_idx}');
  870. if (el) {{
  871. el.checked = true;
  872. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  873. el.dispatchEvent(new Event('click', {{ bubbles: true }}));
  874. }}
  875. """)
  876. time.sleep(1)
  877. # 3. 递签国
  878. page.run_js(f"""
  879. let el = document.querySelector("select[name='formStep1:Visas-selected-deposit-country_input']");
  880. if (el) {{ el.value = '{deposit_country}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
  881. """)
  882. time.sleep(2)
  883. # 4. 停留期
  884. page.run_js(f"""
  885. let el = document.querySelector("select[name='formStep1:Visas-selected-stayDuration_input']");
  886. if (el) {{ el.value = '{stay_duration}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
  887. """)
  888. time.sleep(2)
  889. # 5. 目的地
  890. page.run_js(f"""
  891. let el = document.querySelector("select[name='formStep1:Visas-selected-destination_input']");
  892. if (el && el.options.length > 1) {{
  893. el.value = '{destination}' || el.options[1].value;
  894. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  895. }}
  896. """)
  897. time.sleep(2)
  898. # 6. 递签城市
  899. page.run_js(f"""
  900. let el = document.querySelector("select[name='formStep1:Visas-selected-deposit-town_input']");
  901. if (el && el.options.length > 1) {{
  902. el.value = '{town}' || el.options[1].value;
  903. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  904. }}
  905. """)
  906. time.sleep(2)
  907. # 7. 签发国
  908. page.run_js(f"""
  909. let el = document.querySelector("select[name='formStep1:Visas-selected-authority_input']");
  910. if (el && el.options.length > 1) {{
  911. el.value = '{authority}' || el.options[1].value;
  912. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  913. }}
  914. """)
  915. time.sleep(2)
  916. # 8. 证件类型
  917. page.run_js(f"""
  918. let el = document.querySelector("select[name='formStep1:Visas-dde-travel-document_input']");
  919. if (el && el.options.length > 1) {{
  920. el.value = '{doc_type}' || el.options[1].value;
  921. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  922. }}
  923. """)
  924. time.sleep(2)
  925. # 9. 护照号与起止日期
  926. page.run_js(f"""
  927. let elDoc = document.getElementById('formStep1:Visas-dde-travel-document-number');
  928. if (elDoc) elDoc.value = '{passport_no}';
  929. let elRel = document.getElementById('formStep1:Visas-dde-release_date_real_input');
  930. if (elRel) elRel.value = '{release_date}';
  931. let elExp = document.getElementById('formStep1:Visas-dde-expiration_date_input');
  932. if (elExp) elExp.value = '{expiration_date}';
  933. """)
  934. time.sleep(1)
  935. # 10. 签证目的类别
  936. page.run_js(f"""
  937. let el = document.querySelector("select[name='formStep1:Visas-selected-purposeCategory_input']");
  938. if (el && el.options.length > 1) {{
  939. el.value = '{purpose_cat}' || el.options[1].value;
  940. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  941. }}
  942. """)
  943. time.sleep(2)
  944. # 11. 签证目的子项
  945. page.run_js(f"""
  946. let el = document.querySelector("select[name='formStep1:Visas-selected-purpose_input']");
  947. if (el && el.options.length > 1) {{
  948. let targetVal = '{purpose or ""}';
  949. if (targetVal && Array.from(el.options).some(o => o.value === targetVal)) {{
  950. el.value = targetVal;
  951. }} else {{
  952. el.value = el.options[1].value;
  953. }}
  954. el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  955. }}
  956. """)
  957. time.sleep(2)
  958. # 12. 点击 Verify
  959. logger.info("[Application] 提交 Step 1 校验 (Verify)...")
  960. btn_verif = page.ele('#formStep1\\:btnVerifier') or page.ele('text:Verify')
  961. if btn_verif:
  962. btn_verif.click()
  963. time.sleep(4)
  964. # 13. 点击 Next
  965. btn_suivant = page.ele('#formStep1\\:btnSuivant')
  966. if not btn_suivant:
  967. btn_suivant = page.ele('css:button.primaire')
  968. if btn_suivant:
  969. logger.info("[Application] 点击下一步 (Next) 触发护照确认弹窗...")
  970. btn_suivant.click()
  971. time.sleep(3)
  972. # 14. 弹窗确认 Yes (formStep1:btnValiderModal)
  973. logger.info("[Application] 确认护照信息弹窗 (Yes)...")
  974. page.run_js("""
  975. let modalBtn = document.getElementById('formStep1:btnValiderModal');
  976. if (modalBtn) {
  977. modalBtn.click();
  978. } else {
  979. let btns = Array.from(document.querySelectorAll('.ui-dialog button'));
  980. let y = btns.find(b => b.innerText.trim().toLowerCase() === 'yes' || b.innerText.trim().toLowerCase() === 'oui');
  981. if (y) y.click();
  982. }
  983. """)
  984. time.sleep(4)
  985. # 15. 返回主页提取已生成的 FRA1 申请号
  986. logger.info("[Application] 正在从主页提取 FRA1 申请号...")
  987. page.get(urljoin(BASE_APP_URL, "accueil.xhtml"))
  988. time.sleep(3)
  989. accueil_html = page.html
  990. fra_matches = re.findall(r'\b(FRA\d[A-Z0-9_-]+)\b', accueil_html, re.I)
  991. unique_fra = list(dict.fromkeys([c.upper() for c in fra_matches]))
  992. fra1_number = unique_fra[0] if unique_fra else None
  993. # 提取申请组 ID (Group n°...)
  994. grp_match = re.search(r'Group\s+n[°o]?\s*(\d+)', accueil_html, re.I)
  995. group_id = grp_match.group(1) if grp_match else None
  996. logger.info(f"[Application] 提取结果 -> 申请组号: {group_id}, FRA1 申请号: {fra1_number}")
  997. return {
  998. "success": bool(fra1_number),
  999. "fra1_number": fra1_number,
  1000. "all_fra_codes": unique_fra,
  1001. "group_id": group_id,
  1002. "passport_number": passport_no,
  1003. "city": town,
  1004. "nationality": nationality
  1005. }
  1006. finally:
  1007. if own_page and page:
  1008. try:
  1009. page.quit()
  1010. except Exception:
  1011. pass
  1012. # ==========================================================================
  1013. # 6. 获取 FRA1 申请号 (Fetch FRA1 Application Numbers)
  1014. # ==========================================================================
  1015. def get_applications(self) -> List[Dict[str, Any]]:
  1016. """
  1017. 获取当前登录账号下所有的申请记录与 FRA1 申请号。
  1018. 解析 /fv-fo-dde/accueil.xhtml 页面中的表格及申请卡片数据。
  1019. """
  1020. if not self.logged_in:
  1021. raise RuntimeError("请先调用 login() 成功登录后再查询申请号!")
  1022. logger.info("[Fetch] 正在获取账号申请列表与 FRA1 申请号...")
  1023. accueil_url = urljoin(BASE_APP_URL, "accueil.xhtml")
  1024. resp = self._get(accueil_url)
  1025. html = resp.text
  1026. applications = []
  1027. soup = BeautifulSoup(html, "html.parser")
  1028. # 1. 查找所有符合 FRA1 规范的申请编号 (通常形如 FRA1xxxxxxxx 或 FRAxxxxxxxx)
  1029. fra_codes = re.findall(r'\b(FRA\d[A-Z0-9_-]+)\b', html, re.IGNORECASE)
  1030. unique_fra_codes = list(dict.fromkeys([c.upper() for c in fra_codes]))
  1031. # 2. 结构化解析主页申请表格或数据卡片
  1032. tables = soup.find_all("table")
  1033. for table in tables:
  1034. rows = table.find_all("tr")
  1035. headers = [th.get_text(strip=True) for th in rows[0].find_all(["th", "td"])] if rows else []
  1036. for row in rows[1:]:
  1037. cols = [td.get_text(strip=True) for td in row.find_all("td")]
  1038. if cols:
  1039. row_text = " ".join(cols)
  1040. fra_match = re.search(r'\b(FRA\d[A-Z0-9_-]+)\b', row_text, re.IGNORECASE)
  1041. if fra_match:
  1042. code = fra_match.group(1).upper()
  1043. applications.append({
  1044. "fra1_number": code,
  1045. "raw_columns": cols,
  1046. "headers": headers,
  1047. "summary": row_text
  1048. })
  1049. # 3. 如果在表格中没有独立解析出行,但正则匹配到了 FRA 编号,补充输出
  1050. existing_numbers = {app["fra1_number"] for app in applications}
  1051. for code in unique_fra_codes:
  1052. if code not in existing_numbers:
  1053. applications.append({
  1054. "fra1_number": code,
  1055. "status": "DETECTED_IN_PAGE",
  1056. "summary": f"Detected reference {code}"
  1057. })
  1058. logger.info(f"[Fetch] 共找到 {len(applications)} 条申请记录: {[a['fra1_number'] for a in applications]}")
  1059. return applications
  1060. # ==============================================================================
  1061. # 代理池与云端上报辅助函数
  1062. # ==============================================================================
  1063. def load_proxies(pool_name: str) -> List[Dict[str, Any]]:
  1064. """从 config/proxies.yaml 读取指定的代理池"""
  1065. config_path = os.path.join(ROOT_DIR, "config", "proxies.yaml")
  1066. if not os.path.exists(config_path):
  1067. return []
  1068. try:
  1069. with open(config_path, "r", encoding="utf-8") as f:
  1070. data = yaml.safe_load(f) or {}
  1071. nodes_list = data.get("nodes") or data.get("proxies") or []
  1072. nodes_map = {n["name"]: n for n in nodes_list if isinstance(n, dict) and "name" in n}
  1073. pools_data = data.get("pools", {}) if "pools" in data else data
  1074. clean_name = pool_name.replace("local:", "").strip() if pool_name else ""
  1075. raw_pool = pools_data.get(pool_name) or pools_data.get(clean_name)
  1076. if not raw_pool and clean_name:
  1077. raw_pool = pools_data.get(f"local_{clean_name}")
  1078. if not raw_pool:
  1079. raw_pool = pools_data.get("local", [])
  1080. proxies = []
  1081. for item in raw_pool:
  1082. if isinstance(item, str) and item in nodes_map:
  1083. proxies.append(nodes_map[item])
  1084. elif isinstance(item, dict):
  1085. proxies.append(item)
  1086. return proxies
  1087. except Exception as e:
  1088. logger.warning(f"读取 proxies.yaml 失败: {e}")
  1089. return []
  1090. def upload_account_to_server(
  1091. profile: Dict[str, Any],
  1092. pool_name: str,
  1093. api_token: str = "tok_e946329a60ff45ba807f3f41b0e8b7fc",
  1094. api_url: str = "https://api.text.skin/api/account/add"
  1095. ) -> bool:
  1096. """上报成功注册的账号至云端账号池"""
  1097. try:
  1098. headers = {
  1099. "Authorization": f"Bearer {api_token}",
  1100. "Content-Type": "application/json"
  1101. }
  1102. payload = {
  1103. "pool_name": pool_name,
  1104. "username": profile.get("username") or profile.get("email"),
  1105. "password": profile.get("password"),
  1106. "extra_data": profile
  1107. }
  1108. resp = requests.post(api_url, json=payload, headers=headers, timeout=10)
  1109. if resp.status_code == 200 and resp.json().get("code") == 0:
  1110. logger.info(f"账号已成功上传至云端账号池 [{pool_name}]")
  1111. return True
  1112. else:
  1113. logger.warning(f"账号上传云端失败: {resp.text}")
  1114. return False
  1115. except Exception as e:
  1116. logger.warning(f"上报账号异常: {e}")
  1117. return False
  1118. # ==============================================================================
  1119. # 一键自动注册全流程函数
  1120. # ==============================================================================
  1121. def auto_register(config: Optional[Union[Dict[str, Any], str]] = None, **kwargs) -> Dict[str, Any]:
  1122. """
  1123. 传入配置,一键全自动完成法签账号注册、激活、设密与登录验证全流程:
  1124. :param config: 配置字典或配置文件路径 (yaml/json)
  1125. :param kwargs: 覆盖参数
  1126. :return: 包含成功账号信息和登录凭证的字典
  1127. """
  1128. if isinstance(config, str) and os.path.exists(config):
  1129. with open(config, "r", encoding="utf-8") as f:
  1130. if config.endswith((".yaml", ".yml")):
  1131. raw = yaml.safe_load(f) or {}
  1132. else:
  1133. raw = json.load(f) or {}
  1134. if isinstance(raw, list) and len(raw) > 0:
  1135. cfg = raw[0] if isinstance(raw[0], dict) else {}
  1136. elif isinstance(raw, dict):
  1137. cfg = raw
  1138. else:
  1139. cfg = {}
  1140. elif isinstance(config, list) and len(config) > 0 and isinstance(config[0], dict):
  1141. cfg = dict(config[0])
  1142. elif isinstance(config, dict):
  1143. cfg = dict(config)
  1144. else:
  1145. cfg = {}
  1146. cfg.update(kwargs)
  1147. # 提取账号与配置信息 (兼容普通配置、sentinel配置及free_config)
  1148. account_info = cfg.get("account", {}) if isinstance(cfg.get("account"), dict) else {}
  1149. free_cfg = cfg.get("free_config", {}) if isinstance(cfg.get("free_config"), dict) else {}
  1150. sentinel_cfg = cfg.get("sentinel", {}) if isinstance(cfg.get("sentinel"), dict) else {}
  1151. email = (
  1152. cfg.get("email")
  1153. or cfg.get("username")
  1154. or account_info.get("username")
  1155. or account_info.get("email")
  1156. or free_cfg.get("email")
  1157. )
  1158. password = (
  1159. cfg.get("password")
  1160. or account_info.get("password")
  1161. or free_cfg.get("password")
  1162. )
  1163. # 自动生成邮箱 (默认 @text.skin)
  1164. if not email:
  1165. prefix = cfg.get("account_prefix") or cfg.get("prefix") or "fra"
  1166. domain = cfg.get("email_domain") or cfg.get("domain") or "text.skin"
  1167. rand_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
  1168. email = f"{prefix}_{rand_suffix}@{domain}"
  1169. # 自动生成强密码 (如 FraVis@829103!)
  1170. if not password:
  1171. rand_digits = random.randint(100000, 999999)
  1172. password = f"FraVis@{rand_digits}!"
  1173. first_name = cfg.get("first_name") or cfg.get("firstName") or free_cfg.get("first_name") or "Jerry"
  1174. last_name = cfg.get("last_name") or cfg.get("lastName") or free_cfg.get("last_name") or "Wang"
  1175. language = cfg.get("language") or free_cfg.get("language") or "English"
  1176. master_email = cfg.get("master_email") or free_cfg.get("master_email") or "hujiarui8@gmail.com"
  1177. email_api_token = cfg.get("email_token") or cfg.get("email_api_token")
  1178. account_pool = (
  1179. cfg.get("account_pool")
  1180. or cfg.get("pool_name")
  1181. or sentinel_cfg.get("account_pool_id")
  1182. )
  1183. output_file = cfg.get("output") or cfg.get("output_file") or os.path.join(ROOT_DIR, "data", "francevisa_accounts.txt")
  1184. max_retries = int(cfg.get("max_retries") or 3)
  1185. # 代理处理
  1186. proxy = cfg.get("proxy")
  1187. proxy_pool = cfg.get("proxy_pool")
  1188. if not proxy and proxy_pool:
  1189. pool_name = proxy_pool if isinstance(proxy_pool, str) else (proxy_pool[0] if isinstance(proxy_pool, list) else None)
  1190. if pool_name:
  1191. proxies = load_proxies(pool_name)
  1192. if proxies:
  1193. node = random.choice(proxies)
  1194. if isinstance(node, dict):
  1195. ip = node.get("ip") or node.get("server")
  1196. port = node.get("port")
  1197. proto = node.get("proto", "http")
  1198. user = node.get("user")
  1199. pwd = node.get("password")
  1200. if user and pwd:
  1201. proxy = f"{proto}://{user}:{pwd}@{ip}:{port}"
  1202. else:
  1203. proxy = f"{proto}://{ip}:{port}"
  1204. elif isinstance(node, str):
  1205. proxy = node
  1206. logger.info("=" * 60)
  1207. logger.info(">>> 开始法签申请账号一键自动化注册流程 <<<")
  1208. logger.info(f"账号邮箱: {email}")
  1209. logger.info(f"登录密码: {password}")
  1210. logger.info(f"接收邮箱: {master_email}")
  1211. logger.info(f"网络代理: {proxy or '直连'}")
  1212. logger.info("=" * 60)
  1213. client = FranceVisaKeygen(
  1214. proxy=proxy,
  1215. email_api_token=email_api_token,
  1216. master_email=master_email,
  1217. account_detail={"email": email, "password": password}
  1218. )
  1219. # 1. 账号注册
  1220. reg_success = False
  1221. for attempt in range(1, max_retries + 1):
  1222. try:
  1223. logger.info(f"[AutoRegister] 正在执行注册尝试 ({attempt}/{max_retries})...")
  1224. reg_res = client.register(
  1225. first_name=first_name,
  1226. last_name=last_name,
  1227. email=email,
  1228. language=language
  1229. )
  1230. if reg_res.get("success"):
  1231. reg_success = True
  1232. break
  1233. else:
  1234. logger.warning(f"[AutoRegister] 注册返回未完成: {reg_res.get('error')}")
  1235. except Exception as e:
  1236. logger.warning(f"[AutoRegister] 注册异常: {e}")
  1237. time.sleep(2)
  1238. if not reg_success:
  1239. raise BizLogicError(message=f"账号 {email} 注册失败,已达最大重试次数")
  1240. # 2. 邮箱验证激活
  1241. logger.info(f"[AutoRegister] 正在接收激活邮件并验证账号...")
  1242. client.activate(email=email)
  1243. # 3. 设定初始密码
  1244. logger.info(f"[AutoRegister] 正在接收重置邮件并设定登录密码...")
  1245. client.set_initial_password(email=email, password=password)
  1246. # 4. 登录验证探针
  1247. logger.info(f"[AutoRegister] 正在执行登录验证探针...")
  1248. login_ok = client.login(email, password)
  1249. if not login_ok:
  1250. raise BizLogicError(message=f"账号 {email} 注册并设密后登录验证失败!")
  1251. logger.info(f"🎉 账号 {email} 注册成功并已通过登录验证!")
  1252. profile = {
  1253. "email": email,
  1254. "username": email,
  1255. "password": password,
  1256. "first_name": first_name,
  1257. "last_name": last_name,
  1258. "language": language,
  1259. "status": "active",
  1260. "registered_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1261. }
  1262. # 5. 自动填表 (Step 1) 并获取 FRA1 申请编号
  1263. create_app = cfg.get("create_application", True)
  1264. if str(create_app).lower() not in ("false", "0", "no"):
  1265. try:
  1266. logger.info(f"[AutoRegister] 正在为账号 {email} 执行自动化填表并获取 FRA1 申请编号...")
  1267. app_res = client.fill_step1_and_create_application(applicant_data=cfg)
  1268. fra_code = app_res.get("fra1_number")
  1269. if fra_code:
  1270. profile["fra1_number"] = fra_code
  1271. profile["application_group"] = app_res.get("group_id")
  1272. profile["passport_number"] = app_res.get("passport_number")
  1273. profile["city"] = app_res.get("city")
  1274. logger.info(f"🎉 成功生成并获取到 FRA1 申请号: {fra_code}")
  1275. else:
  1276. logger.warning("[AutoRegister] 填表完成但未在页面提取到有效 FRA1 编号")
  1277. except Exception as e:
  1278. logger.warning(f"[AutoRegister] 自动填表获取 FRA1 异常: {e}")
  1279. # 6. 持久化记录
  1280. try:
  1281. os.makedirs(os.path.dirname(os.path.abspath(output_file)), exist_ok=True)
  1282. fra_val = profile.get("fra1_number") or "N/A"
  1283. line = f"{email}----{password}----{fra_val}----{first_name} {last_name}----{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
  1284. with open(output_file, "a", encoding="utf-8") as f:
  1285. f.write(line)
  1286. json_path = os.path.splitext(output_file)[0] + ".json"
  1287. all_accounts = []
  1288. if os.path.exists(json_path):
  1289. try:
  1290. with open(json_path, "r", encoding="utf-8") as f:
  1291. all_accounts = json.load(f)
  1292. except Exception:
  1293. all_accounts = []
  1294. all_accounts.append(profile)
  1295. with open(json_path, "w", encoding="utf-8") as f:
  1296. json.dump(all_accounts, f, indent=2, ensure_ascii=False)
  1297. logger.info(f"账号凭证已写入: {output_file} & {json_path}")
  1298. except Exception as e:
  1299. logger.warning(f"保存账号文件失败: {e}")
  1300. # 7. 上报云端账号池
  1301. if account_pool:
  1302. upload_account_to_server(profile, pool_name=account_pool)
  1303. return profile
  1304. # ==============================================================================
  1305. # 命令行交互与测试入口
  1306. # ==============================================================================
  1307. def main(config: Optional[Union[Dict[str, Any], str]] = None) -> Optional[Dict[str, Any]]:
  1308. """
  1309. 主入口:执行 France-Visas (法签申请表) 账号全自动注册与填表生成 FRA1 申请号。
  1310. 1. 支持代码内调用传参:传入 config 字典或 YAML/JSON 配置文件路径;
  1311. 2. 支持命令行直接执行:所有注册与填表所需参数(邮箱、密码、姓名、代理、邮箱API、账号池、护照号、城市等)均可直接通过命令行传入。
  1312. """
  1313. if config is not None:
  1314. result = auto_register(config)
  1315. print(json.dumps(result, indent=2, ensure_ascii=False))
  1316. return result
  1317. parser = argparse.ArgumentParser(
  1318. description="France-Visas (法签申请表) 账号一键自动注册与填表工具 - 命令行参数直传模式"
  1319. )
  1320. # 配置文件 (可选,可与命令行参数叠加)
  1321. parser.add_argument("--config", "-c", type=str, default=None, help="配置文件路径 (YAML 或 JSON)")
  1322. # 账号与身份信息
  1323. parser.add_argument("--email", type=str, default=None, help="账号邮箱 (不指定则自动生成)")
  1324. parser.add_argument("--password", type=str, default=None, help="账号密码 (不指定则自动生成强密码)")
  1325. parser.add_argument("--first-name", type=str, default=None, help="名字 (默认 Jerry)")
  1326. parser.add_argument("--last-name", type=str, default=None, help="姓氏 (默认 Wang)")
  1327. parser.add_argument("--language", type=str, default=None, help="界面语言 (默认 English)")
  1328. parser.add_argument("--prefix", "--account-prefix", dest="prefix", type=str, default=None, help="自动生成邮箱的前缀 (默认 fra)")
  1329. parser.add_argument("--domain", "--email-domain", dest="domain", type=str, default=None, help="自动生成邮箱的域名 (默认 text.skin)")
  1330. # 邮件接收与验证 API
  1331. parser.add_argument("--master-email", type=str, default=None, help="接收验证与设密邮件的主邮箱 (默认 hujiarui8@gmail.com)")
  1332. parser.add_argument("--email-token", type=str, default=None, help="邮箱 API Token")
  1333. # 网络代理与账号池
  1334. parser.add_argument("--proxy", type=str, default=None, help="指定网络代理 (如 http://127.0.0.1:7897)")
  1335. parser.add_argument("--proxy-pool", type=str, default=None, help="代理池名称 (在 proxies.yaml 中定义,如 local)")
  1336. parser.add_argument("--account-pool", type=str, default=None, help="注册成功后上报的云端账号池名称")
  1337. # 填表与 FRA1 申请号参数
  1338. parser.add_argument("--create-app", "--fill-form", dest="create_application", action="store_true", default=True, help="注册后是否自动填表并获取 FRA1 申请号 (默认开启)")
  1339. parser.add_argument("--no-create-app", dest="create_application", action="store_false", help="仅注册账号,不进行填表获取 FRA1")
  1340. parser.add_argument("--nationality", type=str, default="CHN", help="国籍代码 (默认 CHN)")
  1341. parser.add_argument("--has-family", dest="has_family", action="store_true", default=False, help="是否有欧盟/欧洲经济区亲属 (默认 False)")
  1342. parser.add_argument("--deposit-country", type=str, default="CHN", help="递签国家代码 (默认 CHN)")
  1343. parser.add_argument("--stay-duration", type=str, default="C", help="停留期限: C(短期<=90天), D(长期>90天), A(机场过境) (默认 C)")
  1344. parser.add_argument("--destination", type=str, default="MET", help="主目的地: MET(法国本土) (默认 MET)")
  1345. parser.add_argument("--city", "--town", dest="city", type=str, default="1PE", help="递签城市代码: 1PE(北京), 1CB(广州), 1SH(上海), 1CA(成都), 1WU(武汉)等 (默认 1PE)")
  1346. parser.add_argument("--authority", type=str, default="CHN", help="护照签发国代码 (默认 CHN)")
  1347. parser.add_argument("--doc-type", type=str, default="10", help="证件类型: 10(普通护照), 30(外交护照), 40(公务护照) (默认 10)")
  1348. parser.add_argument("--passport-number", "--passport-no", dest="passport_number", type=str, default=None, help="填表护照号 (默认自动生成 E+8位随机数字)")
  1349. parser.add_argument("--release-date", type=str, default="01/01/2022", help="护照签发日期 DD/MM/YYYY (默认 01/01/2022)")
  1350. parser.add_argument("--expiration-date", type=str, default="01/01/2032", help="护照失效日期 DD/MM/YYYY (默认 01/01/2032)")
  1351. parser.add_argument("--purpose-category", type=str, default="TOUR", help="签证主目的: TOUR(旅游), VISF(探亲), ETUD(留学), TRAV(商务) (默认 TOUR)")
  1352. parser.add_argument("--purpose", type=str, default=None, help="签证目的子项编号: 134(欧盟家属旅游), 1(个人旅游)等 (默认自动选用)")
  1353. # 运行与存储选项
  1354. parser.add_argument("--output", "-o", type=str, default=None, help="账号本地保存文件路径 (默认 data/francevisa_accounts.txt)")
  1355. parser.add_argument("--max-retries", type=int, default=None, help="验证码或网络失败时的最大重试次数 (默认 3)")
  1356. args = parser.parse_args()
  1357. # 读取配置文件(如果提供)
  1358. cfg: Dict[str, Any] = {}
  1359. if args.config:
  1360. if os.path.exists(args.config):
  1361. with open(args.config, "r", encoding="utf-8") as f:
  1362. if args.config.endswith((".yaml", ".yml")):
  1363. raw = yaml.safe_load(f) or {}
  1364. else:
  1365. raw = json.load(f) or {}
  1366. if isinstance(raw, list) and len(raw) > 0 and isinstance(raw[0], dict):
  1367. cfg = raw[0]
  1368. elif isinstance(raw, dict):
  1369. cfg = raw
  1370. else:
  1371. logger.warning(f"指定配置文件不存在: {args.config}")
  1372. # 提取命令行中显式传入的有效参数(过滤掉 None 和 config 参数)
  1373. cli_params = {k: v for k, v in vars(args).items() if v is not None and k != "config"}
  1374. cfg.update(cli_params)
  1375. # 执行全自动注册与填表全流程
  1376. result = auto_register(cfg)
  1377. print(json.dumps(result, indent=2, ensure_ascii=False))
  1378. return result
  1379. if __name__ == "__main__":
  1380. main()