ソースを参照

fix: vfs cloudflare block

hujiarui 1 ヶ月 前
親
コミット
df1fe293ba
3 ファイル変更、249 行追加、59 行削除
  1. 151 51
      francevisa_keygen.py
  2. 61 7
      plugins/vfs_plugin.py
  3. 37 1
      vfs_keygen.py

+ 151 - 51
francevisa_keygen.py

@@ -955,21 +955,39 @@ class FranceVisaKeygen:
                 time.sleep(4)
 
             # 检查是否有未完成的申请需要编辑,或者新建申请
-            btn_add = page.ele('#formAccueilUsager\\:ajouterGroupe') or page.ele('text:Create a new application')
+            btn_add = (
+                page.ele('@id:formAccueilUsager:ajouterGroupe')
+                or page.ele('@name:formAccueilUsager:ajouterGroupe')
+                or page.ele('text:Create a new application')
+                or page.ele('text:Créer une nouvelle demande')
+            )
             if btn_add:
                 logger.info("[Application] 点击新建申请组 (ajouterGroupe)...")
                 btn_add.click()
                 time.sleep(3)
 
-            # 如果已经在 step1 或需要编辑进入
+            # 如果未进入 step1,尝试点击已有申请的 Edit/Add 进入
             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')
+                btn_edit = (
+                    page.ele('css:a.btnicone[title*="Edit"]')
+                    or page.ele('css:a.btnicone[title*="Modif"]')
+                    or page.ele('text:Edit application')
+                    or page.ele('text:Add an application')
+                    or page.ele('text:Ajouter une demande')
+                )
                 if btn_edit:
+                    logger.info("[Application] 点击编辑/追加申请进入表单...")
                     btn_edit.click()
                     time.sleep(3)
 
+            # 再次确认是否在 step1,若不在则直接导航至 step1.xhtml
+            if "step1.xhtml" not in page.url:
+                page.get(urljoin(BASE_APP_URL, "step1.xhtml"))
+                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']");
@@ -994,44 +1012,70 @@ class FranceVisaKeygen:
                 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)
+            # 等待递签城市下拉框根据递签国完成 AJAX 级联渲染
+            for _ in range(10):
+                opts_len = page.run_js("""
+                    let el = document.querySelector("select[name='formStep1:Visas-selected-deposit-town_input']");
+                    return el ? el.options.length : 0;
+                """)
+                if opts_len and opts_len > 1:
+                    break
+                time.sleep(1)
 
             # 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)
+            time.sleep(1)
 
             # 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;
+                    let targetVal = '{destination}';
+                    let found = Array.from(el.options).some(o => o.value === targetVal);
+                    if (found) {{
+                        el.value = targetVal;
+                    }} else {{
+                        el.value = el.options[1].value;
+                    }}
                     el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                 }}
             """)
-            time.sleep(2)
+            time.sleep(1)
 
-            # 6. 递签城市
+            # 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;
+                    let targetVal = '{town}';
+                    let found = Array.from(el.options).some(o => o.value === targetVal);
+                    if (found) {{
+                        el.value = targetVal;
+                    }} else {{
+                        el.value = el.options[1].value;
+                    }}
                     el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                 }}
             """)
-            time.sleep(2)
+            time.sleep(1)
 
             # 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;
+                    let targetVal = '{authority}';
+                    let found = Array.from(el.options).some(o => o.value === targetVal);
+                    if (found) {{
+                        el.value = targetVal;
+                    }} else {{
+                        el.value = el.options[1].value;
+                    }}
                     el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                 }}
             """)
-            time.sleep(2)
+            time.sleep(1)
 
             # 8. 证件类型
             page.run_js(f"""
@@ -1041,7 +1085,7 @@ class FranceVisaKeygen:
                     el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                 }}
             """)
-            time.sleep(2)
+            time.sleep(1)
 
             # 9. 护照号与起止日期
             page.run_js(f"""
@@ -1062,7 +1106,7 @@ class FranceVisaKeygen:
                     el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                 }}
             """)
-            time.sleep(2)
+            time.sleep(1)
 
             # 11. 签证目的子项
             page.run_js(f"""
@@ -1077,51 +1121,97 @@ class FranceVisaKeygen:
                     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)
+            time.sleep(1)
 
-            # 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)
+            # 12. 校验并点击下一步 (Next)
+            logger.info("[Application] 提交 Step 1 (Next) 触发护照确认弹窗...")
+            clicked = page.run_js("""
+                let btn = document.getElementById('formStep1:btnSuivant') || document.querySelector("button[id*='btnSuivant']");
+                if (btn) { btn.click(); return true; }
+                return false;
+            """)
+            if not clicked:
+                btn_suivant = (
+                    page.ele('@id:formStep1:btnSuivant')
+                    or page.ele('text:Next')
+                    or page.ele('text:Suivant')
+                    or page.ele('css:button.primaire')
+                )
+                if btn_suivant:
+                    btn_suivant.click()
+            time.sleep(2)
 
-            # 14. 弹窗确认 Yes (formStep1:btnValiderModal)
-            logger.info("[Application] 确认护照信息弹窗 (Yes)...")
-            page.run_js("""
-                let modalBtn = document.getElementById('formStep1:btnValiderModal');
-                if (modalBtn) {
-                    modalBtn.click();
-                } else {
+            # 13. 弹窗确认 Yes (formStep1:btnValiderModal)
+            logger.info("[Application] 等待并确认护照信息弹窗 (Yes)...")
+            modal_confirmed = False
+            for _ in range(8):
+                res = page.run_js("""
+                    let modalBtn = document.getElementById('formStep1:btnValiderModal');
+                    if (modalBtn && modalBtn.offsetParent !== null) {
+                        modalBtn.click();
+                        return "modal_clicked";
+                    }
                     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)
+                    let y = btns.find(b => {
+                        let t = b.innerText.trim().toLowerCase();
+                        return (t === 'yes' || t === 'oui') && b.offsetParent !== null;
+                    });
+                    if (y) {
+                        y.click();
+                        return "dialog_clicked";
+                    }
+                    return null;
+                """)
+                if res:
+                    logger.info(f"[Application] 护照确认弹窗点击完成 ({res})")
+                    modal_confirmed = True
+                    break
+                time.sleep(1)
+
+            # 14. 等待跳转至 Step 2 (确认申请已创建成功入库)
+            logger.info("[Application] 等待申请表创建并确认入库...")
+            for _ in range(8):
+                if "step2.xhtml" in page.url or "accueil.xhtml" in page.url:
+                    break
+                time.sleep(1)
 
             # 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
+            
+            fra1_number = None
+            unique_fra = []
+            group_id = None
+
+            for attempt in range(1, 6):
+                time.sleep(2)
+                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]))
+                if unique_fra:
+                    fra1_number = unique_fra[0]
+                    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
+                    break
+                logger.info(f"[Application] 第 {attempt} 次主页提取暂未匹配到,等待页面刷新...")
 
-            # 提取申请组 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
+            # 16. 协议层双重保障:若 DOM 提取为空,同步 Cookie 并调用 get_applications()
+            if not fra1_number:
+                logger.info("[Application] 尝试使用 HTTP 协议接口同步提取申请记录...")
+                try:
+                    cookies = page.cookies()
+                    if isinstance(cookies, list):
+                        for c in cookies:
+                            self.session.cookies.set(c['name'], c['value'])
+                    elif isinstance(cookies, dict):
+                        self.session.cookies.update(cookies)
+                    self.logged_in = True
+                    apps = self.get_applications()
+                    if apps and apps[0].get("fra1_number"):
+                        fra1_number = apps[0]["fra1_number"]
+                        unique_fra = [a["fra1_number"] for a in apps if a.get("fra1_number")]
+                except Exception as ex:
+                    logger.warning(f"[Application] 协议层兜底获取异常: {ex}")
 
             logger.info(f"[Application] 提取结果 -> 申请组号: {group_id}, FRA1 申请号: {fra1_number}")
 
@@ -1431,6 +1521,16 @@ def auto_register(config: Optional[Union[Dict[str, Any], str]] = None, **kwargs)
             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 not fra_code:
+                try:
+                    logger.info("[AutoRegister] 页面提取暂未直接返回 FRA1,执行 get_applications() 兜底查询...")
+                    apps = client.get_applications()
+                    if apps and apps[0].get("fra1_number"):
+                        fra_code = apps[0]["fra1_number"]
+                        logger.info(f"[AutoRegister] 兜底成功获取到已存在的 FRA1 申请号: {fra_code}")
+                except Exception as ex:
+                    logger.warning(f"[AutoRegister] 兜底查询申请号异常: {ex}")
+
             if fra_code:
                 profile["fra1_number"] = fra_code
                 profile["application_group"] = app_res.get("group_id")

+ 61 - 7
plugins/vfs_plugin.py

@@ -210,13 +210,66 @@ class VfsPlugin(IPlugin):
             window.cf_token = null;
             var st = document.getElementById('status');
             if(st) { st.innerText = 'Resetting verification...'; st.style.color = '#666'; }
-            try { window.turnstile.reset(); } catch(e) {}
+            try { 
+                if (window.turnstile) {
+                    if (window.my_widget_id !== undefined) {
+                        window.turnstile.reset(window.my_widget_id);
+                    } else {
+                        window.turnstile.reset();
+                    }
+                }
+            } catch(e) {}
             """)
             return
 
+        # 1. 先打开 login 建立会话上下文与 Cloudflare 信任凭证
+        mission = self.free_config.get("mission_code", "")
+        country = self.free_config.get("country_code", "")
+        lang = self.free_config.get("language", "en")
+        if country and mission:
+            login_url = f"https://visa.vfsglobal.com/{country}/{lang}/{mission}/login"
+        else:
+            login_url = "https://visa.vfsglobal.com/irl/en/dnk/login"
+
+        self._log(f"Establishing session context via login portal: {login_url}")
+        self.page.set.timeouts(page_load=30, script=20)
+        try:
+            self.page.get(login_url)
+            time.sleep(3)
+
+            # 处理 Cloudflare 拦截或等待室
+            cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else True)
+            if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
+                self._log('Block by cloudflare, try refresh...')
+                self.page.refresh()
+                self.page.wait.doc_loaded()
+            cf_bypasser.handle_waiting_room()
+
+            # 处理 OneTrust Cookie 弹窗
+            cookie_btn = self.page.ele('#onetrust-accept-btn-handler', timeout=3)
+            if cookie_btn and cookie_btn.states.is_displayed:
+                cookie_btn.click()
+                self._log("Accepted OneTrust cookie consent.")
+                time.sleep(0.5)
+        except Exception as e:
+            self._log(f"Handling login portal context warning: {e}")
+
+        # 强力清除任何可能阻挡交互的遮罩层
+        try:
+            self.page.run_js("""
+            var ot = document.getElementById('onetrust-consent-sdk');
+            if (ot) ot.remove();
+            var ov = document.querySelector('.onetrust-pc-dark-filter');
+            if (ov) ov.remove();
+            """)
+        except Exception:
+            pass
+
+        # 2. 建立上下文后,进入轻量页面准备注入 Turnstile
         self._log(f"Loading lightweight origin endpoint: {VFS_CLEAN_ENTRY_URL}")
         self.page.set.timeouts(page_load=15, script=15)
         self.page.get(VFS_CLEAN_ENTRY_URL)
+        time.sleep(1)
         
         self._log("Injecting standalone Cloudflare Turnstile into empty page...")
         inject_js = f"""
@@ -239,10 +292,11 @@ class VfsPlugin(IPlugin):
             </div>
         `;
         window.cf_token = null;
+        window.my_widget_id = undefined;
 
         function initTurnstile() {{
             try {{
-                window.turnstile.render('#my-turnstile', {{
+                window.my_widget_id = window.turnstile.render('#my-turnstile', {{
                     sitekey: '{self.sitekey}',
                     callback: function(token) {{
                         window.cf_token = token;
@@ -337,7 +391,7 @@ class VfsPlugin(IPlugin):
         """
         使用 DrissionPage 创建会话:
         1. 启动浏览器
-        2. 根据 bypass_landing_page 开关选择进入极轻量 404 页面或官方登录首页
+        2. 根据 bypass_landing_page 开关选择建立登录会话上下文并进入轻量页面或官方登录首页
         3. 提取 Turnstile Token
         4. JS fetch 登录
         """
@@ -359,8 +413,8 @@ class VfsPlugin(IPlugin):
             raise BizLogicError("Missing mission/country code config")
 
         if self.bypass_landing_page:
-            self._log("Using clean 404 entry mode (bypass landing page)...")
-            # 1. 准备极轻量页面并注入独占 Turnstile 容器 (绕过首页)
+            self._log("Using bypass landing mode: opening login to establish context, then jumping to bypass landing page...")
+            # 1. 建立登录上下文并跳转至极轻量页面注入独占 Turnstile 容器
             self._prepare_clean_page()
             # 2. 获取 Turnstile Token
             cf_token = self._get_turnstile_token(timeout_sec=60)
@@ -840,7 +894,7 @@ class VfsPlugin(IPlugin):
         
         expected_start = user_inputs.get("expected_start_date", "2000-01-01")
         expected_end = user_inputs.get("expected_end_date", "2100-01-01")
-        if from_date >= expected_end:
+        if from_date > expected_end:
             self._log("No valid slots in date preference.") 
             res.success = False
             return res
@@ -1333,7 +1387,7 @@ class VfsPlugin(IPlugin):
         final_url = ""
         
         try:
-            self._log("Resolving payment redirect...")
+            self._log(f"Resolving payment redirect...<{start_url}>")
             pay_tab = self.page.new_tab(start_url)
             pay_tab.wait.url_change(start_url, timeout=15)
             

+ 37 - 1
vfs_keygen.py

@@ -217,7 +217,8 @@ def upload_account_to_server(account, api_url, api_token):
 # 方案三:轻量独占 Turnstile 注册机器人
 # ==========================================
 class VFSRegistrationBotV3:
-    def __init__(self, proxy=None, email_api_token=None, master_email=None, sitekey=VFS_TURNSTILE_SITEKEY):
+    def __init__(self, vfs_url=None, proxy=None, email_api_token=None, master_email=None, sitekey=VFS_TURNSTILE_SITEKEY):
+        self.vfs_url = vfs_url
         self.proxy_config = proxy
         self.email_api_token = email_api_token
         self.master_email = master_email
@@ -305,9 +306,39 @@ class VFSRegistrationBotV3:
             """)
             return
 
+        # 1. 先打开 login 建立会话上下文与 Cloudflare 信任凭证
+        login_url = (self.vfs_url or "https://visa.vfsglobal.com/irl/en/dnk/login").replace('/register', '/login')
+        self._log(f"Establishing session context via login portal: {login_url}")
+        self.page.set.timeouts(page_load=30, script=20)
+        self.page.get(login_url)
+        time.sleep(3)
+
+        # 处理 OneTrust Cookie 弹窗
+        try:
+            cookie_btn = self.page.ele('#onetrust-accept-btn-handler', timeout=3)
+            if cookie_btn and cookie_btn.states.is_displayed:
+                cookie_btn.click()
+                self._log("Accepted OneTrust cookie consent.")
+                time.sleep(0.5)
+        except Exception:
+            pass
+
+        # 强力清除任何可能阻挡交互的遮罩层
+        try:
+            self.page.run_js("""
+            var ot = document.getElementById('onetrust-consent-sdk');
+            if (ot) ot.remove();
+            var ov = document.querySelector('.onetrust-pc-dark-filter');
+            if (ov) ov.remove();
+            """)
+        except Exception:
+            pass
+
+        # 2. 建立上下文后,进入轻量页面准备注入 Turnstile
         self._log(f"Loading lightweight origin endpoint: {VFS_CLEAN_ENTRY_URL}")
         self.page.set.timeouts(page_load=15, script=15)
         self.page.get(VFS_CLEAN_ENTRY_URL)
+        time.sleep(1)
         
         self._log("Injecting standalone Cloudflare Turnstile into empty page...")
         inject_js = f"""
@@ -851,6 +882,10 @@ class VFSRegistrationBotV3:
             shutil.rmtree(self.workspace, ignore_errors=True)
 
 
+# 保持命名兼容别名
+VFSRegistrationBot = VFSRegistrationBotV3
+
+
 # ==========================================
 # 批量注册入口
 # ==========================================
@@ -922,6 +957,7 @@ def main():
             
             if bot is None:
                 bot = VFSRegistrationBotV3(
+                    vfs_url=args.vfs_url,
                     proxy=proxy_config,
                     email_api_token=args.email_token,
                     master_email=args.master_email,