瀏覽代碼

feat: usa_plugin query book update

jerry 2 月之前
父節點
當前提交
f7be358f76
共有 4 個文件被更改,包括 651 次插入 和 169 次删除
  1. 6 6
      config/test_conf.json
  2. 404 0
      docs/usa_visa_api.md
  3. 235 160
      plugins/usa_plugin.py
  4. 6 3
      standalone.py

+ 6 - 6
config/test_conf.json

@@ -148,8 +148,8 @@
     "usa_plugin": {
       "group_id": "usa.guangzhou",
       "account": {
-        "username": "xiaoyi1996",
-        "password": "Abc147258??"
+        "username": "d26mtrcmoqfg",
+        "password": "VLU02aA!@"
       },
       "appointment_types": [
         {
@@ -163,11 +163,11 @@
       "free_config": {
         "usa_url": "https://www.usvisascheduling.com",
         "location": "Guangzhou",
-        "applicant": "xiaoyi jin",
+        "applicant": "furong wang",
         "security": {
-          "1": "1",
-          "2": "2",
-          "3": "3"
+          "1": "m",
+          "2": "r",
+          "3": "j"
         }
       },
       "user_inputs": {

+ 404 - 0
docs/usa_visa_api.md

@@ -0,0 +1,404 @@
+# 美国签证预约系统 (USVisaScheduling) 核心调度与预约 API 逆向解析
+
+本文档详细记录基于 [page3.txt](file:///Users/hujiarui/workspace/coordinate/page3.txt)(美签预约与改约页面)逆向分析得出的完整接口链路。涵盖了从**查询领事馆可用日期**、**选定日期查询可用时间场次**到**选定时间最终提交预约(改约)**的完整生命周期、参数生成逻辑、Token 状态流转与响应结构。
+
+---
+
+## 目录
+1. [通用通信机制与上下文架构](#一通用通信机制与上下文架构)
+2. [步骤一:查询日历有效日期 (get-family-consular-schedule-days)](#二步骤一查询日历有效日期-get-family-consular-schedule-days)
+3. [步骤二:选定日期查询时间场次 (get-family-consular-schedule-entries)](#三步骤二选定日期查询时间场次-get-family-consular-schedule-entries)
+4. [步骤三:选定时间最终提交改约/预约 (reschedule-consular-appointments-for-family)](#四步骤三选定时间最终提交改约预约-reschedule-consular-appointments-for-family)
+5. [Token 链条流转与安全校验机制](#五token-链条流转与安全校验机制)
+6. [前置依赖接口 (Context APIs)](#六前置依赖接口-context-apis)
+7. [Python / 爬虫自动化调用实践指南](#七python--爬虫自动化调用实践指南)
+
+---
+
+## 一、通用通信机制与上下文架构
+
+USVisaScheduling 基于微软 PowerPages / Dynamics 365 门户构建,所有业务接口均通过统一的代理网关 `custom-actions` 进行转发。
+
+### 1. 通用 URL 格式
+```http
+POST https://www.usvisascheduling.com/zh-CN/custom-actions/?route={route}&appd={contactId}&cacheString={timestamp}
+```
+
+- **`route`**: 目标后端 REST API 路径(如 `/api/v1/schedule-group/...`),需要经过 URL 编码。
+- **`appd`**: 当前登录用户的 Dynamics 365 唯一联系人 ID(`contactId`,例如 `1ffaaf70-b798-f111-b8dc-001dd8084c2e`)。由服务端 Liquid 模板在页面加载时注入到 `window.Microsoft.Dynamic365.Portal.User.contactId`。
+- **`cacheString`**: 客户端当前毫秒级时间戳 `new Date().getTime()`,用于防浏览器 HTTP 缓存。
+
+### 2. 通用请求头规范
+- **`Content-Type`**: `application/x-www-form-urlencoded; charset=UTF-8`
+- **`Accept`**: `application/json, text/javascript, */*; q=0.01`
+- **`X-Requested-With`**: `XMLHttpRequest`
+- **`Cookie`**: 必须包含有效的 `.AspNet.ApplicationCookie`、`ASP.NET_SessionId` 以及 Cloudflare 凭证 `cf_clearance`、`__cf_bm`。
+
+### 3. 通用请求体格式
+请求体不是标准的 raw JSON,而是 URL 表单格式,包含单一字段 `parameters`,其值为序列化后的 JSON 字符串:
+```http
+parameters={"primaryId":"...","postId":"..."}
+```
+
+---
+
+## 二、步骤一:查询日历有效日期 (get-family-consular-schedule-days)
+
+当用户在页面选择领事馆下拉框(触发 `onPostChange` -> `getScheduleDays`)时调用。
+
+### 1. 接口信息
+- **Route**: `/api/v1/schedule-group/get-family-consular-schedule-days`
+- **Method**: `POST`
+- **URL 示例**:
+  `https://www.usvisascheduling.com/zh-CN/custom-actions/?route=/api/v1/schedule-group/get-family-consular-schedule-days&appd=1ffaaf70-b798-f111-b8dc-001dd8084c2e&cacheString=1788279318000`
+
+### 2. 请求参数 (`parameters` JSON)
+```json
+{
+  "primaryId": "e048e82b-b998-f111-a3d0-001dd811d743",
+  "applications": [
+    "e048e82b-b998-f111-a3d0-001dd811d743"
+  ],
+  "postId": "a26af614-b0db-ec11-a7b4-001dd80234f6",
+  "isReschedule": "true"
+}
+```
+
+| 字段 | 类型 | 说明 |
+| :--- | :--- | :--- |
+| `primaryId` | string | 主申请人的申请 GUID |
+| `applications` | array[string] | 本组参与预约的所有申请人 ApplicationID 列表 |
+| `postId` | string | 目标领事馆 ID(如广州 `a26af614-b0db-ec11-a7b4-001dd80234f6`) |
+| `isReschedule` | string | 是否为重新预约/改约。改约传 `"true"`,首约无此字段 |
+
+### 3. 响应结果结构
+```json
+{
+  "ScheduleDays": [
+    {
+      "Date": "2027-04-06T00:00:00.000Z",
+      "ID": null
+    },
+    {
+      "Date": "2027-04-13T00:00:00.000Z",
+      "ID": null
+    }
+  ],
+  "Token": "vh1NDnyPCFtEY1v6DUeVr6JmX8xZiugeSoWa5IejTM3uf4NymCUhXduPuuG3Kr+SG0Kbj70MsO5ZVz8Z...",
+  "LocalizedGenericErrorMessage": null,
+  "HasError": false,
+  "ErrorCount": 0,
+  "Errors": {
+    "m_StringValue": ""
+  }
+}
+```
+
+### 4. 逻辑解析与状态转移
+1. **返回有效日期**:`ScheduleDays` 包含所有有号的日期列表(格式为 ISO 字符串)。前端 jQuery UI Datepicker 利用该列表将有效日期高亮标记为绿色(`greenday`),其余日期置灰禁选(`redday`)。
+2. **签发阶段性 Token(Token-1)**:返回由服务端生成的超长加密签名 `data.Token`。前端将其暂存在全局变量 `token` 和 `sd` 中。**下一步查询具体时间必须携带此 Token。**
+3. 接口调用成功后,前端执行 `delete jsdata["isReschedule"]`,将其从全局对象中清理。
+
+---
+
+## 三、步骤二:选定日期查询时间场次 (get-family-consular-schedule-entries)
+
+当用户在日历上点击某个具体日期(触发 Datepicker `onSelect` -> `getScheduleEntries`)时调用。
+
+### 1. 接口信息
+- **Route**: `/api/v1/schedule-group/get-family-consular-schedule-entries`
+- **Method**: `POST`
+- **URL 示例**:
+  `https://www.usvisascheduling.com/zh-CN/custom-actions/?route=/api/v1/schedule-group/get-family-consular-schedule-entries&appd=1ffaaf70-b798-f111-b8dc-001dd8084c2e&cacheString=1788279602440`
+
+### 2. 请求参数 (`parameters` JSON)
+```json
+{
+  "primaryId": null,
+  "applications": null,
+  "scheduleDayId": null,
+  "scheduleEntryId": "",
+  "postId": null,
+  "Token": "vh1NDnyPCFtEY1v6DUeVr6JmX8xZiugeSoWa5IejTM3uf4NymCUhXduPuuG3Kr+SG0Kbj70MsO5ZVz8Z...",
+  "Date": "2027-04-13T00:00:00.000Z",
+  "isReschedule": "true"
+}
+```
+
+| 字段 | 类型 | 说明 |
+| :--- | :--- | :--- |
+| `Token` | string | **步骤一所返回的 `Token`**(必须原样带回,否则服务端无法校验上下文) |
+| `Date` | string | 选中的目标日期,前端代码强制转换成了 **UTC 时间格式的 ISO 8601 字符串** |
+| `postId` | null | **前端代码显式重置为 `null`**(由于已包含在 Token 加密体中) |
+| `primaryId` | null | **前端代码显式重置为 `null`** |
+| `applications` | null | **前端代码显式重置为 `null`** |
+| `scheduleDayId` | null | 选中日期对象中的 ID(改约中 `ScheduleDays[i].ID` 原生为 `null`) |
+| `scheduleEntryId`| string | 默认传空字符串 `""` |
+| `isReschedule` | string | 改约传 `"true"` |
+
+### 3. 响应结果结构
+```json
+{
+  "ScheduleDays": null,
+  "ScheduleEntries": [
+    {
+      "ID": null,
+      "EntriesAvailable": 65,
+      "Time": "08:00",
+      "Num": 1
+    },
+    {
+      "ID": null,
+      "EntriesAvailable": 10,
+      "Time": "08:15",
+      "Num": 2
+    }
+  ],
+  "CategoryID": "00000000-0000-0000-0000-000000000000",
+  "Token": "vh1NDnyPCFtEY1v6DUeVr9hrexujYVBF52kp3AQ9ZKKtM+OLs8L6VxN7zGa2imaTZU4+A4PiMT/19fgosSVAiw2S9mV1G1+FTWnWpIwShet0U/0E2Vnn3RfHpZFOe5Lo...",
+  "LocalizedGenericErrorMessage": null,
+  "HasError": false,
+  "ErrorCount": 0,
+  "Errors": {
+    "m_StringValue": ""
+  },
+  "ErrorString": "<br>"
+}
+```
+
+### 4. 逻辑解析与状态转移
+1. **返回时间场次列表**:`ScheduleEntries` 返回当天所有开放的时间槽。
+   - `Time`: 时间文本(如 `"08:00"`)。
+   - `EntriesAvailable`: 该场次当前剩余可约配额数(如 `65`)。
+   - `Num`: 场次递增序号(`1`, `2`, ...)。
+2. **UI 渲染**:前端将每个条目渲染为一个单选框 `<input type="radio" value="Num">`。用户点击单选框时,将该单选框的 value 赋值给 `jsdata.Num`。
+3. **升级签发最终预约 Token(Token-2)**:服务端在响应中返回了全新的 `data.Token`。该 Token 已经绑定了前一步选择的 `Date` 且包含了最新的时间槽校验信息。前端更新全局变量 `token = data.Token;`。
+
+---
+
+## 四、步骤三:选定时间最终提交改约/预约 (reschedule-consular-appointments-for-family)
+
+当用户勾选了某个单选框(如 08:00 对应 `Num=1`)并点击“提交预约”按钮(触发 `onClickSubmit`)时调用。
+
+### 1. 接口信息
+- **Route**: `/api/v1/schedule-group/reschedule-consular-appointments-for-family`
+- **Method**: `POST`
+- **URL 示例**:
+  `https://www.usvisascheduling.com/zh-CN/custom-actions/?route=/api/v1/schedule-group/reschedule-consular-appointments-for-family&appd=1ffaaf70-b798-f111-b8dc-001dd8084c2e&cacheString=1788279318091`
+
+### 2. 请求参数 (`parameters` JSON)
+```json
+{
+  "primaryId": null,
+  "applications": null,
+  "scheduleDayId": null,
+  "scheduleEntryId": "",
+  "postId": null,
+  "Token": "vh1NDnyPCFtEY1v6DUeVr9hrexujYVBF52kp3AQ9ZKKtM+OLs8L6VxN7zGa2imaTZU4+A4PiMT...",
+  "Date": "2027-04-13T00:00:00.000Z",
+  "Num": "1"
+}
+```
+
+| 字段 | 类型 | 说明 |
+| :--- | :--- | :--- |
+| `Token` | string | **步骤二返回的最终预约 `Token`** |
+| `Date` | string | 选中的目标日期(UTC ISO 字符串,与步骤二保持一致) |
+| `Num` | string | 选中的具体时间场次编号(来自选中的 Radio 的 value,如 `"1"`) |
+| `primaryId` / `postId` / `applications` | null | 保持为 `null` |
+| `scheduleDayId` | null | 保持为 `null` |
+| `scheduleEntryId`| string | 保持为空字符串 `""` |
+
+### 3. 响应结果结构
+
+#### 成功响应:
+```json
+{
+  "HasError": false,
+  "AllScheduled": true,
+  "RedirectStub": "appointment-confirmation/",
+  "Errors": {
+    "m_StringValue": ""
+  }
+}
+```
+- **成功标志**:`HasError === false` 且 `AllScheduled === true`。
+- **跳转页面**:客户端收到响应后,自动跳转至 `/zh-CN/appointment-confirmation/` 查看预约确认单。
+
+#### 常见失败响应与错误码:
+```json
+{
+  "HasError": true,
+  "Errors": {
+    "m_StringValue": "PSE0612"
+  }
+}
+```
+- **`PSE0601`**: 预约选择无效(场次已被抢占或日期过期)。
+- **`PSE0602`**: 缺失关键信息或请求的更改不允许,需要关闭申请后重开。
+- **`PSE0612`**: 重新安排预约失败,需要联系客服中心。
+- **`PSE0610`**: 系统未知异常。
+
+---
+
+## 五、Token 链条流转与安全校验机制
+
+系统通过不可伪造的服务端加密 Token 实现了严格的时序防御,其流转全生命周期如下:
+
+```mermaid
+sequenceDiagram
+    autonumber
+    participant Client as 客户端浏览器
+    participant Gateway as custom-actions 网关
+    participant Backend as 预约系统后端
+
+    Note over Client,Backend: 阶段一:查询领事馆排期日历
+    Client->>Gateway: POST get-family-consular-schedule-days (带 postId, primaryId, applications)
+    Gateway->>Backend: 校验用户权限与领事馆
+    Backend-->>Gateway: 返回 ScheduleDays + 签发 Token-1 (日期级凭证)
+    Gateway-->>Client: 返回包含 ScheduleDays 和 Token-1 的 JSON
+
+    Note over Client,Backend: 阶段二:选定日期获取具体时间槽
+    Client->>Gateway: POST get-family-consular-schedule-entries (带 Date + Token-1)
+    Gateway->>Backend: 验证 Token-1 合法性及请求频率
+    Backend-->>Gateway: 返回 ScheduleEntries (各场次Num与余票) + 签发 Token-2 (场次级凭证)
+    Gateway-->>Client: 返回包含时间场次和 Token-2 的 JSON
+
+    Note over Client,Backend: 阶段三:选定时间槽最终提交占位
+    Client->>Gateway: POST reschedule-consular-appointments-for-family (带 Date + Num + Token-2)
+    Gateway->>Backend: 校验 Token-2,原子性扣减配额并写入预约
+    Backend-->>Gateway: 返回 AllScheduled: true, RedirectStub: appointment-confirmation/
+    Gateway-->>Client: 改约成功,跳转确认页
+```
+
+### 核心安全机制:
+1. **防跳步验证**:如果不先调步骤一,就无法获得 `Token-1`;没有 `Token-1`,步骤二直接报错 400/403;没有步骤二返回的 `Token-2`,直接调用步骤三会导致签名校验失败。
+2. **单次消费(Nonce 特性)**:`Token-2` 一旦被步骤三消费,便立即作废,无法重复提交。
+3. **参数置空设计**:在步骤二和步骤三中,`postId`、`primaryId`、`applications` 被前端代码置为 `null`,因为这些敏感实体在步骤一生成 `Token` 时已被服务端哈希并加密在 Token 密文中,避免客户端篡改申请人 ID。
+
+---
+
+## 六、前置依赖接口 (Context APIs)
+
+在进入日期查询之前,页面通过以下两个接口加载基础上下文:
+
+### 1. 查询家庭成员与申请人列表 (`queryFamilyMembers`)
+- **Route**: 由前端在 `onVisaClassSelectChange` 中触发。
+- **作用**: 提取同组所有申请人的 `ApplicationID`(对应全局 `applications` 数组)和姓名,填充页面 `#gm_select`。
+
+### 2. 查询可选领事馆列表 (`query-consular-posts`)
+- **Route**: `/api/v1/schedule-group/query-consular-posts`
+- **Method**: `POST`
+- **请求参数**:
+  ```json
+  { "applicationId": "e048e82b-b998-f111-a3d0-001dd811d743" }
+  ```
+- **作用**: 动态获取该类别申请允许预约的领事馆列表(返回各城市的 `Id` 与 `Name`),填充 `#post_select`。
+
+---
+
+## 七、Python / 爬虫自动化调用实践指南
+
+在编写自动化爬虫(如基于 DrissionPage / Playwright / Selenium)时,推荐采用**“浏览器内直发 API 请求 (`run_js`)”**的方式,兼顾稳定性和速度:
+
+### 示例:在当前会话直接查询日期 (直发 API)
+```python
+def fetch_available_dates_via_js(page, post_id: str, appd: str) -> dict:
+    js_code = """
+    const post_id = arguments[0];
+    const appd = arguments[1];
+    const cacheString = new Date().getTime();
+    const route = "/api/v1/schedule-group/get-family-consular-schedule-days";
+    
+    // 复用页面已就绪的 jsdata 上下文
+    jsdata['postId'] = post_id;
+    jsdata['isReschedule'] = "true";
+    
+    return new Promise((resolve) => {
+        $.ajax({
+            url: "/zh-CN/custom-actions/?route=" + encodeURI(route) + "&appd=" + appd + "&cacheString=" + cacheString,
+            type: "POST",
+            data: "parameters=" + JSON.stringify(jsdata),
+            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+            dataType: "json",
+            success: (data) => resolve({ success: true, data: data }),
+            error: (xhr) => resolve({ success: false, status: xhr.status, text: xhr.responseText })
+        });
+    });
+    """
+    return page.run_js(js_code, post_id, appd)
+```
+
+### 示例:在当前会话直接拉取时间场次 (直发 API)
+```python
+def fetch_time_slots_via_js(page, selected_date: str, token_1: str, appd: str) -> dict:
+    js_code = """
+    const selectedDate = arguments[0];
+    const token1 = arguments[1];
+    const appd = arguments[2];
+    const cacheString = new Date().getTime();
+    const route = "/api/v1/schedule-group/get-family-consular-schedule-entries";
+    
+    // 构造请求参数,置空 ID
+    const payload = {
+        primaryId: null,
+        applications: null,
+        scheduleDayId: null,
+        scheduleEntryId: "",
+        postId: null,
+        Token: token1,
+        Date: new Date(selectedDate).toISOString(),
+        isReschedule: "true"
+    };
+    
+    return new Promise((resolve) => {
+        $.ajax({
+            url: "/zh-CN/custom-actions/?route=" + encodeURI(route) + "&appd=" + appd + "&cacheString=" + cacheString,
+            type: "POST",
+            data: "parameters=" + JSON.stringify(payload),
+            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+            dataType: "json",
+            success: (data) => resolve({ success: true, data: data }),
+            error: (xhr) => resolve({ success: false, status: xhr.status, text: xhr.responseText })
+        });
+    });
+    """
+    return page.run_js(js_code, selected_date, token_1, appd)
+```
+
+### 示例:极速提交改约预定
+```python
+def submit_reschedule_via_js(page, selected_date: str, slot_num: int, token_2: str, appd: str) -> dict:
+    js_code = """
+    const selectedDate = arguments[0];
+    const slotNum = String(arguments[1]);
+    const token2 = arguments[2];
+    const appd = arguments[3];
+    const cacheString = new Date().getTime();
+    const route = "/api/v1/schedule-group/reschedule-consular-appointments-for-family";
+    
+    const payload = {
+        primaryId: null,
+        applications: null,
+        scheduleDayId: null,
+        scheduleEntryId: "",
+        postId: null,
+        Token: token2,
+        Date: new Date(selectedDate).toISOString(),
+        Num: slotNum
+    };
+    
+    return new Promise((resolve) => {
+        $.ajax({
+            url: "/zh-CN/custom-actions/?route=" + encodeURI(route) + "&appd=" + appd + "&cacheString=" + cacheString,
+            type: "POST",
+            data: "parameters=" + JSON.stringify(payload),
+            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+            dataType: "json",
+            success: (data) => resolve({ success: true, data: data }),
+            error: (xhr) => resolve({ success: false, status: xhr.status, text: xhr.responseText })
+        });
+    });
+    """
+    return page.run_js(js_code, selected_date, slot_num, token_2, appd)
+```

+ 235 - 160
plugins/usa_plugin.py

@@ -51,7 +51,8 @@ class UsaLoginFlow(BaseFlow):
             max_stuck_cycles=30
         )
         self.plugin = plugin
-        self.has_submitted_login = False
+        self.login_submit_attempts = 0
+        self.last_login_submit_time = 0.0
 
     # --- 异常守卫与自愈 (Priority 5~7) ---
     @guard(text="502 Bad Gateway", priority=5)
@@ -100,9 +101,31 @@ class UsaLoginFlow(BaseFlow):
     # --- 状态流转与表单处理 (Priority 35~50) ---
     @on(ele="#signInName", priority=50)
     def handle_login_form(self):
-        if self.has_submitted_login:
+        # 1. 冷却保护:若距离上次提交不足 15 秒,避免高频点击,静候跳转
+        if time.time() - self.last_login_submit_time < 15.0:
+            self.log("Login form recently submitted, waiting for redirect...")
+            time.sleep(2)
             return
-        self.log("[State] Login page detected. Submitting credentials...")
+
+        # 2. 检查是否有页面报错(如凭证无效、被锁等)
+        err_ele = (
+            self.page.ele('.pageLevel', timeout=0.2)
+            or self.page.ele('.claimVerificationServerError', timeout=0.2)
+            or self.page.ele('.error:not([aria-hidden="true"])', timeout=0.2)
+        )
+        if err_ele and err_ele.text:
+            err_msg = err_ele.text.strip().replace('\n', ' ')
+            self.log(f"[WARN] 登录页面提示错误: '{err_msg}'", level="warning")
+            if any(k in err_msg.lower() for k in ["invalid", "无效", "locked", "锁定"]):
+                if self.login_submit_attempts >= 2:
+                    raise BizLogicError(f"美签登录凭据无效或账号被锁定: {err_msg}")
+
+        # 3. 最大重试上限防护
+        if self.login_submit_attempts >= 5:
+            raise BizLogicError("登录失败:已重试 5 次登录仍停留在登录页面,请检查账号密码或代理网络。")
+
+        self.login_submit_attempts += 1
+        self.log(f"[State] Login page detected. Submitting credentials (attempt {self.login_submit_attempts}/5)...")
         username = self.plugin.config.account.username
         password = self.plugin.config.account.password
 
@@ -110,20 +133,21 @@ class UsaLoginFlow(BaseFlow):
         self.plugin.mouse.human_click_ele(username_input)
         username_input.clear()
         self.plugin.keyboard.type_text(username, humanize=True)
-        self.plugin._random_sleep(3, 5)
+        self.plugin._random_sleep(2, 4)
 
         password_input = self.page.ele('#password')
         self.plugin.mouse.human_click_ele(password_input)
         password_input.clear()
         self.plugin.keyboard.type_text(password, humanize=True)
-        self.plugin._random_sleep(3, 5)
+        self.plugin._random_sleep(2, 4)
 
         continue_btn = self.page.ele('#continue')
         if continue_btn:
             self.plugin.mouse.human_click_ele(continue_btn)
-        self.has_submitted_login = True
+
+        self.last_login_submit_time = time.time()
         self.log("Login form submitted. Waiting for the next step to load...")
-        self.plugin._random_sleep(30, 40)
+        self.plugin._random_sleep(10, 15)
 
     def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]:
         if not security:
@@ -189,27 +213,11 @@ class UsaLoginFlow(BaseFlow):
         self.log("Security answers submitted. Waiting for redirection...")
         self.plugin._random_sleep(30, 40)
 
-    @on(ele="#continue_application", priority=30)
-    def handle_continue_application(self):
-        self.log("Found '#continue_application' (安排预约), clicking to proceed...")
-        schedule_btn = self.page.ele('#continue_application')
-        if schedule_btn:
-            self.plugin.mouse.human_click_ele(schedule_btn)
-        self.plugin._random_sleep(15, 25)
-
     @on(ele="#atlas-sidebar", priority=35)
     def handle_dashboard_sidebar(self):
         self.log("[State] At the main booking dashboard. Looking for navigation button...")
 
-        # 1. 优先检查继续/安排预约按钮 (#continue_application)
-        continue_btn = self.page.ele('#continue_application', timeout=0.5)
-        if continue_btn:
-            self.log("Found '#continue_application' (安排预约), clicking to proceed...")
-            self.plugin.mouse.human_click_ele(continue_btn)
-            self.plugin._random_sleep(15, 25)
-            return
-
-        # 2. 检查重新安排预约按钮 (#reschedule_appointment)
+        # 1. 优先检查重新安排预约按钮 (#reschedule_appointment,针对已有预约账号的改约)
         reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
         if reschedule_btn:
             self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...")
@@ -217,7 +225,7 @@ class UsaLoginFlow(BaseFlow):
             self.plugin._random_sleep(15, 25)
             return
 
-        # 3. 检查首次预约按钮 (#schedule_appointment)
+        # 2. 检查首次预约按钮 (#schedule_appointment)
         schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5)
         if schedule_btn:
             self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...")
@@ -225,7 +233,7 @@ class UsaLoginFlow(BaseFlow):
             self.plugin._random_sleep(15, 25)
             return
 
-        # 4. 检查动态注入的 admin_link 安排预约
+        # 3. 检查动态注入的 admin_link 安排预约
         admin_link = self.page.ele('#admin_link', timeout=0.5)
         if admin_link:
             self.log("Found '#admin_link' (安排预约), clicking to proceed...")
@@ -233,10 +241,10 @@ class UsaLoginFlow(BaseFlow):
             self.plugin._random_sleep(15, 25)
             return
 
-        # 5. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本为 '安排预约' 的链接
+        # 4. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本匹配预约/改约的链接
         fallback_link = (
             self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5)
-            or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "Schedule")]', timeout=0.5)
+            or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "重新安排预约") or contains(text(), "Schedule") or contains(text(), "Reschedule")]', timeout=0.5)
         )
         if fallback_link:
             self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...")
@@ -321,9 +329,15 @@ class UsaPlugin(IVSPlg):
         if self.page is None:
             return False
         try:
+            # 优先关闭可能阻塞页面的 alert 弹窗,防止阻断 run_js 执行
+            try:
+                self.page.handle_alert(accept=True, timeout=0.2)
+            except Exception:
+                pass
+
             if not self.page.run_js("return 1;"):
                 return False
-        except:
+        except Exception:
             return False
             
         if self.config.session_max_life > 0:
@@ -334,6 +348,34 @@ class UsaPlugin(IVSPlg):
                 return False
         return True
 
+    def _refresh_and_bypass_cf(self):
+        """
+        处理长时间静置后由于 Cloudflare 凭据失效导致的拦截(如页面弹窗“服务不可用”),
+        关闭弹窗并主动刷新页面,触发并穿透 Cloudflare 5 秒盾以获取新 token。
+        """
+        self._log("Refreshing page to trigger and solve Cloudflare 5s shield...")
+        try:
+            self.page.handle_alert(accept=True, timeout=0.5)
+        except Exception:
+            pass
+
+        self.page.refresh()
+        self._random_sleep(2, 4)
+
+        # 刷新后若弹出 5 秒盾挑战,使用 CloudflareBypasser 进行穿透
+        cf_bypasser = CloudflareBypasser(self.page, log=True, logger=self._log)
+        page_title = (getattr(self.page, "title", "") or "").lower()
+        if not cf_bypasser.is_bypassed() or any(w in page_title for w in ["just a moment", "请稍候", "attention required", "cloudflare"]):
+            self._log("🛡️ 检测到刷新后触发 Cloudflare 5秒盾,正在进行穿透...")
+            if not cf_bypasser.bypass(max_retry=8):
+                raise BizLogicError("Cloudflare 5秒盾穿透超时")
+            self._random_sleep(2, 4)
+            cf_bypasser.handle_waiting_room()
+
+        # 等待排期页面核心元素重新加载完成
+        self.page.ele("css:#gm_select label", timeout=30)
+        self.page.ele("css:#post_select option:not([value=''])", timeout=30)
+
     def create_session(self) -> None:
         """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
         self._log(f"Initializing Session (ID: {self.instance_id})...")
@@ -380,142 +422,175 @@ class UsaPlugin(IVSPlg):
         res = VSQueryResult()
         res.success = False
 
-        current_url = (getattr(self.page, "url", "") or "").lower()
-        if "schedule" not in current_url:
-            self._log(f"Current url '{current_url}' not on schedule page, navigating...")
-            schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
-            self.page.get(schedule_url)
-            self._random_sleep(3, 5)
-        else:
-            self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
-
-        if "just a moment" in (getattr(self.page, "title", "") or "").lower():
-            cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
-            if not cf_bypasser.bypass(max_retry=5):
-                raise BizLogicError("Cloudflare bypass timeout")
-            self._random_sleep(3, 5)
-            cf_bypasser.handle_waiting_room()
-
-        current_url = (getattr(self.page, "url", "") or "").lower()
-        if 'auth' in current_url or 'login' in current_url:
-            self.is_healthy = False
-            raise SessionExpiredOrInvalidError()
+        location_name = (self.free_config.get('location') or "").strip()
 
-        # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
-        self._log("Waiting for applicant list (#gm_select) to populate...")
-        self.page.ele("css:#gm_select label", timeout=30)
+        # 最多尝试 2 次:首次查询 + 若遇 alert/超时则刷新过 5 秒盾重试
+        for attempt in range(2):
+            # 1. 检查并清理可能存在的残留弹窗
+            try:
+                alert_text = self.page.handle_alert(accept=True, timeout=0.5)
+                if alert_text:
+                    self._log(f"[WARN] 发现并关闭残留弹窗: '{alert_text}'")
+            except Exception:
+                pass
 
-        # 2. 等待领事馆下拉框选项加载完成(从 page1 仅空 option 异步加载到 page2 包含各领事馆 option)
-        self._log("Waiting for consular post options to populate in #post_select...")
-        post_select = self.page.ele('#post_select', timeout=30)
-        if not post_select:
-            raise BizLogicError("Element #post_select not found.")
+            current_url = (getattr(self.page, "url", "") or "").lower()
+            if "schedule" not in current_url:
+                self._log(f"Current url '{current_url}' not on schedule page, navigating...")
+                schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
+                self.page.get(schedule_url)
+                self._random_sleep(3, 5)
+            else:
+                self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
+
+            if "just a moment" in (getattr(self.page, "title", "") or "").lower():
+                cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
+                if not cf_bypasser.bypass(max_retry=5):
+                    raise BizLogicError("Cloudflare bypass timeout")
+                self._random_sleep(3, 5)
+                cf_bypasser.handle_waiting_room()
+
+            current_url = (getattr(self.page, "url", "") or "").lower()
+            if 'auth' in current_url or 'login' in current_url:
+                self.is_healthy = False
+                raise SessionExpiredOrInvalidError()
+
+            # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
+            self._log("Waiting for applicant list (#gm_select) to populate...")
+            self.page.ele("css:#gm_select label", timeout=30)
+
+            # 2. 等待领事馆下拉框选项加载完成
+            self._log("Waiting for consular post options to populate in #post_select...")
+            post_select = self.page.ele('#post_select', timeout=30)
+            if not post_select:
+                if attempt == 0:
+                    self._log("[WARN] 未找到 #post_select,尝试刷新页面刷新 token...")
+                    self._refresh_and_bypass_cf()
+                    continue
+                raise BizLogicError("Element #post_select not found.")
+
+            # 等待至少出现一个有效选项
+            self.page.ele("css:#post_select option:not([value=''])", timeout=30)
+
+            # 获取所有已加载的领事馆 options
+            all_options = post_select.eles("tag:option")
+            available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
+            opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
+            self._log(f"Available consular posts: {opts_summary}")
+
+            # 3. 匹配目标领事馆
+            matched_id = None
+
+            # 策略 A: 优先检查 LOCATIONS 字典
+            known_info = self.LOCATIONS.get(location_name.upper())
+            if known_info:
+                target_id = known_info["id"]
+                if any(opt.attrs.get("value") == target_id for opt in available_options):
+                    matched_id = target_id
+
+            # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
+            if not matched_id:
+                for opt in available_options:
+                    opt_text = (getattr(opt, "text", "") or "").upper()
+                    if location_name.upper() in opt_text:
+                        matched_id = opt.attrs.get("value")
+                        break
+
+            # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
+            if not matched_id and available_options:
+                fallback_opt = available_options[0]
+                matched_id = fallback_opt.attrs.get("value")
+                self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
+
+            if not matched_id:
+                raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
+
+            # 开启监听目标 API
+            target_api = 'get-family-consular-schedule-days'
+            self.page.listen.start(target_api)
+
+            # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
+            self._log(f"Selecting consular post ID: {matched_id}...")
+            post_select.select.by_value(matched_id)
+            try:
+                self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
+            except Exception as e:
+                self._log(f"[DEBUG] Triggering change event via JS: {e}")
 
-        # 等待至少出现一个有效选项
-        self.page.ele("css:#post_select option:not([value=''])", timeout=30)
+            # 5. 等待拦截 API 响应 (设置超时时间)
+            self._log("Waiting for schedule dates API response...")
+            packet = self.page.listen.wait(timeout=20)
+            self.page.listen.stop()
 
-        # 获取所有已加载的领事馆 options
-        all_options = post_select.eles("tag:option")
-        available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
-        opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
-        self._log(f"Available consular posts: {opts_summary}")
+            # 检查是否有 alert 弹出(如“服务不可用”)
+            alert_msg = None
+            try:
+                alert_msg = self.page.handle_alert(accept=True, timeout=1.0)
+            except Exception:
+                pass
 
-        # 3. 匹配目标领事馆
-        location_name = (self.free_config.get('location') or "").strip()
-        matched_id = None
-
-        # 策略 A: 优先检查 LOCATIONS 字典
-        known_info = self.LOCATIONS.get(location_name.upper())
-        if known_info:
-            target_id = known_info["id"]
-            if any(opt.attrs.get("value") == target_id for opt in available_options):
-                matched_id = target_id
-
-        # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
-        if not matched_id:
-            for opt in available_options:
-                opt_text = (getattr(opt, "text", "") or "").upper()
-                if location_name.upper() in opt_text:
-                    matched_id = opt.attrs.get("value")
-                    break
-
-        # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
-        if not matched_id and available_options:
-            fallback_opt = available_options[0]
-            matched_id = fallback_opt.attrs.get("value")
-            self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
-
-        if not matched_id:
-            raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
-
-        # 开启监听目标 API
-        target_api = 'get-family-consular-schedule-days'
-        self.page.listen.start(target_api)
-
-        # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
-        self._log(f"Selecting consular post ID: {matched_id}...")
-        post_select.select.by_value(matched_id)
-        try:
-            self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
-        except Exception as e:
-            self._log(f"[DEBUG] Triggering change event via JS: {e}")
-
-        # 5. 等待拦截 API 响应 (设置超时时间)
-        self._log("Waiting for schedule dates API response...")
-        packet = self.page.listen.wait(timeout=30)
-        self.page.listen.stop()
-
-        if not packet:
-            raise BizLogicError("Timeout waiting for schedule API response")
-
-        status_code = packet.response.status
-        body = packet.response.body
-        if isinstance(body, bytes):
-            body = body.decode("utf-8", errors="ignore")
-        self._log(f"API Response Status: {status_code}")
-
-        # 处理 HTTP 返回码不是200的情况
-        if status_code != 200:
-            err_text = str(body)[:512]
-            if status_code == 403:
-                raise PermissionDeniedError(f"HTTP 403: {err_text}")
-            if status_code == 429:
-                self.is_healthy = False
-                raise RateLimiteddError(f"HTTP 429: {err_text}")
-            raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
-
-        # 6. 解析返回的数据
-        available_dates = []
-        data = body if isinstance(body, dict) else None
-        if not data:
-            match = re.search(r'(\{.*\})', str(body), re.DOTALL)
-            data = json.loads(match.group(1)) if match else json.loads(str(body))
-
-        schedule_days = data.get("ScheduleDays", [])
-        if schedule_days:
-            for day_obj in schedule_days:
-                date_str = day_obj.get("Date")
-                if date_str:
-                    available_dates.append(date_str)
-
-        # 6. 处理最终结果
-        if available_dates:
-            available_dates.sort()
-            res.success = True
-            res.availability_status = AvailabilityStatus.Available
-            earliest_date = available_dates[0]
-            res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
-            res.availability = [
-                DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
-                for d in available_dates
-            ]
-            self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
-        else:
-            res.success = False
-            res.availability_status = AvailabilityStatus.NoneAvailable
-            self._log("No slots available.")
-            
-        return res
+            if alert_msg or not packet:
+                if attempt == 0:
+                    self._log(f"[WARN] 查询未成功 (alert='{alert_msg}', packet={bool(packet)}),判定为长时间未操作导致凭据失效。正在刷新页面并解决 5 秒盾...")
+                    self._refresh_and_bypass_cf()
+                    continue
+                else:
+                    if alert_msg:
+                        raise BizLogicError(f"页面弹出提示: {alert_msg}")
+                    raise BizLogicError("Timeout waiting for schedule API response")
+
+            status_code = packet.response.status
+            body = packet.response.body
+            if isinstance(body, bytes):
+                body = body.decode("utf-8", errors="ignore")
+            self._log(f"API Response Status: {status_code}")
+
+            # 处理 HTTP 返回码不是200的情况
+            if status_code != 200:
+                err_text = str(body)[:512]
+                if status_code == 403:
+                    if attempt == 0:
+                        self._log(f"[WARN] HTTP 403 权限受限,尝试刷新页面过 5 秒盾...")
+                        self._refresh_and_bypass_cf()
+                        continue
+                    raise PermissionDeniedError(f"HTTP 403: {err_text}")
+                if status_code == 429:
+                    self.is_healthy = False
+                    raise RateLimiteddError(f"HTTP 429: {err_text}")
+                raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
+
+            # 6. 解析返回的数据
+            available_dates = []
+            data = body if isinstance(body, dict) else None
+            if not data:
+                match = re.search(r'(\{.*\})', str(body), re.DOTALL)
+                data = json.loads(match.group(1)) if match else json.loads(str(body))
+
+            schedule_days = data.get("ScheduleDays", [])
+            if schedule_days:
+                for day_obj in schedule_days:
+                    date_str = day_obj.get("Date")
+                    if date_str:
+                        available_dates.append(date_str)
+
+            # 6. 处理最终结果
+            if available_dates:
+                available_dates.sort()
+                res.success = True
+                res.availability_status = AvailabilityStatus.Available
+                earliest_date = available_dates[0]
+                res.earliest_date = datetime.strptime(earliest_date, "%Y-%m-%d")
+                res.availability = [
+                    DateAvailability(date=datetime.strptime(d, "%Y-%m-%d"), times=[])
+                    for d in available_dates
+                ]
+                self._log(f"Slot Found! earliest_date={earliest_date}, size={len(available_dates)}")
+            else:
+                res.success = False
+                res.availability_status = AvailabilityStatus.NoneAvailable
+                self._log("No slots available.")
+                
+            return res
 
     def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
         """进行预约操作"""

+ 6 - 3
standalone.py

@@ -196,8 +196,9 @@ class StandaloneGCO:
         try:
             instance.create_session()
             self.m_last_login_time = time.time()
-            self.m_next_query_time = time.time() + self._get_wait_interval()
-            self._log("Session created successfully.")
+            interval = self._get_wait_interval()
+            self.m_next_query_time = time.time() + interval
+            self._log(f"Session created successfully. Initial query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')}).")
         except Exception:
             self._cleanup_instance("session creation failed")
             raise
@@ -252,7 +253,9 @@ class StandaloneGCO:
                 self._log(f"Querying slots for {apt_type.routing_key}...")
                 query_result = self.m_instance.query(apt_type)
                 query_result.apt_type = apt_type
-                self.m_next_query_time = time.time() + self._get_wait_interval()
+                interval = self._get_wait_interval()
+                self.m_next_query_time = time.time() + interval
+                self._log(f"Next query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')})...")
                 self._notify_date_changes(query_result)
 
                 # 5. 发现档期,执行自动预定