| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- France-Visas (法签申请表系统) 自动化 Keygen / 协议客户端
- Target URL: https://application-form.france-visas.gouv.fr/fv-fo-dde/
- Authentication Realm: Keycloak Usager (https://connect.france-visas.gouv.fr/realms/usager)
- 核心功能:
- 1. 账号注册 (Registration) - 访问 OAuth 注册页,填写基本信息并提交验证码,触发邮箱验证
- 2. 获取激活邮件与验证 (Email Activation) - 预留空壳/API 钩子,支持自动提取并访问 action-token 完成激活
- 3. 重置与设置密码 (Reset / Set Password) - 申请重置密码、读取邮件中的更新密码 token 并提交新密码
- 4. 账号登录 (Login) - 完整 OAuth2 / OpenID Connect 授权登录与会话保持 (JSESSIONID)
- 5. 填表与新建申请 (Application Creation) - 基于 Jakarta Faces (JSF) 状态机创建申请组/表单
- 6. 获取 FRA1 申请号 (Fetch FRA1 Application Reference) - 解析用户主页,提取已生成的所有 FRA1 申请号及状态
- 7. 验证码空壳/扩展钩子 (Captcha Hook) - 内置 ddddocr 识别支持,并提供自定义回调/空壳函数
- """
- import os
- import re
- import sys
- import json
- import time
- import uuid
- import base64
- import yaml
- import random
- import string
- import logging
- import argparse
- from datetime import datetime, timezone, timedelta
- from typing import Optional, Dict, Any, List, Tuple, Union
- from urllib.parse import urljoin, urlparse, parse_qs, unquote
- ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
- # 解决 Windows GBK 终端乱码问题
- if sys.platform == "win32":
- try:
- sys.stdout.reconfigure(encoding="utf-8")
- sys.stderr.reconfigure(encoding="utf-8")
- except Exception:
- pass
- from curl_cffi import requests
- from bs4 import BeautifulSoup
- from DrissionPage import ChromiumPage, ChromiumOptions
- from toolkit.captcha_breaker import CaptchaBreaker
- from toolkit.cloud_api import CloudApi
- from core_types import BizLogicError
- # ==============================================================================
- # 日志配置
- # ==============================================================================
- logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s [%(levelname)s] %(message)s',
- datefmt='%H:%M:%S'
- )
- logger = logging.getLogger("FranceVisa-Keygen")
- # ==============================================================================
- # 常量定义
- # ==============================================================================
- BASE_APP_URL = "https://application-form.france-visas.gouv.fr/fv-fo-dde/"
- BASE_AUTH_URL = "https://connect.france-visas.gouv.fr"
- CLIENT_ID = "fv-fo-keycloak-web"
- DEFAULT_USER_AGENT = (
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
- "AppleWebKit/537.36 (KHTML, like Gecko) "
- "Chrome/128.0.0.0 Safari/537.36"
- )
- DEFAULT_HEADERS = {
- "User-Agent": DEFAULT_USER_AGENT,
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
- "Accept-Language": "en-US,en;q=0.9,fr;q=0.8",
- "Sec-Ch-Ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
- "Sec-Ch-Ua-Mobile": "?0",
- "Sec-Ch-Ua-Platform": '"Windows"',
- }
- # ==============================================================================
- # FranceVisaKeygen 核心客户端
- # ==============================================================================
- class FranceVisaKeygen:
- def __init__(
- self,
- proxy: Optional[str] = None,
- email_api_token: Optional[str] = None,
- master_email: Optional[str] = "hujiarui8@gmail.com",
- account_detail: Optional[Dict[str, Any]] = None,
- page: Optional[Any] = None,
- timeout: int = 20
- ):
- """
- :param proxy: 代理地址,例如 'http://127.0.0.1:7890' 或 'socks5://127.0.0.1:1080'
- :param email_api_token: 邮箱 API Token (如 text.skin),若无则使用空壳/交互输入
- :param master_email: 主接收邮箱地址 (默认 'hujiarui8@gmail.com')
- :param account_detail: 账号信息字典 (包含 'email', 'password' 等)
- :param page: DrissionPage 浏览器页面实例 (可选)
- :param timeout: 请求超时秒数
- """
- self.proxy = proxy
- self.email_api_token = email_api_token
- self.master_email = master_email or "hujiarui8@gmail.com"
- self.account_detail = account_detail or {}
- self.page = page
- self.timeout = timeout
-
- self.session = self._init_session()
- self.logged_in = False
- self.current_user = self.account_detail.get("email")
-
- # JSF 状态缓存
- self.last_view_state: Optional[str] = None
- self.last_csrf_token: Optional[str] = None
- # 大模型验证码识别器
- self.captcha_breaker = CaptchaBreaker()
- def _log(self, msg: str):
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- logger.info(f"[{now}] {msg}")
- def _init_session(self):
- """初始化 HTTP 会话,使用 curl_cffi 模拟 Chrome 浏览器指纹"""
- session = requests.Session(impersonate="chrome120")
- if self.proxy:
- session.proxies = {
- "http": self.proxy,
- "https": self.proxy,
- }
- return session
- def _get(self, url: str, **kwargs) -> Any:
- """带默认头部和超时的 GET 请求"""
- kwargs.setdefault("timeout", self.timeout)
- headers = kwargs.pop("headers", {})
- merged_headers = dict(DEFAULT_HEADERS)
- merged_headers.update(headers)
- return self.session.get(url, headers=merged_headers, **kwargs)
- def _post(self, url: str, data: Any = None, **kwargs) -> Any:
- """带默认头部和超时的 POST 请求"""
- kwargs.setdefault("timeout", self.timeout)
- headers = kwargs.pop("headers", {})
- merged_headers = dict(DEFAULT_HEADERS)
- merged_headers.update(headers)
- return self.session.post(url, data=data, headers=merged_headers, **kwargs)
- # ==========================================================================
- # 验证码处理 (使用 toolkit.captcha_breaker.CaptchaBreaker)
- # ==========================================================================
- def solve_captcha(
- self,
- image_bytes: Optional[bytes] = None,
- image_b64: Optional[str] = None,
- uuid_str: Optional[str] = None
- ) -> str:
- """
- 图像验证码识别函数。
- 使用 toolkit.captcha_breaker.CaptchaBreaker 多模态视觉大模型进行识别。
- 如果获取不了验证码图片或识别失败,调用空壳占位生成函数。
- """
- image_input = image_bytes or image_b64
- if image_input:
- try:
- breaker = getattr(self, "captcha_breaker", None) or CaptchaBreaker()
- result = breaker.break_captcha(
- image_input,
- prompt="请识别图片中的4-6位英文字母或数字验证码,只输出验证码本身的内容,不要任何空格、标点或额外文字。"
- )
- if result:
- clean_res = re.sub(r'[^a-zA-Z0-9]', '', result).lower()
- logger.info(f"[Captcha] CaptchaBreaker 识别结果: {clean_res}")
- return clean_res
- except Exception as e:
- logger.warning(f"[Captcha] CaptchaBreaker 识别出错: {e}")
- # 空壳函数备用逻辑:允许外部配置回调或返回模拟/占位
- logger.warning("[Captcha] 未获取到有效图片数据或识别失败,调用空壳占位验证码函数")
- # 占位生成 4 位伪随机码或固定测试码
- return ''.join(random.choices(string.ascii_lowercase + string.digits, k=4))
- def fetch_captcha_image(self, referer_url: str) -> Tuple[Optional[str], Optional[bytes], str]:
- """
- 从 Keycloak captchaEndpoint 拉取验证码图片数据与 UUID。
- 实际接口路径为 /fv-fo-captcha-rest/v2/simple-captcha-endpoint
- """
- captcha_url = f"{BASE_AUTH_URL}/fv-fo-captcha-rest/v2/simple-captcha-endpoint?get=image&c=alphanumerique4to6LightCaptchaFR"
- headers = {
- "Accept": "application/json, text/plain, */*",
- "Referer": referer_url,
- "Sec-Fetch-Dest": "empty",
- "Sec-Fetch-Mode": "cors",
- "Sec-Fetch-Site": "same-origin",
- }
-
- uuid_str = str(uuid.uuid4())
- try:
- resp = self._get(captcha_url, headers=headers)
- if resp.status_code == 200:
- data = resp.json()
- captcha_uuid = data.get("uuid", uuid_str)
- img_b64 = data.get("imageb64", "")
- logger.info(f"[Captcha] 成功获取验证码图片及 UUID: {captcha_uuid}")
- return captcha_uuid, None, img_b64
- else:
- logger.warning(f"[Captcha] 拉取验证码接口状态异常: {resp.status_code}")
- except Exception as e:
- logger.warning(f"[Captcha] 拉取验证码异常: {e}")
- return uuid_str, None, ""
- # ==========================================================================
- # 邮件获取与激活处理 (基于 CloudApi fetch_mail_content_from_top 轮询,防 504)
- # ==========================================================================
- def fetch_email_link(
- self,
- email: str,
- token_type: str = "verify-email",
- max_wait_seconds: int = 90,
- poll_interval: int = 3
- ) -> str:
- """
- 从 CloudApi 邮箱中提取指定账号的 action-token 验证或重置链接。
- 解码 JWT 负载核对 typ (verify-email 或 reset-credentials) 与 eml,防止混淆。
- 采用 fetch_mail_content_from_top 轮询机制,避免长轮询超时 504。
- """
- email_box = self.master_email or 'hujiarui8@gmail.com'
- self._log(f"正在通过 CloudApi 轮询 {email_box} 获取收件人 {email} 的邮件 (期望类型: {token_type})...")
- def _decode_jwt(link_str: str) -> Dict[str, Any]:
- m = re.search(r'key(?:=|=|=)([a-zA-Z0-9_\-\.]+)', link_str)
- if not m:
- return {}
- parts = m.group(1).split('.')
- if len(parts) >= 2:
- payload_b64 = parts[1]
- payload_b64 += '=' * ((4 - len(payload_b64) % 4) % 4)
- try:
- return json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8', errors='ignore'))
- except Exception:
- return {}
- return {}
- start_time = time.time()
- while time.time() - start_time < max_wait_seconds:
- try:
- content = CloudApi.Instance().fetch_mail_content_from_top(
- email=email_box,
- sender="",
- recipient=email,
- subject_keywords="",
- body_keywords="",
- top=10
- )
- if content:
- matches = re.findall(r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token[^\s"\'>]+', content)
- for m in matches:
- clean_link = m.replace('&#61;', '=').replace('=', '=').replace('&', '&').rstrip('"\'>.,;')
- jwt_data = _decode_jwt(clean_link)
- typ = jwt_data.get('typ', '')
- eml = jwt_data.get('eml', '')
- # 严格核对收件人与 token 类型
- if eml and eml.lower() != email.lower():
- continue
- if token_type == "verify-email" and typ == "verify-email":
- self._log(f"成功匹配到激活邮件链接: {clean_link}")
- return clean_link
- elif token_type in ("reset-credentials", "UPDATE_PASSWORD") and typ in ("reset-credentials", "UPDATE_PASSWORD"):
- self._log(f"成功匹配到密码重置邮件链接: {clean_link}")
- return clean_link
- elif not token_type:
- return clean_link
- except Exception as e:
- self._log(f"轮询邮件返回: {e}")
- time.sleep(poll_interval)
- # 兜底尝试原生 fetch_mail_content
- try:
- content_out = CloudApi.Instance().fetch_mail_content(
- email=email_box,
- sender="",
- recipient=email,
- subject_keywords="",
- body_keywords="",
- sent_date=(datetime.now(timezone.utc) - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S"),
- expiry=30
- )
- match = re.search(r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token[^\s"\'>]+', content_out or "")
- if match:
- return match.group(0).replace('&', '&').rstrip('"\'>.,;')
- except Exception:
- pass
- raise BizLogicError(message=f"等待账号 {email} 的邮件超时 (期望类型: {token_type})")
- def activate(self, sent_at: Optional[str] = None, email: Optional[str] = None) -> bool:
- """
- 激活账号邮件:
- 使用 CloudApi 轮询拉取邮件并提取激活链接,访问链接完成激活
- """
- email = email or (self.account_detail.get('email') if self.account_detail else None) or self.current_user
- if not email:
- raise ValueError("必须提供待激活账号的 email 或在 account_detail 中预设")
- activate_link = self.fetch_email_link(email=email, token_type="verify-email")
- self._log(f"成功获取激活链接: {activate_link}")
-
- # 若传入了 DrissionPage 浏览器页面实例,则通过浏览器访问并点击激活按钮
- if hasattr(self, 'page') and self.page is not None:
- self.page.get(activate_link)
- btn_selector = "#activation-pending-button"
- if hasattr(self.page, 'wait') and self.page.wait.ele_displayed(btn_selector, timeout=10):
- self.page.ele(btn_selector).click()
- time.sleep(3)
- return True
- else:
- # 纯协议极速激活
- resp = self._get(activate_link, allow_redirects=True)
- self._log(f"协议访问激活链接响应码: {resp.status_code}")
- return resp.status_code in (200, 302)
- def fetch_activation_link(self, email: str, max_wait_sec: int = 60) -> Optional[str]:
- """
- 空壳函数:获取激活邮件中的验证链接。
- 如系统支持 text.skin API,将尝试调用云端接口轮询;
- 若无配置,则提示用户或返回 None。
- """
- logger.info(f"[Email-Stub] 正在等待/获取 {email} 的激活邮件...")
- # 如果配置了 text.skin 邮箱服务 API,则自动轮询读取
- if self.email_api_token:
- api_url = "https://api.text.skin/api/email-authorizations/fetch"
- headers = {
- "Authorization": f"Bearer {self.email_api_token}",
- "Content-Type": "application/json"
- }
- start_time = time.time()
- while time.time() - start_time < max_wait_sec:
- try:
- params = {
- "recipient": email,
- "subjectKeywords": "France-Visas",
- "bodyKeywords": "action-token",
- "expiry": str(max_wait_sec)
- }
- if self.master_email:
- params["email"] = self.master_email
- resp = requests.post(api_url, headers=headers, params=params, json={}, timeout=10)
- if resp.status_code == 200:
- data = resp.json()
- body = data.get("data", {}).get("body", "")
- if body:
- match = re.search(
- r'https?://connect\.france-visas\.gouv\.fr[^\s"\'>]+action-token\?key=[^\s"\'>]+',
- body
- )
- if match:
- link = match.group(0).replace("&", "&")
- logger.info(f"[Email] 从 text.skin 成功获取激活链接: {link}")
- return link
- except Exception as e:
- logger.debug(f"[Email] 轮询异常: {e}")
- time.sleep(3)
- logger.warning(f"[Email-Stub] 空壳函数未获取到自动激活邮件,请手动传入 action-token 链接。")
- return None
- def fetch_password_reset_link(self, email: str, max_wait_sec: int = 60) -> Optional[str]:
- """
- 空壳函数:获取密码重置邮件中的 action-token 链接。
- """
- logger.info(f"[Email-Stub] 正在等待/获取 {email} 的重置密码邮件...")
- # 与 fetch_activation_link 类似,使用相同格式的 action-token
- return self.fetch_activation_link(email, max_wait_sec=max_wait_sec)
- # ==========================================================================
- # 1. 注册功能 (Registration)
- # ==========================================================================
- def register(
- self,
- first_name: str,
- last_name: str,
- email: str,
- language: str = "English",
- captcha_code: Optional[str] = None,
- captcha_uuid: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- 注册法签申请账号:
- 1. 访问首页并跳转至 Keycloak 认证页
- 2. 获取注册页 URL (registrationUrl) 并拉取表单上下文
- 3. 获取/计算验证码及 captchetat-uuid
- 4. 提交注册 POST 请求
- """
- logger.info(f"[Register] 开始注册账号: {email} ({first_name} {last_name})")
-
- # Step 1: 访问主站以进入 Keycloak OAuth 授权流
- resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
- login_html = resp_entry.text
- # 从页面提取 registrationUrl
- reg_match = re.search(r'"registrationUrl":\s*"([^"]+)"', login_html)
- if not reg_match:
- # 兼容 HTML a 标签
- soup = BeautifulSoup(login_html, "html.parser")
- a_tag = soup.find("a", href=lambda h: h and "registration" in h)
- if a_tag:
- reg_url = urljoin(resp_entry.url, a_tag["href"])
- else:
- raise RuntimeError("未能从登录页解析出注册地址 (registrationUrl)")
- else:
- reg_url = urljoin(resp_entry.url, reg_match.group(1).replace(r"\/", "/"))
- logger.info(f"[Register] 打开注册表单页: {reg_url}")
- resp_reg = self._get(reg_url)
- reg_html = resp_reg.text
- # Step 2: 提取注册表单 action (包含 session_code, execution 等参数)
- action_match = re.search(r'"registrationAction":\s*"([^"]+)"', reg_html)
- if not action_match:
- soup = BeautifulSoup(reg_html, "html.parser")
- form = soup.find("form", id="kc-register-form") or soup.find("form")
- if form and form.get("action"):
- action_url = urljoin(resp_reg.url, form["action"])
- else:
- action_url = reg_url
- else:
- action_url = action_match.group(1).replace(r"\/", "/")
- logger.info(f"[Register] 注册表单 Action: {action_url}")
- # Step 3: 获取验证码与 UUID
- if not captcha_uuid or not captcha_code:
- fetched_uuid, _, img_b64 = self.fetch_captcha_image(referer_url=reg_url)
- captcha_uuid = captcha_uuid or fetched_uuid
- if not captcha_code:
- captcha_code = self.solve_captcha(image_b64=img_b64, uuid_str=captcha_uuid)
- # Step 4: 构造 POST 负载提交注册
- payload = {
- "lastName": last_name,
- "firstName": first_name,
- "email": email,
- "emailVerif": email,
- "ddeLanguage": language,
- "captchaFormulaireExtInput": captcha_code,
- "captchetat-uuid": captcha_uuid
- }
- headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- "Origin": BASE_AUTH_URL,
- "Referer": reg_url
- }
- logger.info(f"[Register] 提交注册信息 (Captcha: {captcha_code}, UUID: {captcha_uuid})")
- resp_submit = self._post(action_url, data=payload, headers=headers, allow_redirects=False)
- # Keycloak 成功注册后会重定向至 required-action?execution=VERIFY_EMAIL
- location = resp_submit.headers.get("Location", "")
- if resp_submit.status_code in (302, 303) and "VERIFY_EMAIL" in location:
- logger.info(f"[Register] 注册成功!已触发邮箱验证邮件,重定向目标: {location}")
- # 请求提示页以确认验证状态
- self._get(urljoin(action_url, location))
- return {
- "success": True,
- "email": email,
- "status": "PENDING_EMAIL_VERIFICATION",
- "verify_url": location
- }
- elif resp_submit.status_code == 200:
- # 留在原页面通常代表验证码错误或字段校验失败
- soup = BeautifulSoup(resp_submit.text, "html.parser")
- err_alert = soup.find(class_=lambda c: c and any(x in c.lower() for x in ["error", "alert", "feedback"]))
- err_msg = err_alert.get_text(strip=True) if err_alert else "注册未通过(可能是验证码或邮箱已存在)"
- logger.warning(f"[Register] 提交响应未重定向: {err_msg}")
- return {
- "success": False,
- "email": email,
- "error": err_msg,
- "html_snippet": resp_submit.text[:500]
- }
- else:
- logger.info(f"[Register] 响应状态码: {resp_submit.status_code}, Location: {location}")
- return {
- "success": resp_submit.status_code in (200, 302),
- "email": email,
- "status_code": resp_submit.status_code,
- "location": location
- }
- # ==========================================================================
- # 2. 邮箱验证激活 (Verify Email via Token)
- # ==========================================================================
- def verify_email(self, action_token_url_or_key: str) -> bool:
- """
- 通过 action-token 链接激活邮箱。
- :param action_token_url_or_key: 完整的 action-token URL 或其中的 JWT key
- """
- if "action-token?key=" in action_token_url_or_key:
- url = action_token_url_or_key
- else:
- url = f"{BASE_AUTH_URL}/realms/usager/login-actions/action-token?key={action_token_url_or_key}&client_id={CLIENT_ID}"
- logger.info(f"[VerifyEmail] 正在访问激活链接: {url[:100]}...")
- resp = self._get(url, allow_redirects=True)
- if resp.status_code in (200, 302):
- logger.info("[VerifyEmail] 邮箱激活请求完成!")
- return True
- else:
- logger.error(f"[VerifyEmail] 激活失败,HTTP 状态码: {resp.status_code}")
- return False
- # ==========================================================================
- # 3. 重置/设置密码 (Reset / Set Password)
- # ==========================================================================
- def request_password_reset(
- self,
- email: str,
- captcha_code: Optional[str] = None,
- captcha_uuid: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- 申请密码重置邮件:
- 1. 获取 reset-credentials 页面
- 2. 填写邮箱与验证码
- 3. 提交后系统向邮箱发送 UPDATE_PASSWORD token 邮件
- """
- logger.info(f"[ResetPassword] 正在申请重置密码: {email}")
-
- # 获取重置密码入口
- resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
- reset_match = re.search(r'"loginResetCredentialsUrl":\s*"([^"]+)"', resp_entry.text)
- if reset_match:
- reset_url = urljoin(resp_entry.url, reset_match.group(1).replace(r"\/", "/"))
- else:
- reset_url = f"{BASE_AUTH_URL}/realms/usager/login-actions/reset-credentials?client_id={CLIENT_ID}"
- resp_reset = self._get(reset_url)
- reset_html = resp_reset.text
- # 提取表单 action
- action_match = re.search(r'"loginAction":\s*"([^"]+)"', reset_html) or re.search(r'action=["\']([^"\']+)["\']', reset_html)
- action_url = action_match.group(1).replace(r"\/", "/") if action_match else reset_url
- if not action_url.startswith("http"):
- action_url = urljoin(resp_reset.url, action_url)
- # 获取/计算验证码
- if not captcha_uuid or not captcha_code:
- fetched_uuid, _, img_b64 = self.fetch_captcha_image(referer_url=reset_url)
- captcha_uuid = captcha_uuid or fetched_uuid
- if not captcha_code:
- captcha_code = self.solve_captcha(image_b64=img_b64, uuid_str=captcha_uuid)
- payload = {
- "username": email,
- "captchaFormulaireExtInput": captcha_code,
- "captchetat-uuid": captcha_uuid
- }
- headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- "Origin": BASE_AUTH_URL,
- "Referer": reset_url
- }
- logger.info(f"[ResetPassword] 提交重置申请 (Captcha: {captcha_code}, UUID: {captcha_uuid})")
- resp_submit = self._post(action_url, data=payload, headers=headers)
- if resp_submit.status_code == 200:
- # 校验 Keycloak 响应中是否有错误提示 (防验证码识别偏差导致误判为成功)
- m_ctx = re.search(r'kcContext\s*=\s*(\{.+?\});', resp_submit.text, re.DOTALL)
- is_error = False
- err_msg = ""
- if m_ctx:
- ctx_str = m_ctx.group(1)
- if re.search(r'"type":\s*"error"|"error":\s*true', ctx_str):
- is_error = True
- m_summary = re.search(r'"summary":\s*"([^"]+)"', ctx_str)
- err_msg = m_summary.group(1) if m_summary else "验证码识别不匹配"
- soup = BeautifulSoup(resp_submit.text, "html.parser")
- err_alert = soup.find(class_=lambda c: c and any(x in str(c).lower() for x in ["error", "alert", "feedback"]))
- if err_alert and not is_error:
- txt = err_alert.get_text(strip=True)
- if txt and len(txt) > 3:
- is_error = True
- err_msg = txt
- if is_error:
- logger.warning(f"[ResetPassword] 重置申请未通过 (将自动重试): {err_msg}")
- return {"success": False, "error": err_msg}
- logger.info("[ResetPassword] 重置请求已提交,邮件已发送!")
- return {"success": True, "email": email}
- else:
- logger.warning(f"[ResetPassword] 提交响应码: {resp_submit.status_code}")
- return {"success": False, "status_code": resp_submit.status_code}
- def complete_password_reset(self, action_token_url_or_key: str, new_password: str) -> bool:
- """
- 通过邮件中的 action-token 完成重置并设定新密码:
- 1. 访问 action-token 链接 -> 跟随重定向至 required-action?execution=UPDATE_PASSWORD
- 2. 从 kcContext 中提取真实的 loginAction URL (包含 session_code)
- 3. 提交 password-new 与 password-confirm 完成更新
- """
- logger.info("[ResetPassword] 正在执行重置密码最终设定...")
- if "action-token?key=" in action_token_url_or_key:
- token_url = action_token_url_or_key
- else:
- 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}"
- # 访问 token URL,通常会经过 302 重定向到 required-action 页面
- resp_token = self._get(token_url, allow_redirects=True)
- form_html = resp_token.text
- pwd_form_url = resp_token.url
- # 从 kcContext 中提取真实的 loginAction URL (包含 session_code, execution=UPDATE_PASSWORD)
- action_match = (
- re.search(r'"loginAction":\s*"([^"]+)"', form_html)
- or re.search(r'"registrationAction":\s*"([^"]+)"', form_html)
- or re.search(r'action=["\']([^"\']+)["\']', form_html)
- )
- if action_match:
- action_url = action_match.group(1).replace(r"\/", "/").replace("&", "&")
- if not action_url.startswith("http"):
- action_url = urljoin(pwd_form_url, action_url)
- else:
- action_url = pwd_form_url
- payload = {
- "password-new": new_password,
- "password-confirm": new_password
- }
- headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- "Origin": BASE_AUTH_URL,
- "Referer": pwd_form_url
- }
- logger.info(f"[ResetPassword] 正在向 {action_url} 提交新密码...")
- resp_pwd = self._post(action_url, data=payload, headers=headers, allow_redirects=False)
-
- # 成功更新密码后,Keycloak 通常返回 302 重定向到前端或返回无错误的确认页面
- if resp_pwd.status_code in (302, 303):
- logger.info("[ResetPassword] 密码重置成功 (302 Redirect)!")
- return True
- elif resp_pwd.status_code == 200:
- # 检查是否有错误提示
- soup = BeautifulSoup(resp_pwd.text, "html.parser")
- err = soup.find(class_=lambda c: c and any(x in str(c).lower() for x in ["error", "alert", "feedback"]))
- if err:
- logger.error(f"[ResetPassword] 密码重置未通过: {err.get_text(strip=True)}")
- return False
- logger.info("[ResetPassword] 密码重置成功!")
- return True
- else:
- logger.error(f"[ResetPassword] 提交密码失败,状态码: {resp_pwd.status_code}")
- return False
- def set_initial_password(self, email: str, password: str, max_retries: int = 3) -> bool:
- """
- 为新注册的账号设置初始密码:
- 1. 申请重置密码(利用 CaptchaBreaker 破解验证码)
- 2. 通过 CloudApi 轮询接收包含 UPDATE_PASSWORD 的 action-token 邮件
- 3. 提交 password-new 与 password-confirm 完成设定
- """
- self._log(f"开始为账号 {email} 设定初始登录密码...")
-
- # 1. 提交重置密码申请 (如遇验证码识别失败自动重试)
- reset_ok = False
- for attempt in range(1, max_retries + 1):
- try:
- reset_req = self.request_password_reset(email)
- if reset_req.get("success"):
- reset_ok = True
- break
- except Exception as e:
- self._log(f"密码重置申请第 {attempt} 次失败: {e}")
- time.sleep(2)
- if not reset_ok:
- raise BizLogicError(message=f"账号 {email} 申请密码重置失败")
-
- # 2. 等待重置邮件
- self._log(f"正在通过 CloudApi 等待密码重置邮件...")
- reset_link = self.fetch_email_link(email=email, token_type="reset-credentials")
- self._log(f"成功获取重置链接: {reset_link}")
- # 3. 提交新密码
- return self.complete_password_reset(reset_link, password)
- # ==========================================================================
- # 4. 登录功能 (Login)
- # ==========================================================================
- def login(self, username: str, password: str) -> bool:
- """
- 执行完整 OAuth2 / Keycloak 登录认证流程:
- 1. 访问主系统入口,触发 OAuth2 授权重定向并获取 state/nonce
- 2. 提取 Keycloak authenticate 表单 action
- 3. POST 提交用户名和密码
- 4. 跟随 302 重定向回到应用回调地址,获取并持久化 JSESSIONID
- 5. 验证登录后的主控面板 (accueil.xhtml)
- """
- logger.info(f"[Login] 开始登录账号: {username}")
- self.logged_in = False
- self.current_user = None
- # Step 1: 访问首页触发 OAuth2 认证流
- resp_entry = self._get(BASE_APP_URL, allow_redirects=True)
- login_html = resp_entry.text
- # Step 2: 提取 authenticate 动作地址
- action_match = re.search(r'"loginAction":\s*"([^"]+)"', login_html)
- if action_match:
- auth_action_url = action_match.group(1).replace(r"\/", "/")
- else:
- soup = BeautifulSoup(login_html, "html.parser")
- form = soup.find("form", id="kc-form-login") or soup.find("form")
- if form and form.get("action"):
- auth_action_url = urljoin(resp_entry.url, form["action"])
- else:
- auth_action_url = resp_entry.url
- logger.info(f"[Login] 登录认证 Action: {auth_action_url}")
- # Step 3: 提交登录凭证
- payload = {
- "username": username,
- "password": password,
- "credentialId": ""
- }
- headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- "Origin": BASE_AUTH_URL,
- "Referer": resp_entry.url
- }
- resp_auth = self._post(auth_action_url, data=payload, headers=headers, allow_redirects=False)
- redirect_url = resp_auth.headers.get("Location")
- # Keycloak 登录成功后会 302 重定向到 application-form.../login/oauth2/code/keycloak
- if resp_auth.status_code in (302, 303) and redirect_url:
- logger.info(f"[Login] 认证成功,跟随 OAuth2 回调: {redirect_url[:80]}...")
-
- # Step 4: 访问 OAuth2 回调并换取业务 JSESSIONID
- resp_cb = self._get(redirect_url, allow_redirects=True)
- logger.info(f"[Login] 登录完成,当前 URL: {resp_cb.url}")
- # Step 5: 验证登录状态
- dashboard_html = resp_cb.text
- 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():
- self.logged_in = True
- self.current_user = username
- self._extract_jsf_state(dashboard_html)
- logger.info(f"[Login] 账号 {username} 成功登录法签申请表系统!")
- return True
- else:
- logger.warning("[Login] 回调后页面未见主页表单,登录状态待确认")
- self.logged_in = True
- self.current_user = username
- return True
- else:
- logger.error(f"[Login] 登录失败!HTTP 状态码: {resp_auth.status_code}")
- if resp_auth.status_code == 200:
- soup = BeautifulSoup(resp_auth.text, "html.parser")
- err = soup.find(class_=lambda c: c and ("error" in c.lower() or "alert" in c.lower()))
- if err:
- logger.error(f"[Login] 错误提示: {err.get_text(strip=True)}")
- return False
- def _extract_jsf_state(self, html: str):
- """解析 Jakarta Faces / JSF 页面中的 ViewState 与 CSRF Token"""
- soup = BeautifulSoup(html, "html.parser")
-
- # ViewState
- vs_input = soup.find("input", {"name": "jakarta.faces.ViewState"})
- if vs_input and vs_input.get("value"):
- self.last_view_state = vs_input["value"]
-
- # CSRF Token
- csrf_input = soup.find("input", {"name": "_csrf"})
- if csrf_input and csrf_input.get("value"):
- self.last_csrf_token = csrf_input["value"]
- # ==========================================================================
- # 5. 填表与新建申请组 (Application Creation)
- # ==========================================================================
- def create_application_group(self) -> Dict[str, Any]:
- """
- 在主页发起新建申请组/申请表:
- 1. GET /fv-fo-dde/accueil.xhtml 提取 ViewState 与 _csrf
- 2. POST /fv-fo-dde/accueil.xhtml 提交 formAccueilUsager:ajouterGroupe
- 3. 重定向到 step1.xhtml 并初始化表单会话
- """
- if not self.logged_in:
- raise RuntimeError("请先调用 login() 成功登录后再进行填表操作!")
- logger.info("[Application] 正在主页发起新建申请组 (ajouterGroupe)...")
- accueil_url = urljoin(BASE_APP_URL, "accueil.xhtml")
- resp_accueil = self._get(accueil_url)
- self._extract_jsf_state(resp_accueil.text)
- if not self.last_view_state or not self.last_csrf_token:
- logger.warning("[Application] 未能在主页解析到完整的 JSF ViewState 或 _csrf,尝试使用正则提取")
- vs_m = re.search(r'name=["\']jakarta\.faces\.ViewState["\']\s+value=["\']([^"\']+)["\']', resp_accueil.text)
- csrf_m = re.search(r'name=["\']_csrf["\']\s+value=["\']([^"\']+)["\']', resp_accueil.text)
- if vs_m:
- self.last_view_state = vs_m.group(1)
- if csrf_m:
- self.last_csrf_token = csrf_m.group(1)
- payload = {
- "formAccueilUsager": "formAccueilUsager",
- "formAccueilUsager:ajouterGroupe": "",
- "_csrf": self.last_csrf_token or "",
- "jakarta.faces.ViewState": self.last_view_state or ""
- }
- headers = {
- "Content-Type": "application/x-www-form-urlencoded",
- "Origin": "https://application-form.france-visas.gouv.fr",
- "Referer": accueil_url
- }
- resp_create = self._post(accueil_url, data=payload, headers=headers, allow_redirects=False)
- location = resp_create.headers.get("Location", "")
- logger.info(f"[Application] 新建申请组响应状态: {resp_create.status_code}, 重定向: {location}")
- if "step1.xhtml" in location or resp_create.status_code in (302, 303):
- step1_url = urljoin(BASE_APP_URL, location if location else "step1.xhtml")
- resp_step1 = self._get(step1_url)
- self._extract_jsf_state(resp_step1.text)
- logger.info(f"[Application] 成功进入申请表 Step 1 (Plans) 页面: {step1_url}")
- return {
- "success": True,
- "current_step": "step1",
- "step_url": step1_url
- }
- else:
- return {
- "success": False,
- "status_code": resp_create.status_code,
- "location": location
- }
- def fill_step1_and_create_application(
- self,
- applicant_data: Optional[Dict[str, Any]] = None
- ) -> Dict[str, Any]:
- """
- 自动化填表 (Step 1 - Your plans) 并生成/提取 FRA1 申请编号:
- 1. 启动/复用 Chromium 浏览器页面 (带代理配置)
- 2. 登录账号进入法签系统
- 3. 发起新建申请组 (Create a new application in a new group of applications)
- 4. 级联填写 Step 1 必填信息:
- - 国籍 (Nationality): 默认 CHN
- - 欧盟亲属 (hasNationalFamily): 默认 No
- - 递签国家 (Place of submission): 默认 CHN
- - 停留类型 (Stay duration): 默认 C (Short-stay <= 90 days)
- - 主目的地 (Destination): 默认 MET (France)
- - 递签城市 (Town): 默认 1PE (Beijing) 或指定城市
- - 护照签发国 (Authority): 默认 CHN (China)
- - 旅行证件类型 (Travel document): 默认 10 (Ordinary passport)
- - 护照号与起止有效期
- - 申请主目的与子目的 (Purpose category & Purpose): 默认 TOUR (Tourism) / 134 或 1
- 5. 点击 Verify 校验表单
- 6. 点击 Next 弹出护照号确认弹窗
- 7. 确认弹窗中的 Yes (formStep1:btnValiderModal),完成第一步锁定并提交
- 8. 确认成功跳转至 Step 2 (Your information)
- 9. 返回主页 accueil.xhtml 提取正式生成的 FRA1 申请编号 (如 FRA1PE20267100927)
- """
- applicant_data = applicant_data or {}
- email = (
- applicant_data.get("email")
- or applicant_data.get("username")
- or self.account_detail.get("email")
- or self.current_user
- )
- password = (
- applicant_data.get("password")
- or self.account_detail.get("password")
- )
- if not email or not password:
- raise ValueError("必须提供账号 email 与 password 才能进行填表生成 FRA1!")
- logger.info(f"[Application] 开始为账号 {email} 执行自动化填表 (Step 1) 与 FRA1 申请号生成流程...")
- nationality = applicant_data.get("nationality", "CHN")
- has_family = applicant_data.get("has_family", False)
- if isinstance(has_family, str):
- has_family = has_family.lower() in ("true", "1", "yes")
- deposit_country = applicant_data.get("deposit_country", "CHN")
- stay_duration = applicant_data.get("stay_duration", "C")
- destination = applicant_data.get("destination", "MET")
- town = applicant_data.get("town") or applicant_data.get("city", "1PE")
- authority = applicant_data.get("authority", "CHN")
- doc_type = applicant_data.get("doc_type", "10")
- # 护照号与有效期
- passport_no = applicant_data.get("passport_number") or applicant_data.get("passport_no")
- if not passport_no:
- rand_digits = ''.join(random.choices(string.digits, k=8))
- passport_no = f"E{rand_digits}"
- release_date = applicant_data.get("release_date", "01/01/2022")
- expiration_date = applicant_data.get("expiration_date", "01/01/2032")
- purpose_cat = applicant_data.get("purpose_category", "TOUR")
- purpose = applicant_data.get("purpose")
- own_page = False
- page = getattr(self, "page", None)
- if not page:
- co = ChromiumOptions()
- if self.proxy:
- co.set_proxy(self.proxy)
- co.headless(True)
- co.set_argument('--no-sandbox')
- co.set_argument('--disable-gpu')
- page = ChromiumPage(co)
- own_page = True
- try:
- logger.info("[Application] 访问法签主系统入口...")
- page.get(BASE_APP_URL)
- time.sleep(2)
- # 若遇到登录表单则自动登录
- user_inp = page.ele('@name:username')
- pwd_inp = page.ele('@name:password')
- if user_inp and pwd_inp:
- logger.info(f"[Application] 自动提交登录: {email}")
- user_inp.input(email)
- pwd_inp.input(password)
- btn_login = page.ele('@id:kc-login') or page.ele('@type:submit')
- if btn_login:
- btn_login.click()
- time.sleep(4)
- # 检查是否有未完成的申请需要编辑,或者新建申请
- btn_add = page.ele('#formAccueilUsager\\:ajouterGroupe') or page.ele('text:Create a new application')
- if btn_add:
- logger.info("[Application] 点击新建申请组 (ajouterGroupe)...")
- btn_add.click()
- time.sleep(3)
- # 如果已经在 step1 或需要编辑进入
- if "step1.xhtml" not in page.url:
- btn_edit = page.ele('css:a[title*="Edit"], a[title*="Modif"]') or page.ele('css:a.ui-commandlink')
- if btn_edit:
- btn_edit.click()
- time.sleep(3)
- # 填充 Step 1 字段
- logger.info(f"[Application] 填充基本信息: 国籍={nationality}, 递签国={deposit_country}, 城市={town}, 护照={passport_no}")
- # 1. 国籍
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:visas-selected-nationality_input']");
- if (el) {{ el.value = '{nationality}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
- """)
- time.sleep(1)
- # 2. 欧盟亲属: Yes/No (0: Yes, 1: No)
- family_radio_idx = 0 if has_family else 1
- page.run_js(f"""
- let el = document.getElementById('formStep1:hasNationalFamily:{family_radio_idx}');
- if (el) {{
- el.checked = true;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- el.dispatchEvent(new Event('click', {{ bubbles: true }}));
- }}
- """)
- time.sleep(1)
- # 3. 递签国
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-deposit-country_input']");
- if (el) {{ el.value = '{deposit_country}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
- """)
- time.sleep(2)
- # 4. 停留期
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-stayDuration_input']");
- if (el) {{ el.value = '{stay_duration}'; el.dispatchEvent(new Event('change', {{ bubbles: true }})); }}
- """)
- time.sleep(2)
- # 5. 目的地
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-destination_input']");
- if (el && el.options.length > 1) {{
- el.value = '{destination}' || el.options[1].value;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 6. 递签城市
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-deposit-town_input']");
- if (el && el.options.length > 1) {{
- el.value = '{town}' || el.options[1].value;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 7. 签发国
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-authority_input']");
- if (el && el.options.length > 1) {{
- el.value = '{authority}' || el.options[1].value;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 8. 证件类型
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-dde-travel-document_input']");
- if (el && el.options.length > 1) {{
- el.value = '{doc_type}' || el.options[1].value;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 9. 护照号与起止日期
- page.run_js(f"""
- let elDoc = document.getElementById('formStep1:Visas-dde-travel-document-number');
- if (elDoc) elDoc.value = '{passport_no}';
- let elRel = document.getElementById('formStep1:Visas-dde-release_date_real_input');
- if (elRel) elRel.value = '{release_date}';
- let elExp = document.getElementById('formStep1:Visas-dde-expiration_date_input');
- if (elExp) elExp.value = '{expiration_date}';
- """)
- time.sleep(1)
- # 10. 签证目的类别
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-purposeCategory_input']");
- if (el && el.options.length > 1) {{
- el.value = '{purpose_cat}' || el.options[1].value;
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 11. 签证目的子项
- page.run_js(f"""
- let el = document.querySelector("select[name='formStep1:Visas-selected-purpose_input']");
- if (el && el.options.length > 1) {{
- let targetVal = '{purpose or ""}';
- if (targetVal && Array.from(el.options).some(o => o.value === targetVal)) {{
- el.value = targetVal;
- }} else {{
- el.value = el.options[1].value;
- }}
- el.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- """)
- time.sleep(2)
- # 12. 点击 Verify
- logger.info("[Application] 提交 Step 1 校验 (Verify)...")
- btn_verif = page.ele('#formStep1\\:btnVerifier') or page.ele('text:Verify')
- if btn_verif:
- btn_verif.click()
- time.sleep(4)
- # 13. 点击 Next
- btn_suivant = page.ele('#formStep1\\:btnSuivant')
- if not btn_suivant:
- btn_suivant = page.ele('css:button.primaire')
- if btn_suivant:
- logger.info("[Application] 点击下一步 (Next) 触发护照确认弹窗...")
- btn_suivant.click()
- time.sleep(3)
- # 14. 弹窗确认 Yes (formStep1:btnValiderModal)
- logger.info("[Application] 确认护照信息弹窗 (Yes)...")
- page.run_js("""
- let modalBtn = document.getElementById('formStep1:btnValiderModal');
- if (modalBtn) {
- modalBtn.click();
- } else {
- let btns = Array.from(document.querySelectorAll('.ui-dialog button'));
- let y = btns.find(b => b.innerText.trim().toLowerCase() === 'yes' || b.innerText.trim().toLowerCase() === 'oui');
- if (y) y.click();
- }
- """)
- time.sleep(4)
- # 15. 返回主页提取已生成的 FRA1 申请号
- logger.info("[Application] 正在从主页提取 FRA1 申请号...")
- page.get(urljoin(BASE_APP_URL, "accueil.xhtml"))
- time.sleep(3)
- accueil_html = page.html
- fra_matches = re.findall(r'\b(FRA\d[A-Z0-9_-]+)\b', accueil_html, re.I)
- unique_fra = list(dict.fromkeys([c.upper() for c in fra_matches]))
- fra1_number = unique_fra[0] if unique_fra else None
- # 提取申请组 ID (Group n°...)
- grp_match = re.search(r'Group\s+n[°o]?\s*(\d+)', accueil_html, re.I)
- group_id = grp_match.group(1) if grp_match else None
- logger.info(f"[Application] 提取结果 -> 申请组号: {group_id}, FRA1 申请号: {fra1_number}")
- return {
- "success": bool(fra1_number),
- "fra1_number": fra1_number,
- "all_fra_codes": unique_fra,
- "group_id": group_id,
- "passport_number": passport_no,
- "city": town,
- "nationality": nationality
- }
- finally:
- if own_page and page:
- try:
- page.quit()
- except Exception:
- pass
- # ==========================================================================
- # 6. 获取 FRA1 申请号 (Fetch FRA1 Application Numbers)
- # ==========================================================================
- def get_applications(self) -> List[Dict[str, Any]]:
- """
- 获取当前登录账号下所有的申请记录与 FRA1 申请号。
- 解析 /fv-fo-dde/accueil.xhtml 页面中的表格及申请卡片数据。
- """
- if not self.logged_in:
- raise RuntimeError("请先调用 login() 成功登录后再查询申请号!")
- logger.info("[Fetch] 正在获取账号申请列表与 FRA1 申请号...")
- accueil_url = urljoin(BASE_APP_URL, "accueil.xhtml")
- resp = self._get(accueil_url)
- html = resp.text
- applications = []
- soup = BeautifulSoup(html, "html.parser")
- # 1. 查找所有符合 FRA1 规范的申请编号 (通常形如 FRA1xxxxxxxx 或 FRAxxxxxxxx)
- fra_codes = re.findall(r'\b(FRA\d[A-Z0-9_-]+)\b', html, re.IGNORECASE)
- unique_fra_codes = list(dict.fromkeys([c.upper() for c in fra_codes]))
- # 2. 结构化解析主页申请表格或数据卡片
- tables = soup.find_all("table")
- for table in tables:
- rows = table.find_all("tr")
- headers = [th.get_text(strip=True) for th in rows[0].find_all(["th", "td"])] if rows else []
- for row in rows[1:]:
- cols = [td.get_text(strip=True) for td in row.find_all("td")]
- if cols:
- row_text = " ".join(cols)
- fra_match = re.search(r'\b(FRA\d[A-Z0-9_-]+)\b', row_text, re.IGNORECASE)
- if fra_match:
- code = fra_match.group(1).upper()
- applications.append({
- "fra1_number": code,
- "raw_columns": cols,
- "headers": headers,
- "summary": row_text
- })
- # 3. 如果在表格中没有独立解析出行,但正则匹配到了 FRA 编号,补充输出
- existing_numbers = {app["fra1_number"] for app in applications}
- for code in unique_fra_codes:
- if code not in existing_numbers:
- applications.append({
- "fra1_number": code,
- "status": "DETECTED_IN_PAGE",
- "summary": f"Detected reference {code}"
- })
- logger.info(f"[Fetch] 共找到 {len(applications)} 条申请记录: {[a['fra1_number'] for a in applications]}")
- return applications
- # ==============================================================================
- # 代理池与云端上报辅助函数
- # ==============================================================================
- def load_proxies(pool_name: str) -> List[Dict[str, Any]]:
- """从 config/proxies.yaml 读取指定的代理池"""
- config_path = os.path.join(ROOT_DIR, "config", "proxies.yaml")
- if not os.path.exists(config_path):
- return []
- try:
- with open(config_path, "r", encoding="utf-8") as f:
- data = yaml.safe_load(f) or {}
- nodes_list = data.get("nodes") or data.get("proxies") or []
- nodes_map = {n["name"]: n for n in nodes_list if isinstance(n, dict) and "name" in n}
- pools_data = data.get("pools", {}) if "pools" in data else data
- clean_name = pool_name.replace("local:", "").strip() if pool_name else ""
- raw_pool = pools_data.get(pool_name) or pools_data.get(clean_name)
- if not raw_pool and clean_name:
- raw_pool = pools_data.get(f"local_{clean_name}")
- if not raw_pool:
- raw_pool = pools_data.get("local", [])
- proxies = []
- for item in raw_pool:
- if isinstance(item, str) and item in nodes_map:
- proxies.append(nodes_map[item])
- elif isinstance(item, dict):
- proxies.append(item)
- return proxies
- except Exception as e:
- logger.warning(f"读取 proxies.yaml 失败: {e}")
- return []
- def upload_account_to_server(
- profile: Dict[str, Any],
- pool_name: str,
- api_token: str = "tok_e946329a60ff45ba807f3f41b0e8b7fc",
- api_url: str = "https://api.text.skin/api/account/add"
- ) -> bool:
- """上报成功注册的账号至云端账号池"""
- try:
- headers = {
- "Authorization": f"Bearer {api_token}",
- "Content-Type": "application/json"
- }
- payload = {
- "pool_name": pool_name,
- "username": profile.get("username") or profile.get("email"),
- "password": profile.get("password"),
- "extra_data": profile
- }
- resp = requests.post(api_url, json=payload, headers=headers, timeout=10)
- if resp.status_code == 200 and resp.json().get("code") == 0:
- logger.info(f"账号已成功上传至云端账号池 [{pool_name}]")
- return True
- else:
- logger.warning(f"账号上传云端失败: {resp.text}")
- return False
- except Exception as e:
- logger.warning(f"上报账号异常: {e}")
- return False
- # ==============================================================================
- # 一键自动注册全流程函数
- # ==============================================================================
- def auto_register(config: Optional[Union[Dict[str, Any], str]] = None, **kwargs) -> Dict[str, Any]:
- """
- 传入配置,一键全自动完成法签账号注册、激活、设密与登录验证全流程:
- :param config: 配置字典或配置文件路径 (yaml/json)
- :param kwargs: 覆盖参数
- :return: 包含成功账号信息和登录凭证的字典
- """
- if isinstance(config, str) and os.path.exists(config):
- with open(config, "r", encoding="utf-8") as f:
- if config.endswith((".yaml", ".yml")):
- raw = yaml.safe_load(f) or {}
- else:
- raw = json.load(f) or {}
- if isinstance(raw, list) and len(raw) > 0:
- cfg = raw[0] if isinstance(raw[0], dict) else {}
- elif isinstance(raw, dict):
- cfg = raw
- else:
- cfg = {}
- elif isinstance(config, list) and len(config) > 0 and isinstance(config[0], dict):
- cfg = dict(config[0])
- elif isinstance(config, dict):
- cfg = dict(config)
- else:
- cfg = {}
- cfg.update(kwargs)
- # 提取账号与配置信息 (兼容普通配置、sentinel配置及free_config)
- account_info = cfg.get("account", {}) if isinstance(cfg.get("account"), dict) else {}
- free_cfg = cfg.get("free_config", {}) if isinstance(cfg.get("free_config"), dict) else {}
- sentinel_cfg = cfg.get("sentinel", {}) if isinstance(cfg.get("sentinel"), dict) else {}
- email = (
- cfg.get("email")
- or cfg.get("username")
- or account_info.get("username")
- or account_info.get("email")
- or free_cfg.get("email")
- )
- password = (
- cfg.get("password")
- or account_info.get("password")
- or free_cfg.get("password")
- )
-
- # 自动生成邮箱 (默认 @text.skin)
- if not email:
- prefix = cfg.get("account_prefix") or cfg.get("prefix") or "fra"
- domain = cfg.get("email_domain") or cfg.get("domain") or "text.skin"
- rand_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
- email = f"{prefix}_{rand_suffix}@{domain}"
-
- # 自动生成强密码 (如 FraVis@829103!)
- if not password:
- rand_digits = random.randint(100000, 999999)
- password = f"FraVis@{rand_digits}!"
- first_name = cfg.get("first_name") or cfg.get("firstName") or free_cfg.get("first_name") or "Jerry"
- last_name = cfg.get("last_name") or cfg.get("lastName") or free_cfg.get("last_name") or "Wang"
- language = cfg.get("language") or free_cfg.get("language") or "English"
- master_email = cfg.get("master_email") or free_cfg.get("master_email") or "hujiarui8@gmail.com"
- email_api_token = cfg.get("email_token") or cfg.get("email_api_token")
- account_pool = (
- cfg.get("account_pool")
- or cfg.get("pool_name")
- or sentinel_cfg.get("account_pool_id")
- )
- output_file = cfg.get("output") or cfg.get("output_file") or os.path.join(ROOT_DIR, "data", "francevisa_accounts.txt")
- max_retries = int(cfg.get("max_retries") or 3)
- # 代理处理
- proxy = cfg.get("proxy")
- proxy_pool = cfg.get("proxy_pool")
- if not proxy and proxy_pool:
- pool_name = proxy_pool if isinstance(proxy_pool, str) else (proxy_pool[0] if isinstance(proxy_pool, list) else None)
- if pool_name:
- proxies = load_proxies(pool_name)
- if proxies:
- node = random.choice(proxies)
- if isinstance(node, dict):
- ip = node.get("ip") or node.get("server")
- port = node.get("port")
- proto = node.get("proto", "http")
- user = node.get("user")
- pwd = node.get("password")
- if user and pwd:
- proxy = f"{proto}://{user}:{pwd}@{ip}:{port}"
- else:
- proxy = f"{proto}://{ip}:{port}"
- elif isinstance(node, str):
- proxy = node
- logger.info("=" * 60)
- logger.info(">>> 开始法签申请账号一键自动化注册流程 <<<")
- logger.info(f"账号邮箱: {email}")
- logger.info(f"登录密码: {password}")
- logger.info(f"接收邮箱: {master_email}")
- logger.info(f"网络代理: {proxy or '直连'}")
- logger.info("=" * 60)
- client = FranceVisaKeygen(
- proxy=proxy,
- email_api_token=email_api_token,
- master_email=master_email,
- account_detail={"email": email, "password": password}
- )
- # 1. 账号注册
- reg_success = False
- for attempt in range(1, max_retries + 1):
- try:
- logger.info(f"[AutoRegister] 正在执行注册尝试 ({attempt}/{max_retries})...")
- reg_res = client.register(
- first_name=first_name,
- last_name=last_name,
- email=email,
- language=language
- )
- if reg_res.get("success"):
- reg_success = True
- break
- else:
- logger.warning(f"[AutoRegister] 注册返回未完成: {reg_res.get('error')}")
- except Exception as e:
- logger.warning(f"[AutoRegister] 注册异常: {e}")
- time.sleep(2)
- if not reg_success:
- raise BizLogicError(message=f"账号 {email} 注册失败,已达最大重试次数")
- # 2. 邮箱验证激活
- logger.info(f"[AutoRegister] 正在接收激活邮件并验证账号...")
- client.activate(email=email)
- # 3. 设定初始密码
- logger.info(f"[AutoRegister] 正在接收重置邮件并设定登录密码...")
- client.set_initial_password(email=email, password=password)
- # 4. 登录验证探针
- logger.info(f"[AutoRegister] 正在执行登录验证探针...")
- login_ok = client.login(email, password)
- if not login_ok:
- raise BizLogicError(message=f"账号 {email} 注册并设密后登录验证失败!")
- logger.info(f"🎉 账号 {email} 注册成功并已通过登录验证!")
- profile = {
- "email": email,
- "username": email,
- "password": password,
- "first_name": first_name,
- "last_name": last_name,
- "language": language,
- "status": "active",
- "registered_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- }
- # 5. 自动填表 (Step 1) 并获取 FRA1 申请编号
- create_app = cfg.get("create_application", True)
- if str(create_app).lower() not in ("false", "0", "no"):
- try:
- logger.info(f"[AutoRegister] 正在为账号 {email} 执行自动化填表并获取 FRA1 申请编号...")
- app_res = client.fill_step1_and_create_application(applicant_data=cfg)
- fra_code = app_res.get("fra1_number")
- if fra_code:
- profile["fra1_number"] = fra_code
- profile["application_group"] = app_res.get("group_id")
- profile["passport_number"] = app_res.get("passport_number")
- profile["city"] = app_res.get("city")
- logger.info(f"🎉 成功生成并获取到 FRA1 申请号: {fra_code}")
- else:
- logger.warning("[AutoRegister] 填表完成但未在页面提取到有效 FRA1 编号")
- except Exception as e:
- logger.warning(f"[AutoRegister] 自动填表获取 FRA1 异常: {e}")
- # 6. 持久化记录
- try:
- os.makedirs(os.path.dirname(os.path.abspath(output_file)), exist_ok=True)
- fra_val = profile.get("fra1_number") or "N/A"
- line = f"{email}----{password}----{fra_val}----{first_name} {last_name}----{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
- with open(output_file, "a", encoding="utf-8") as f:
- f.write(line)
- json_path = os.path.splitext(output_file)[0] + ".json"
- all_accounts = []
- if os.path.exists(json_path):
- try:
- with open(json_path, "r", encoding="utf-8") as f:
- all_accounts = json.load(f)
- except Exception:
- all_accounts = []
- all_accounts.append(profile)
- with open(json_path, "w", encoding="utf-8") as f:
- json.dump(all_accounts, f, indent=2, ensure_ascii=False)
- logger.info(f"账号凭证已写入: {output_file} & {json_path}")
- except Exception as e:
- logger.warning(f"保存账号文件失败: {e}")
- # 7. 上报云端账号池
- if account_pool:
- upload_account_to_server(profile, pool_name=account_pool)
- return profile
- # ==============================================================================
- # 命令行交互与测试入口
- # ==============================================================================
- def main(config: Optional[Union[Dict[str, Any], str]] = None) -> Optional[Dict[str, Any]]:
- """
- 主入口:执行 France-Visas (法签申请表) 账号全自动注册与填表生成 FRA1 申请号。
- 1. 支持代码内调用传参:传入 config 字典或 YAML/JSON 配置文件路径;
- 2. 支持命令行直接执行:所有注册与填表所需参数(邮箱、密码、姓名、代理、邮箱API、账号池、护照号、城市等)均可直接通过命令行传入。
- """
- if config is not None:
- result = auto_register(config)
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return result
- parser = argparse.ArgumentParser(
- description="France-Visas (法签申请表) 账号一键自动注册与填表工具 - 命令行参数直传模式"
- )
- # 配置文件 (可选,可与命令行参数叠加)
- parser.add_argument("--config", "-c", type=str, default=None, help="配置文件路径 (YAML 或 JSON)")
- # 账号与身份信息
- parser.add_argument("--email", type=str, default=None, help="账号邮箱 (不指定则自动生成)")
- parser.add_argument("--password", type=str, default=None, help="账号密码 (不指定则自动生成强密码)")
- parser.add_argument("--first-name", type=str, default=None, help="名字 (默认 Jerry)")
- parser.add_argument("--last-name", type=str, default=None, help="姓氏 (默认 Wang)")
- parser.add_argument("--language", type=str, default=None, help="界面语言 (默认 English)")
- parser.add_argument("--prefix", "--account-prefix", dest="prefix", type=str, default=None, help="自动生成邮箱的前缀 (默认 fra)")
- parser.add_argument("--domain", "--email-domain", dest="domain", type=str, default=None, help="自动生成邮箱的域名 (默认 text.skin)")
- # 邮件接收与验证 API
- parser.add_argument("--master-email", type=str, default=None, help="接收验证与设密邮件的主邮箱 (默认 hujiarui8@gmail.com)")
- parser.add_argument("--email-token", type=str, default=None, help="邮箱 API Token")
- # 网络代理与账号池
- parser.add_argument("--proxy", type=str, default=None, help="指定网络代理 (如 http://127.0.0.1:7897)")
- parser.add_argument("--proxy-pool", type=str, default=None, help="代理池名称 (在 proxies.yaml 中定义,如 local)")
- parser.add_argument("--account-pool", type=str, default=None, help="注册成功后上报的云端账号池名称")
- # 填表与 FRA1 申请号参数
- parser.add_argument("--create-app", "--fill-form", dest="create_application", action="store_true", default=True, help="注册后是否自动填表并获取 FRA1 申请号 (默认开启)")
- parser.add_argument("--no-create-app", dest="create_application", action="store_false", help="仅注册账号,不进行填表获取 FRA1")
- parser.add_argument("--nationality", type=str, default="CHN", help="国籍代码 (默认 CHN)")
- parser.add_argument("--has-family", dest="has_family", action="store_true", default=False, help="是否有欧盟/欧洲经济区亲属 (默认 False)")
- parser.add_argument("--deposit-country", type=str, default="CHN", help="递签国家代码 (默认 CHN)")
- parser.add_argument("--stay-duration", type=str, default="C", help="停留期限: C(短期<=90天), D(长期>90天), A(机场过境) (默认 C)")
- parser.add_argument("--destination", type=str, default="MET", help="主目的地: MET(法国本土) (默认 MET)")
- parser.add_argument("--city", "--town", dest="city", type=str, default="1PE", help="递签城市代码: 1PE(北京), 1CB(广州), 1SH(上海), 1CA(成都), 1WU(武汉)等 (默认 1PE)")
- parser.add_argument("--authority", type=str, default="CHN", help="护照签发国代码 (默认 CHN)")
- parser.add_argument("--doc-type", type=str, default="10", help="证件类型: 10(普通护照), 30(外交护照), 40(公务护照) (默认 10)")
- parser.add_argument("--passport-number", "--passport-no", dest="passport_number", type=str, default=None, help="填表护照号 (默认自动生成 E+8位随机数字)")
- parser.add_argument("--release-date", type=str, default="01/01/2022", help="护照签发日期 DD/MM/YYYY (默认 01/01/2022)")
- parser.add_argument("--expiration-date", type=str, default="01/01/2032", help="护照失效日期 DD/MM/YYYY (默认 01/01/2032)")
- parser.add_argument("--purpose-category", type=str, default="TOUR", help="签证主目的: TOUR(旅游), VISF(探亲), ETUD(留学), TRAV(商务) (默认 TOUR)")
- parser.add_argument("--purpose", type=str, default=None, help="签证目的子项编号: 134(欧盟家属旅游), 1(个人旅游)等 (默认自动选用)")
- # 运行与存储选项
- parser.add_argument("--output", "-o", type=str, default=None, help="账号本地保存文件路径 (默认 data/francevisa_accounts.txt)")
- parser.add_argument("--max-retries", type=int, default=None, help="验证码或网络失败时的最大重试次数 (默认 3)")
- args = parser.parse_args()
- # 读取配置文件(如果提供)
- cfg: Dict[str, Any] = {}
- if args.config:
- if os.path.exists(args.config):
- with open(args.config, "r", encoding="utf-8") as f:
- if args.config.endswith((".yaml", ".yml")):
- raw = yaml.safe_load(f) or {}
- else:
- raw = json.load(f) or {}
- if isinstance(raw, list) and len(raw) > 0 and isinstance(raw[0], dict):
- cfg = raw[0]
- elif isinstance(raw, dict):
- cfg = raw
- else:
- logger.warning(f"指定配置文件不存在: {args.config}")
- # 提取命令行中显式传入的有效参数(过滤掉 None 和 config 参数)
- cli_params = {k: v for k, v in vars(args).items() if v is not None and k != "config"}
- cfg.update(cli_params)
- # 执行全自动注册与填表全流程
- result = auto_register(cfg)
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return result
- if __name__ == "__main__":
- main()
|