合并 dev:发布 Docker 多架构与完善项目文档
This commit is contained in:
commit
0f77607d57
259 files changed
+26813
-6620
No files matched your search
@@ -1,5 +1,7 @@
|
||||
.git
|
||||
.gitignore
|
||||
.env
|
||||
.env.*
|
||||
data
|
||||
browser_data
|
||||
frontend/node_modules
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# 复制为 .env 后再填写。不要提交包含真实密钥的 .env。
|
||||
COMPOSE_PROJECT_NAME=xianyu
|
||||
|
||||
# PostgreSQL 17
|
||||
POSTGRES_IMAGE=postgres:17-trixie
|
||||
POSTGRES_DB=xianyu
|
||||
POSTGRES_USER=xianyu
|
||||
POSTGRES_PASSWORD=请替换为高强度数据库密码
|
||||
# 密码含有特殊字符时,必须先进行 URL 编码。
|
||||
DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgres:5432/xianyu?sslmode=disable
|
||||
|
||||
# 应用
|
||||
XIANYU_IMAGE=ghcr.io/christ9038/xinayu-go:dev
|
||||
XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥
|
||||
XIANYU_BIND_ADDRESS=0.0.0.0
|
||||
XIANYU_HTTP_PORT=8080
|
||||
XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
TZ=Asia/Shanghai
|
||||
LOG_LEVEL=info
|
||||
LOG_FORMAT=json
|
||||
BROWSER_HEADLESS=true
|
||||
|
||||
# 仅在执行 init-admin profile 时使用。
|
||||
XIANYU_ADMIN_PASSWORD=请替换为管理员密码
|
||||
@@ -0,0 +1,70 @@
|
||||
name: 构建并发布 Docker 镜像
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
concurrency:
|
||||
group: docker-publish-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: 发布多架构镜像
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 配置 QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: 配置 Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: 登录 GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 生成小写镜像名称
|
||||
id: image
|
||||
shell: bash
|
||||
run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 生成镜像标签
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,format=long
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: 构建并推送镜像
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.debian13
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
@@ -8,8 +8,14 @@
|
||||
!/Dockerfile.test
|
||||
*.out
|
||||
|
||||
# Local deployment environment (keep secrets out of Git)
|
||||
/.env
|
||||
/.env.*
|
||||
!/.env.example
|
||||
|
||||
# Runtime data
|
||||
/data/
|
||||
/browser_data/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Repository shape
|
||||
|
||||
The active application contains:
|
||||
|
||||
- `cmd/server/` — server entrypoint, administrator bootstrap (`-init-admin`), and HTTP server.
|
||||
- `cmd/init-admin/` — interactive administrator initialization CLI.
|
||||
- `cmd/dbverify/` — migration + core CRUD verification tool across SQLite/MySQL/Postgres.
|
||||
- `internal/server/` — chi HTTP API and SPA serving.
|
||||
- `internal/adapter/` — wiring layer that implements `engine.Handler` and `automation.OrderDetailFetcher` (system events → automation center, order-detail fetch / password-login refresh → browser, account alerts → notifier).
|
||||
- `internal/account/` — enabled-account supervisor.
|
||||
- `internal/engine/` — per-account runtime, replies, and delivery behavior.
|
||||
- `internal/automation/` — unified automation center (paid delivery, review gifts, review requests) + scheduler.
|
||||
- `internal/xianyu/` — MTOP, WebSocket, QR login, and protocol code.
|
||||
- `internal/browser/` — in-process Chromium automation through playwright-go.
|
||||
- `internal/db/` — multi-database access (SQLite/MySQL/Postgres) with embedded Goose migrations per dialect.
|
||||
- `frontend/` — active React/Vite source.
|
||||
- `internal/webui/static/` — embedded frontend build output.
|
||||
|
||||
## Common commands
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
|
||||
make build # go build ./cmd/server
|
||||
make test # go test ./...
|
||||
make vet # go vet ./...
|
||||
make lint # golangci-lint run ./... (0 issues baseline)
|
||||
make check # vet + lint + test
|
||||
make frontend # build frontend into internal/webui/static
|
||||
```
|
||||
|
||||
Run the server (SQLite by default; MySQL/Postgres via `-db-url` or `DATABASE_URL`):
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :8080
|
||||
```
|
||||
|
||||
Disable browser automation when Chromium is unavailable:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
```
|
||||
|
||||
Initialize or reset the administrator:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '...'
|
||||
```
|
||||
|
||||
Verify a database (migration + CRUD across dialects):
|
||||
|
||||
```bash
|
||||
go run ./cmd/dbverify "mysql://user:pass@tcp(host:3306)/db"
|
||||
```
|
||||
|
||||
Run a focused test:
|
||||
|
||||
```bash
|
||||
go test ./internal/server -run TestName -v
|
||||
go test ./internal/db -run TestMigrate -v
|
||||
```
|
||||
|
||||
Cross-database regression (requires Docker containers or external DBs):
|
||||
|
||||
```bash
|
||||
TEST_MYSQL_URL="mysql://root:pass@tcp(host:3306)/db" \
|
||||
TEST_POSTGRES_URL="postgres://user:pass@host:5432/db" \
|
||||
go test ./internal/db -run TestMultiDB -v
|
||||
```
|
||||
|
||||
Build the frontend:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
Run the frontend development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Vite proxies backend routes to `localhost:8080`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
||||
|
||||
## Architecture
|
||||
|
||||
`cmd/server/main.go` opens the database (SQLite/MySQL/Postgres by URL scheme), constructs the adapter + account manager + automation center + notifier, starts enabled account runtimes, initializes the optional in-process browser manager, and starts the HTTP server. Business logic does not live in `main.go` — it delegates to `internal/adapter` (Handler/OrderDetailFetcher wiring), `internal/engine`, `internal/account`, `internal/automation`, and domain-specific server handlers.
|
||||
|
||||
`internal/xianyu` owns lower-level platform integration:
|
||||
|
||||
- `mtop` for signed HTTP calls (interface `mtop.Client` allows test mocking).
|
||||
- `ws` for WebSocket transport.
|
||||
- `qrlogin` for QR login.
|
||||
- `protocol` for cookies, signing, decoding, and message IDs.
|
||||
|
||||
Browser-backed verification, password login refresh, and order-detail fallbacks live in `internal/browser`. Keep the browser contract and its server/engine callers aligned.
|
||||
|
||||
## Frozen slider CAPTCHA logic — DO NOT MODIFY
|
||||
|
||||
The current slider CAPTCHA implementation is production-frozen. Its authoritative behavior is documented in `docs/slider-captcha-frozen-spec.md`.
|
||||
|
||||
Unless the user explicitly requests a slider CAPTCHA behavior change in the current task, agents MUST NOT:
|
||||
|
||||
- edit, refactor, optimize, rename, move, delete, or reformat the protected slider implementation or its tests;
|
||||
- change selectors or selector priority, same-frame visibility checks, the exact `300px - 42px = 258px` standard NC distance, trajectories, point counts, timing, mouse-event order, or main-engine no-overshoot behavior;
|
||||
- change fresh-`x5sec` success criteria, punish/captcha URL checks, retry selectors, retry text checks, origin checks, reload recovery, retry counts, or timeouts;
|
||||
- change Playwright-first / direct-Chromium-CDP-fallback ordering, persistent-profile reuse and locking, verification-URL refresh timing, Cookie merge behavior, browser flags, environment defaults, or engine result labels;
|
||||
- weaken, skip, delete, or rewrite slider tests to permit different behavior;
|
||||
- modify a caller or shared helper in another file when that would indirectly change any frozen behavior above.
|
||||
|
||||
Directly protected files are:
|
||||
|
||||
- `internal/browser/slider.go`
|
||||
- `internal/browser/slider_test.go`
|
||||
- `internal/browser/token_captcha.go`
|
||||
- `internal/browser/token_captcha_test.go`
|
||||
- `internal/browser/token_captcha_fallback.go`
|
||||
- `internal/browser/token_captcha_fallback_integration_test.go`
|
||||
- `internal/browser/token_captcha_orchestrator_test.go`
|
||||
|
||||
Only an explicit user instruction in the current task can authorize a change. When authorized, update the implementation, tests, and frozen specification together, and run every verification required by the specification. Do not treat one authorization as permission for later tasks.
|
||||
|
||||
## Editing notes
|
||||
|
||||
- Preserve unrelated working-tree changes.
|
||||
- Update `frontend/vite.config.ts` if API route prefixes change.
|
||||
- Rebuild the frontend after source changes so embedded assets stay current.
|
||||
- Keep protocol and database behavior covered by focused tests.
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM golang:1.26-trixie AS go-toolchain
|
||||
|
||||
# 复用生产运行镜像中已经安装并验证过的 Chromium、Node 和 Playwright driver,
|
||||
# 只补 Go 工具链来执行真实浏览器集成测试。
|
||||
FROM xianyu-go:functional
|
||||
ENV PATH=/usr/local/go/bin:${PATH}
|
||||
ENV CGO_ENABLED=0
|
||||
WORKDIR /src
|
||||
COPY --from=go-toolchain /usr/local/go /usr/local/go
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
CMD ["go", "test", "-timeout=2m", "./internal/browser", "-run", "TestTokenCaptchaCDPFallbackBrowserIntegration", "-v", "-count=1"]
|
||||
+8
-6
@@ -1,13 +1,13 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:22-trixie AS frontend
|
||||
FROM --platform=$BUILDPLATFORM node:22-trixie AS frontend
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-trixie AS playwright-driver
|
||||
FROM --platform=$BUILDPLATFORM node:22-trixie AS playwright-driver
|
||||
RUN npm install -g playwright@1.57.0 \
|
||||
&& mkdir -p /ms-playwright-go/package \
|
||||
&& cp -a /usr/local/lib/node_modules/playwright/. /ms-playwright-go/package/ \
|
||||
@@ -16,15 +16,17 @@ RUN npm install -g playwright@1.57.0 \
|
||||
&& cp -a /usr/local/lib/node_modules/playwright-core /ms-playwright-go/package/node_modules/playwright-core; \
|
||||
fi
|
||||
|
||||
FROM golang:1.26-trixie AS backend
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
|
||||
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
|
||||
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
|
||||
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
|
||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
|
||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
|
||||
|
||||
FROM debian:13-slim AS runtime
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
FROM alpine:3.22 AS sqlite-tools
|
||||
RUN apk add --no-cache sqlite
|
||||
|
||||
FROM node:22-trixie AS frontend-assets
|
||||
WORKDIR /src/frontend
|
||||
@@ -28,4 +29,4 @@ WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
CMD ["sh", "-c", "npm test && npm run build"]
|
||||
CMD ["sh", "-c", "npm run typecheck && npm test && npm run build"]
|
||||
@@ -1,215 +1,583 @@
|
||||
# 闲鱼管家
|
||||
# Xianyu Go
|
||||
|
||||
这是当前活跃版本:Go 后端 + React 前端。后续功能迭代均在此目录进行:
|
||||
基于 Go 与 React 构建的闲鱼多账号管理、消息回复与自动发货系统
|
||||
|
||||
```text
|
||||
xianyu-go/
|
||||
cmd/server/ Go 服务入口(含 -init-admin 非交互初始化)
|
||||
cmd/init-admin/ 交互式初始化管理员 CLI
|
||||
cmd/dbverify/ 三库迁移 + 核心 CRUD 验证工具
|
||||
internal/ Go 后端代码
|
||||
frontend/ 当前活跃 React 前端源码
|
||||
internal/webui/static/ 前端构建产物,Go 会内置并提供给浏览器
|
||||
```
|
||||
[](go.mod)
|
||||
[](frontend/package.json)
|
||||
[](docker-compose.debian13-postgres17.yml)
|
||||
[](https://github.com/Christ9038/xinayu-go/actions/workflows/docker-publish.yml)
|
||||
|
||||
## 数据库支持
|
||||
[功能特性](#功能特性) · [快速开始](#快速开始) · [配置说明](#配置说明) ·
|
||||
[Docker 部署](#docker-部署) · [开发指南](#开发指南)
|
||||
|
||||
支持三种数据库,由连接 URL 的 scheme 决定:
|
||||
> [!IMPORTANT]
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
|
||||
> 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。
|
||||
> 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。
|
||||
|
||||
| scheme | 说明 |
|
||||
## 项目简介
|
||||
|
||||
Xianyu Go 是一个面向闲鱼卖家的自托管管理系统。它将账号运行、即时消息、订单、
|
||||
商品、卡密库存、自动化规则、AI 回复和异常通知整合到同一个 Web 管理后台,适合需要
|
||||
同时维护多个闲鱼账号或交付数字商品的个人与小型团队。
|
||||
|
||||
项目采用 Go 实现闲鱼登录、Cookie 续期、MTOP 请求和 WebSocket 消息链路。Chromium
|
||||
不是业务请求代理,仅用于读取真实浏览器指纹以及处理必须依赖浏览器环境的滑块风控。
|
||||
扫码登录、人脸验证流程、消息连接、凭证更新和绝大部分业务逻辑均由 Go 客户端完成。
|
||||
|
||||
### 适用场景
|
||||
|
||||
- 多个闲鱼账号的统一在线状态与消息管理
|
||||
- 数字商品、兑换码、链接或图片内容的自动交付
|
||||
- 付款后发货、评价赠品、超时求评价等自动化流程
|
||||
- 商品与订单同步、单商品发布及表格批量铺货
|
||||
- 接入 OpenAI 兼容接口实现可控的 AI 客服回复
|
||||
- 账号掉线、风控、续期和发货结果的多渠道通知
|
||||
|
||||
## 功能特性
|
||||
|
||||
| 模块 | 能力 |
|
||||
| --- | --- |
|
||||
| `sqlite://<path>` 或纯路径 | 纯 Go modernc.org/sqlite,WAL + foreign_keys(默认,本地开发) |
|
||||
| `mysql://<dsn>` | go-sql-driver/mysql(生产 / Docker 外置库) |
|
||||
| `postgres://<dsn>` | jackc/pgx(生产 / Docker 外置库) |
|
||||
| 账号管理 | 多账号启停、扫码登录、密码登录、资料刷新、在线状态、登录审计与备注管理 |
|
||||
| 凭证续期 | Cookie/token 定时续期、WebSocket 凭证更新、失效恢复、冷却与失败停用 |
|
||||
| 即时消息 | 闲鱼 WebSocket 长连接、消息收发、关键词回复、默认回复及仅回复一次 |
|
||||
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
|
||||
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
|
||||
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、任务恢复与结果导出 |
|
||||
| 订单管理 | 订单同步、插入、编辑、平台发货、补发卡密、仅确认发货及异常状态处理 |
|
||||
| AI 回复 | OpenAI 兼容 API、模型发现、自定义提示词、议价轮次和让价范围控制 |
|
||||
| 数据看板 | 活跃账号、订单、营收、库存、商品销量与金额统计 |
|
||||
| 通知告警 | Bark、钉钉、飞书、企业微信、Telegram、邮件和自定义 Webhook |
|
||||
| 数据存储 | SQLite、MySQL、PostgreSQL,内置按方言执行的 Goose 数据库迁移 |
|
||||
| 安全能力 | 管理端会话、敏感字段 AES-256-GCM 加密、日志脱敏和出站地址校验 |
|
||||
| 容器部署 | PostgreSQL 17、健康检查、持久化卷、GHCR amd64/arm64 多架构镜像 |
|
||||
|
||||
迁移用 goose 嵌入式执行,按方言分目录 `internal/db/migrations/{sqlite,mysql,postgres}`。
|
||||
## 系统架构
|
||||
|
||||
## 首次运行
|
||||
|
||||
### 1. 安装前端依赖并构建
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm install
|
||||
npm run build
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI["React 管理后台"] --> API["Go / chi HTTP API"]
|
||||
API --> Store["SQLite / MySQL / PostgreSQL"]
|
||||
API --> Manager["账号管理器"]
|
||||
Manager --> Engine["单账号运行时"]
|
||||
Engine --> WS["闲鱼 WebSocket"]
|
||||
Engine --> MTOP["闲鱼 MTOP"]
|
||||
Engine --> Automation["自动化中心"]
|
||||
Automation --> Notify["通知渠道"]
|
||||
Engine -. "仅指纹与滑块风控" .-> Chromium["Playwright / Chromium"]
|
||||
```
|
||||
|
||||
构建产物会写入:
|
||||
核心职责划分:
|
||||
|
||||
```text
|
||||
xianyu-go/internal/webui/static/
|
||||
```
|
||||
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
||||
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
||||
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
||||
- `internal/browser`:Chromium 指纹读取与滑块验证
|
||||
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
||||
- `internal/server`:HTTP API、管理端鉴权和前端静态资源
|
||||
|
||||
### 2. 初始化管理员
|
||||
## 快速开始
|
||||
|
||||
### 方式一:Docker Compose(推荐)
|
||||
|
||||
适用于 Linux x86_64、Linux ARM64 和 Apple Silicon。需要 Docker Engine 或
|
||||
Docker Desktop,并使用 Docker Compose v2。
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/init-admin -db data/xianyu_data.db
|
||||
git clone https://github.com/Christ9038/xinayu-go.git
|
||||
cd xinayu-go
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
也可以通过服务入口非交互初始化(适合脚本/Docker):
|
||||
编辑 `.env`,至少修改以下配置:
|
||||
|
||||
```dotenv
|
||||
POSTGRES_DB=xianyu
|
||||
POSTGRES_USER=xianyu
|
||||
POSTGRES_PASSWORD=替换为高强度密码
|
||||
DATABASE_URL=postgres://xianyu:替换为URL编码后的数据库密码@postgres:5432/xianyu?sslmode=disable
|
||||
XIANYU_DATA_KEY=替换为长期固定的随机密钥
|
||||
XIANYU_ADMIN_PASSWORD=替换为管理员密码
|
||||
```
|
||||
|
||||
推荐使用以下命令生成随机值:
|
||||
|
||||
```bash
|
||||
openssl rand -hex 24 # 适合作为 POSTGRES_PASSWORD,连接串无需额外 URL 编码
|
||||
openssl rand -base64 48 # 适合作为 XIANYU_DATA_KEY
|
||||
```
|
||||
|
||||
启动 PostgreSQL、初始化管理员并启动应用:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.debian13-postgres17.yml
|
||||
|
||||
docker compose -f "$COMPOSE_FILE" pull app postgres
|
||||
docker compose -f "$COMPOSE_FILE" up -d postgres
|
||||
docker compose -f "$COMPOSE_FILE" --profile init run --rm init-admin
|
||||
docker compose -f "$COMPOSE_FILE" up -d --no-build app
|
||||
```
|
||||
|
||||
浏览器访问 `http://localhost:8080`,使用用户名 `admin` 和 `.env` 中的
|
||||
`XIANYU_ADMIN_PASSWORD` 登录。
|
||||
|
||||
> GHCR 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行
|
||||
> `docker login ghcr.io -u Christ9038`,并使用具有 `read:packages` 权限的
|
||||
> Personal Access Token 登录。
|
||||
|
||||
### 方式二:从源码运行
|
||||
|
||||
环境要求:
|
||||
|
||||
- Go 1.26.4 或兼容版本
|
||||
- Node.js 22 与 npm
|
||||
- Chromium 运行所需的系统依赖
|
||||
- 默认可直接使用 SQLite,无需额外数据库服务
|
||||
|
||||
构建前端:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Christ9038/xinayu-go.git
|
||||
cd xinayu-go
|
||||
npm --prefix frontend ci
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
初始化管理员:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
go run ./cmd/server \
|
||||
-init-admin \
|
||||
-db data/xianyu_data.db \
|
||||
-admin-password '你的密码'
|
||||
-admin-password '请替换为管理员密码'
|
||||
```
|
||||
|
||||
`-admin-password` 也可用环境变量 `XIANYU_ADMIN_PASSWORD` 传入。
|
||||
|
||||
### 3. 启动服务
|
||||
启动服务:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
使用 MySQL / Postgres 时改用 `-db-url` 或 `DATABASE_URL`:
|
||||
首次启动会准备 Playwright 运行环境和 Chromium;下载速度取决于当前网络。启动完成后
|
||||
访问 `http://localhost:8080`。
|
||||
|
||||
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
||||
|
||||
```bash
|
||||
# MySQL(DSN 需含 multiStatements=true,工具会自动补齐)
|
||||
go run ./cmd/server -db-url "mysql://user:pass@tcp(host:3306)/dbname" -addr :8080
|
||||
|
||||
# Postgres
|
||||
DATABASE_URL="postgres://user:pass@host:5432/dbname?sslmode=disable" go run ./cmd/server -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
```
|
||||
|
||||
浏览器访问:
|
||||
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
|
||||
和长期运行账号的生产环境。
|
||||
|
||||
## 初次使用
|
||||
|
||||
1. 使用管理员账号登录管理后台。
|
||||
2. 进入“账号管理”,通过闲鱼 App 扫描二维码完成账号授权。
|
||||
3. 如平台触发风控,根据页面提示在手机端完成人脸或安全验证。
|
||||
4. 等待账号状态变为在线,再同步商品和订单。
|
||||
5. 在“卡密库存”创建交付内容。
|
||||
6. 在“自动化规则”将闲鱼商品与卡密、规格和触发条件关联。
|
||||
7. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
|
||||
|
||||
扫码登录是推荐方式。密码登录适合已有明确需求的环境,但更容易触发平台安全校验。
|
||||
无论使用哪种方式,都不要把 Cookie、密码、二维码或人脸验证地址分享给不可信第三方。
|
||||
|
||||
## 配置说明
|
||||
|
||||
配置分为三层:进程环境变量、命令行参数和管理后台设置。数据库连接优先级为:
|
||||
|
||||
```text
|
||||
http://localhost:8080
|
||||
DATABASE_URL > -db-url > -db
|
||||
```
|
||||
|
||||
不传 `-web` 时,Go 会使用 `internal/webui/static` 中的内置前端资源。
|
||||
### 环境变量
|
||||
|
||||
## 开发模式
|
||||
| 变量 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 空 | 数据库连接 URL;生产环境推荐 PostgreSQL |
|
||||
| `XIANYU_DATA_KEY` | 空 | 敏感字段加密主密钥;生产环境必须固定并备份 |
|
||||
| `XIANYU_ADMIN_PASSWORD` | 空 | 非交互初始化或重置管理员时使用 |
|
||||
| `XIANYU_UPLOAD_DIR` | `data/uploads` | 批量铺货上传文件与临时资源目录 |
|
||||
| `LOG_LEVEL` | 系统设置或 `info` | `debug`、`info`、`warn`、`error` |
|
||||
| `LOG_FORMAT` | 系统设置或 `text` | `text` 或 `json` |
|
||||
| `BROWSER_HEADLESS` | 按账号设置;Docker 为 `true` | 强制启用或关闭无头 Chromium |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 指定系统 Chromium 可执行文件 |
|
||||
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
|
||||
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
|
||||
|
||||
后端:
|
||||
Docker Compose 还支持:
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `COMPOSE_PROJECT_NAME` | `xianyu` | Compose 项目名及命名卷前缀 |
|
||||
| `POSTGRES_IMAGE` | `postgres:17-trixie` | PostgreSQL 镜像 |
|
||||
| `POSTGRES_DB` | 必填 | 数据库名 |
|
||||
| `POSTGRES_USER` | 必填 | 数据库用户 |
|
||||
| `POSTGRES_PASSWORD` | 必填 | 数据库密码 |
|
||||
| `XIANYU_IMAGE` | `xianyu-go:debian13` | 应用镜像与标签 |
|
||||
| `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 |
|
||||
| `XIANYU_HTTP_PORT` | `8080` | 应用在宿主机上的端口 |
|
||||
|
||||
Compose 文件回退到本地镜像 `xianyu-go:debian13`;随仓库提供的 `.env.example` 已将
|
||||
`XIANYU_IMAGE` 设置为 GHCR 的 `:dev` 多架构镜像。
|
||||
|
||||
`XIANYU_DATA_KEY` 用于加密 Cookie、账号密码、设备令牌、访问令牌、AI/SMTP 密钥和
|
||||
通知凭证。启用后,服务会自动升级历史明文数据。密钥丢失或更换后,已有加密数据将
|
||||
无法解密,因此必须与数据库备份一起保存。
|
||||
|
||||
### 命令行参数
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `-db` | `data/xianyu_data.db` | SQLite 数据库路径 |
|
||||
| `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL |
|
||||
| `-addr` | `:8080` | HTTP 监听地址 |
|
||||
| `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` |
|
||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
||||
| `-log-format` | 环境变量或系统设置 | 覆盖日志格式 |
|
||||
| `-v` | `false` | 启用调试日志,等价于未显式配置时使用 debug |
|
||||
| `-init-admin` | `false` | 初始化或重置 `admin` 后退出 |
|
||||
| `-admin-email` | `admin@example.com` | 初始化管理员邮箱 |
|
||||
| `-admin-password` | 空 | 初始化管理员密码 |
|
||||
|
||||
### 数据库连接示例
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
# SQLite
|
||||
DATABASE_URL="sqlite://data/xianyu_data.db" ./xianyu-server
|
||||
|
||||
# MySQL;应用会强制补齐 multiStatements=true 和 clientFoundRows=true
|
||||
DATABASE_URL="mysql://user:pass@tcp(127.0.0.1:3306)/xianyu" ./xianyu-server
|
||||
|
||||
# PostgreSQL
|
||||
DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xianyu-server
|
||||
```
|
||||
|
||||
前端开发服务器:
|
||||
每次启动都会自动执行对应数据库方言的嵌入式 Goose 迁移。生产数据库升级前仍建议
|
||||
先完成备份。
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm run dev
|
||||
```
|
||||
### 管理后台配置
|
||||
|
||||
访问:
|
||||
以下配置通过 Web 管理后台维护并保存在数据库中:
|
||||
|
||||
- **账号设置**:启停状态、备注、通知渠道绑定和单账号 AI 回复策略
|
||||
- **自动化规则**:触发条件、商品、规格、卡密组、发送数量、延迟和后续动作
|
||||
- **回复规则**:关键词、文本或图片回复、默认回复及回复次数限制
|
||||
- **AI 设置**:OpenAI 兼容 API 地址、API Key、模型和全局提示词
|
||||
- **议价策略**:最大折扣比例、最大折扣金额和最多议价轮次
|
||||
- **通知设置**:Bark、钉钉、飞书、企业微信、Telegram、邮件和 Webhook
|
||||
- **日志设置**:日志等级、输出格式和续期日志保留天数
|
||||
- **远程滑块服务**:服务地址、密钥及是否允许传递 Cookie;默认不传递 Cookie
|
||||
- **管理凭据**:管理员用户名、密码和邮箱
|
||||
|
||||
AI Base URL 支持 OpenAI 兼容接口,可连接 OpenAI、通义千问、Ollama、vLLM、
|
||||
LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI 或远程验证服务传递
|
||||
消息内容与账号数据。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
### 镜像与架构
|
||||
|
||||
GitHub Actions 会将同一标签发布为多架构镜像:
|
||||
|
||||
```text
|
||||
http://localhost:3000
|
||||
ghcr.io/christ9038/xinayu-go:dev
|
||||
├── linux/amd64
|
||||
└── linux/arm64
|
||||
```
|
||||
|
||||
Vite 会把 API 请求代理到 `http://localhost:8080`。
|
||||
Docker 会根据宿主机 CPU 自动选择镜像。x86_64 Linux 拉取 amd64,Apple M 系列和
|
||||
ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
||||
|
||||
## 编译运行
|
||||
标签规则:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go build -o xianyu-server ./cmd/server
|
||||
./xianyu-server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
如果要使用外部前端目录,也可以传:
|
||||
|
||||
```bash
|
||||
./xianyu-server -db data/xianyu_data.db -addr :8080 -web /path/to/static
|
||||
```
|
||||
|
||||
## 验证数据库(三库冒烟)
|
||||
|
||||
`cmd/dbverify` 在目标库上跑迁移 + 核心 CRUD,确认方言适配正常:
|
||||
|
||||
```bash
|
||||
go run ./cmd/dbverify "sqlite:///tmp/verify.db"
|
||||
go run ./cmd/dbverify "mysql://root:pass@tcp(host:3306)/db?multiStatements=true"
|
||||
go run ./cmd/dbverify "postgres://user:pass@host:5432/db"
|
||||
```
|
||||
|
||||
全部 9 步通过即说明 upsert / 布尔读写 / 自增主键 / NULL 扫描跨三库一致。
|
||||
|
||||
## Docker 部署注意
|
||||
|
||||
批量铺货会用到上传目录。容器部署时建议挂载持久化数据:
|
||||
|
||||
```bash
|
||||
-v ./data:/app/data
|
||||
```
|
||||
|
||||
并设置:
|
||||
|
||||
```bash
|
||||
XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
```
|
||||
|
||||
数据库建议放在:
|
||||
|
||||
```text
|
||||
/app/data/xianyu_data.db
|
||||
```
|
||||
|
||||
外置 MySQL/Postgres 时改用 `DATABASE_URL` 环境变量。
|
||||
|
||||
## 常用参数
|
||||
|
||||
| 参数 | 说明 |
|
||||
| Git 引用 | 镜像标签 |
|
||||
| --- | --- |
|
||||
| `-db` | SQLite 数据库路径,默认 `data/xianyu_data.db`(向后兼容) |
|
||||
| `-db-url` | 数据库连接 URL(`sqlite://` / `mysql://` / `postgres://`),优先级高于 `-db` |
|
||||
| `DATABASE_URL` | 环境变量,优先级最高 |
|
||||
| `-addr` | HTTP 监听地址,默认 `:8080` |
|
||||
| `-web` | 外部前端静态资源目录;不传则用内置前端 |
|
||||
| `-init-admin` | 初始化或重置管理员后退出 |
|
||||
| `-admin-email` | 初始化管理员邮箱 |
|
||||
| `-admin-password` | 初始化管理员密码(也可用 `XIANYU_ADMIN_PASSWORD` 环境变量) |
|
||||
| `-no-browser` | 禁用内置浏览器自动化(扫码风控/密码登录/订单抓取将不可用) |
|
||||
| `-secure` | HTTPS 模式,Cookie 加 Secure |
|
||||
| `-v` | 调试日志 |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
||||
|
||||
## 质量门禁与测试
|
||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||
|
||||
项目内置 Makefile 与 golangci-lint 配置:
|
||||
### Compose 服务
|
||||
|
||||
`docker-compose.debian13-postgres17.yml` 包含三个服务:
|
||||
|
||||
| 服务 | 用途 |
|
||||
| --- | --- |
|
||||
| `postgres` | PostgreSQL 17 数据库,仅在 Compose 内部网络开放 5432 |
|
||||
| `app` | Xianyu Go 主服务、前端和 Chromium |
|
||||
| `init-admin` | 一次性管理员初始化任务,通过 `init` profile 启用 |
|
||||
|
||||
持久化卷:
|
||||
|
||||
| 卷 | 内容 |
|
||||
| --- | --- |
|
||||
| `postgres_data` | PostgreSQL 数据文件 |
|
||||
| `app_data` | 上传文件、批量铺货资源和应用数据 |
|
||||
| `browser_data` | Chromium 持久化配置和验证上下文 |
|
||||
|
||||
### 完整部署步骤
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
make vet # go vet
|
||||
make test # 全部单元测试
|
||||
make lint # golangci-lint(0 issues 基线)
|
||||
make cover # 覆盖率报告
|
||||
make check # vet + lint + test 一键全检
|
||||
make frontend # 构建前端
|
||||
git clone https://github.com/Christ9038/xinayu-go.git
|
||||
cd xinayu-go
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
跨三库回归(需 Docker 容器或外置库):
|
||||
完成 `.env` 配置后执行:
|
||||
|
||||
```bash
|
||||
TEST_MYSQL_URL="mysql://root:pass@tcp(host:3306)/db" \
|
||||
TEST_POSTGRES_URL="postgres://user:pass@host:5432/db" \
|
||||
go test ./internal/db -run TestMultiDB -v
|
||||
COMPOSE_FILE=docker-compose.debian13-postgres17.yml
|
||||
|
||||
# 拉取应用和 PostgreSQL 镜像
|
||||
docker compose -f "$COMPOSE_FILE" pull app postgres
|
||||
|
||||
# 启动数据库并等待健康检查
|
||||
docker compose -f "$COMPOSE_FILE" up -d postgres
|
||||
|
||||
# 创建或重置管理员
|
||||
docker compose -f "$COMPOSE_FILE" --profile init run --rm init-admin
|
||||
|
||||
# 启动应用
|
||||
docker compose -f "$COMPOSE_FILE" up -d --no-build app
|
||||
```
|
||||
|
||||
完整 Docker 功能回归(前端测试/构建、vet、lint、Go `-race`、三库迁移、
|
||||
MySQL 8.4 与 PostgreSQL 17 API 功能及重启持久化):
|
||||
检查运行状态:
|
||||
|
||||
```bash
|
||||
docker compose -f "$COMPOSE_FILE" ps
|
||||
curl -fsS http://127.0.0.1:8080/health
|
||||
docker compose -f "$COMPOSE_FILE" logs --tail=200 app
|
||||
```
|
||||
|
||||
健康接口正常时返回:
|
||||
|
||||
```json
|
||||
{"database":"ok","status":"ok"}
|
||||
```
|
||||
|
||||
### 更新镜像
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.debian13-postgres17.yml
|
||||
docker compose -f "$COMPOSE_FILE" pull app
|
||||
docker compose -f "$COMPOSE_FILE" up -d --no-build app
|
||||
docker compose -f "$COMPOSE_FILE" logs --tail=100 app
|
||||
```
|
||||
|
||||
更新前请先备份数据库,并确认 `.env` 中的 `XIANYU_DATA_KEY` 未发生变化。
|
||||
|
||||
### 备份 PostgreSQL
|
||||
|
||||
```bash
|
||||
set -a
|
||||
. ./.env
|
||||
set +a
|
||||
|
||||
docker compose -f docker-compose.debian13-postgres17.yml exec -T postgres \
|
||||
pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
|
||||
> "xianyu-$(date +%Y%m%d-%H%M%S).sql"
|
||||
```
|
||||
|
||||
恢复前请先停止应用,并在独立环境验证备份文件:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.debian13-postgres17.yml stop app
|
||||
docker compose -f docker-compose.debian13-postgres17.yml exec -T postgres \
|
||||
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" < xianyu-backup.sql
|
||||
```
|
||||
|
||||
同时备份 `.env` 中的 `XIANYU_DATA_KEY`。不要把包含真实密码和密钥的 `.env` 提交到
|
||||
Git;项目已默认忽略该文件。
|
||||
|
||||
### 停止服务
|
||||
|
||||
```bash
|
||||
# 停止并保留数据卷
|
||||
docker compose -f docker-compose.debian13-postgres17.yml down
|
||||
|
||||
# 查看数据卷
|
||||
docker volume ls --filter name=xianyu
|
||||
```
|
||||
|
||||
不要在生产环境随意执行 `down -v`,该参数会删除 Compose 管理的数据库和应用数据卷。
|
||||
|
||||
### HTTPS 与反向代理
|
||||
|
||||
生产环境建议使用 Caddy、Nginx、Traefik 或云负载均衡器终止 TLS,并避免直接向公网
|
||||
暴露管理端口。启用 HTTPS 后,应为应用命令增加 `-secure`,确保管理端会话 Cookie
|
||||
仅通过 HTTPS 发送。例如可创建一个 Compose override:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-secure"]
|
||||
```
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 项目结构
|
||||
|
||||
```text
|
||||
.
|
||||
├── cmd/
|
||||
│ ├── server/ # 主服务与管理员初始化入口
|
||||
│ ├── init-admin/ # 交互式管理员初始化工具
|
||||
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
|
||||
│ └── dbseed/ # Docker 功能测试数据种子
|
||||
├── internal/
|
||||
│ ├── account/ # 多账号监督与生命周期
|
||||
│ ├── adapter/ # 业务模块接线层
|
||||
│ ├── automation/ # 自动化中心与调度器
|
||||
│ ├── browser/ # Chromium 指纹和滑块验证
|
||||
│ ├── db/ # 数据访问、加密与迁移
|
||||
│ ├── engine/ # 单账号消息和交付运行时
|
||||
│ ├── notify/ # 通知渠道
|
||||
│ ├── renewal/ # 登录态续期调度
|
||||
│ ├── server/ # HTTP API 与 SPA 服务
|
||||
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
|
||||
├── frontend/ # React、TypeScript、Vite 前端
|
||||
├── docs/ # 专题文档和行为规范
|
||||
├── scripts/ # Docker 与回归测试脚本
|
||||
└── Dockerfile.debian13 # 多阶段生产镜像
|
||||
```
|
||||
|
||||
### 本地开发
|
||||
|
||||
启动后端:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
启动前端开发服务器:
|
||||
|
||||
```bash
|
||||
npm --prefix frontend ci
|
||||
npm --prefix frontend run dev
|
||||
```
|
||||
|
||||
访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:8080`。
|
||||
|
||||
构建嵌入式前端和 Go 二进制:
|
||||
|
||||
```bash
|
||||
make frontend
|
||||
make build
|
||||
```
|
||||
|
||||
### 质量检查
|
||||
|
||||
```bash
|
||||
make fmt # 格式化 Go 代码
|
||||
make vet # go vet
|
||||
make lint # golangci-lint
|
||||
make test # 全部 Go 单元测试
|
||||
make cover # 覆盖率报告
|
||||
make check # fmt + vet + lint + test
|
||||
|
||||
npm --prefix frontend run typecheck
|
||||
npm --prefix frontend test
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
完整 Docker 功能回归会检查前端、Go `-race`、SQLite、MySQL 8.4、PostgreSQL 17、
|
||||
API 功能和容器重启持久化:
|
||||
|
||||
```bash
|
||||
./scripts/docker-full-test.sh
|
||||
```
|
||||
|
||||
测试编排使用命名卷 `mysql8_data`、`postgres17_data` 和 `sqlite_seed`。
|
||||
本地 `data/xianyu_data.db` 只会抽取少量商品、订单和卡密元数据,写入外置库前会替换
|
||||
Cookie、买家 ID 和卡密内容。测试应用分别监听 `18081`(MySQL)与 `18082`
|
||||
(PostgreSQL),测试账号为 `docker_fixture / docker_fixture_password`。
|
||||
测试管理员为 `docker_admin / docker_admin_password`。
|
||||
|
||||
保留数据库并停止容器:
|
||||
验证指定数据库的迁移与核心 CRUD:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.functional.yml down
|
||||
go run ./cmd/dbverify "sqlite:///tmp/xianyu-verify.db"
|
||||
go run ./cmd/dbverify "mysql://root:pass@tcp(127.0.0.1:3306)/xianyu"
|
||||
go run ./cmd/dbverify "postgres://user:pass@127.0.0.1:5432/xianyu"
|
||||
```
|
||||
|
||||
只有明确需要清空测试数据时才追加 `-v` 删除命名卷。
|
||||
## 常见问题
|
||||
|
||||
### 服务启动后提示尚未初始化
|
||||
|
||||
先执行管理员初始化:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.debian13-postgres17.yml \
|
||||
--profile init run --rm init-admin
|
||||
```
|
||||
|
||||
源码运行时可执行:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密码'
|
||||
```
|
||||
|
||||
### PostgreSQL 连接失败
|
||||
|
||||
- 确认 `.env` 中 `POSTGRES_DB`、`POSTGRES_USER`、`POSTGRES_PASSWORD` 与
|
||||
`DATABASE_URL` 完全一致。
|
||||
- Compose 内部的数据库主机名必须写 `postgres`,不能写 `localhost`。
|
||||
- 密码包含 `@`、`:`、`/`、`#` 等字符时,需要在 `DATABASE_URL` 中进行 URL 编码。
|
||||
- 使用 `docker compose ... ps` 确认 PostgreSQL 健康检查已通过。
|
||||
|
||||
### Chromium 或 Playwright 初始化失败
|
||||
|
||||
- Docker 部署优先使用项目提供的镜像,镜像已包含 Chromium 和运行依赖。
|
||||
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
||||
- 自带 Chromium 时设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`,并按需设置
|
||||
`PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`。
|
||||
- 容器内需要足够的共享内存与可写的 `browser_data` 卷。
|
||||
|
||||
### 账号掉线或需要安全验证
|
||||
|
||||
- 查看“账号管理”中的状态和续期日志。
|
||||
- 根据页面二维码在闲鱼 App 完成人脸或安全验证。
|
||||
- 检查服务器时间、时区和外网连接是否正常。
|
||||
- 不要同时在多个实例中运行同一个闲鱼账号,避免凭证相互覆盖。
|
||||
|
||||
### 修改 `XIANYU_DATA_KEY` 后无法读取凭证
|
||||
|
||||
这是预期的安全行为。请恢复写入这些数据时使用的原密钥。无法恢复原密钥时,只能重新
|
||||
登录账号并重新录入受保护的密钥;不要通过清空或绕过解密检查继续运行生产数据库。
|
||||
|
||||
## 安全建议
|
||||
|
||||
- 仅通过 HTTPS 暴露管理后台,并限制可信来源访问。
|
||||
- 为管理员、数据库和 GHCR 分别使用不同的高强度密码。
|
||||
- 固定并离线备份 `XIANYU_DATA_KEY`,不要在多套环境之间随意复用。
|
||||
- 不要提交 `.env`、数据库文件、Cookie、二维码、日志或浏览器数据目录。
|
||||
- 定期备份 PostgreSQL,并实际验证恢复流程。
|
||||
- 使用版本或 SHA 镜像标签部署生产环境。
|
||||
- 仅向可信的 AI、SMTP、Webhook 和远程滑块服务发送数据。
|
||||
- 发现账号异常时先停用账号,再检查登录审计和续期日志。
|
||||
|
||||
## 贡献
|
||||
|
||||
欢迎通过 Issue 报告可复现的问题,或通过 Pull Request 提交改进。提交前请:
|
||||
|
||||
1. 将不同主题拆分为独立提交。
|
||||
2. 为协议、数据库和关键业务行为补充测试。
|
||||
3. 运行 `make check` 和前端测试。
|
||||
4. 不要提交真实账号、Cookie、订单、卡密、密钥或其他敏感数据。
|
||||
5. 不要在未说明原因和验证证据的情况下修改风控与滑块行为。
|
||||
|
||||
提交安全问题时,请避免在公开 Issue 中附带真实凭证或用户数据。
|
||||
|
||||
## 许可证
|
||||
|
||||
当前仓库尚未包含 `LICENSE` 文件。公开仓库不等同于授予开源许可;在项目维护者补充
|
||||
明确许可证之前,源码的复制、修改和分发仍受著作权限制。若计划接受社区贡献或允许
|
||||
再分发,建议在公开发布前选择并添加合适的开源许可证。
|
||||
|
||||
## 免责声明
|
||||
|
||||
本项目仅提供技术研究和自托管管理能力,不保证对闲鱼接口变化、账号风控策略、业务
|
||||
连续性或数据完整性的长期兼容。因使用本项目造成的账号限制、交易纠纷、数据损失或
|
||||
其他直接与间接损失,应由使用者自行承担。请勿将本项目用于垃圾消息、欺诈、未授权
|
||||
访问、规避平台限制或任何违法违规活动。
|
||||
@@ -111,6 +111,24 @@ func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, optio
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
// 保留一条历史脏金额,用于验证三种数据库下统计接口都能安全跳过而不是 500。
|
||||
fixtureItemID := ""
|
||||
for _, id := range itemMap {
|
||||
fixtureItemID = id
|
||||
break
|
||||
}
|
||||
if fixtureItemID != "" {
|
||||
if err := target.Orders.Upsert(ctx, "docker-invalid-amount", db.OrderUpsertOpts{
|
||||
CookieID: accountID, ItemID: fixtureItemID, BuyerID: "docker-buyer-invalid",
|
||||
Quantity: "1", OrderStatus: "completed",
|
||||
}); err != nil {
|
||||
return result, err
|
||||
}
|
||||
// 直接写入一条模拟升级前遗留的脏数据;正常仓储写入口会拒绝该金额。
|
||||
if _, err := target.DB.ExecContext(ctx, `UPDATE orders SET amount='not-a-number' WHERE order_id='docker-invalid-amount'`); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
result.Cards, err = seedCards(ctx, source, target, user.ID, options.Limit)
|
||||
return result, err
|
||||
}
|
||||
@@ -229,6 +247,11 @@ func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if normalized, valid := db.NormalizeOrderAmount(amount); valid {
|
||||
amount = normalized
|
||||
} else {
|
||||
amount = ""
|
||||
}
|
||||
if err := target.Orders.Upsert(ctx, "docker-order-"+shortHash(sourceOrderID), db.OrderUpsertOpts{
|
||||
CookieID: accountID, ItemID: itemID, BuyerID: "docker-buyer", Quantity: quantity,
|
||||
Amount: amount, OrderStatus: status, SpecName: specName, SpecValue: specValue,
|
||||
|
||||
@@ -51,6 +51,10 @@ func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) {
|
||||
if len(cards) != 1 || strings.Contains(cards[0].DataContent, "SECRET-CODE") {
|
||||
t.Fatalf("source card secret leaked: %+v", cards)
|
||||
}
|
||||
invalidOrder, err := target.Orders.Get(ctx, "docker-invalid-amount")
|
||||
if err != nil || invalidOrder.Amount != "not-a-number" {
|
||||
t.Fatalf("invalid amount fixture missing: order=%+v err=%v", invalidOrder, err)
|
||||
}
|
||||
|
||||
second, err := seedFromSQLite(ctx, sourceDB, target, options)
|
||||
if err != nil {
|
||||
|
||||
+18
-6
@@ -8,8 +8,8 @@
|
||||
//
|
||||
// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。
|
||||
//
|
||||
// 浏览器自动化(扫码风控验证、密码登录、订单抓取)内置 playwright-go,
|
||||
// 首次使用时自动下载 Chromium。加 -no-browser 可禁用。
|
||||
// Chromium 仅用于读取本机浏览器指纹和处理 token 滑块,首次使用时由
|
||||
// playwright-go 准备运行环境。加 -no-browser 可禁用这两项能力。
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -40,7 +40,7 @@ func main() {
|
||||
addr := flag.String("addr", ":8080", "HTTP 监听地址")
|
||||
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
|
||||
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
|
||||
noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/密码登录/订单抓取将不可用)")
|
||||
noBrowser := flag.Bool("no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
|
||||
verbose := flag.Bool("v", false, "调试日志")
|
||||
logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
|
||||
logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
|
||||
@@ -92,6 +92,10 @@ func main() {
|
||||
}
|
||||
logger.Info("数据库已就绪", "dialect", dialect)
|
||||
store := db.NewStore(database, dialect)
|
||||
if err := store.EncryptLegacySecrets(ctx); err != nil {
|
||||
logger.Error("校验或升级数据库敏感字段失败", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer database.Close()
|
||||
if !explicitLogLevel {
|
||||
if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
|
||||
@@ -121,10 +125,15 @@ func main() {
|
||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||
}
|
||||
|
||||
// 2) 内置浏览器管理器(playwright-go,首运行自动下载 Chromium)。
|
||||
// 2) Chromium 只负责读取本机浏览器指纹和处理 token 滑块。
|
||||
// 扫码、人脸、续期、MTOP、Cookie 与 WebSocket 全部走 Go 协议实现。
|
||||
var bm *browser.Manager
|
||||
if !*noBrowser {
|
||||
bm = browser.NewManager(logger)
|
||||
if err := bm.Initialize(); err != nil {
|
||||
logger.Error("初始化 Playwright Chromium 指纹失败", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
var mgr *account.Manager
|
||||
ap := adapter.New(store, bm, logger)
|
||||
@@ -132,6 +141,7 @@ func main() {
|
||||
autoCenter := automation.New(store, mgr, logger)
|
||||
autoCenter.SetOrderDetailFetcher(ap)
|
||||
notifier := notify.New("", store, logger)
|
||||
notifier.Start(ctx)
|
||||
autoCenter.SetNotifier(notifier)
|
||||
ap.SetAutomation(autoCenter)
|
||||
ap.SetNotifier(notifier)
|
||||
@@ -139,10 +149,11 @@ func main() {
|
||||
logger.Error("启动账号引擎失败", "err", err)
|
||||
}
|
||||
go automation.NewScheduler(autoCenter).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, bm, ap, logger).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
go srv.RunPublishBatchRecovery(ctx)
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
logger.Error("HTTP 服务退出", "err", err)
|
||||
// 即便出错也尝试清理已启动的账号与浏览器。
|
||||
@@ -157,6 +168,7 @@ func main() {
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
}
|
||||
notifier.Wait()
|
||||
}
|
||||
|
||||
// handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
x-app-env: &app-env
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-xianyu}:${POSTGRES_PASSWORD:-xianyu_password}@postgres:5432/${POSTGRES_DB:-xianyu}?sslmode=disable
|
||||
DATABASE_URL: ${DATABASE_URL:?请在 .env 中配置 DATABASE_URL}
|
||||
XIANYU_DATA_KEY: ${XIANYU_DATA_KEY:?请在 .env 中配置 XIANYU_DATA_KEY}
|
||||
XIANYU_UPLOAD_DIR: ${XIANYU_UPLOAD_DIR:-/app/data/uploads}
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
LOG_FORMAT: ${LOG_FORMAT:-json}
|
||||
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
||||
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
|
||||
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
|
||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
|
||||
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
|
||||
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:-}
|
||||
|
||||
x-app-volumes: &app-volumes
|
||||
- app_data:/app/data
|
||||
@@ -14,22 +17,23 @@ x-app-volumes: &app-volumes
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-trixie
|
||||
image: ${POSTGRES_IMAGE:-postgres:17-trixie}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-xianyu}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-xianyu}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-xianyu_password}
|
||||
POSTGRES_DB: ${POSTGRES_DB:?请在 .env 中配置 POSTGRES_DB}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?请在 .env 中配置 POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?请在 .env 中配置 POSTGRES_PASSWORD}
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "${POSTGRES_PORT:-5432}:5432"
|
||||
expose:
|
||||
- "5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 10s
|
||||
|
||||
app:
|
||||
image: ${XIANYU_IMAGE:-xianyu-go:debian13}
|
||||
@@ -43,7 +47,7 @@ services:
|
||||
environment: *app-env
|
||||
command: ["/app/xianyu-server", "-addr", ":8080"]
|
||||
ports:
|
||||
- "${XIANYU_HTTP_PORT:-8080}:8080"
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080"
|
||||
volumes: *app-volumes
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
|
||||
@@ -62,7 +66,9 @@ services:
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment: *app-env
|
||||
environment:
|
||||
<<: *app-env
|
||||
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:-}
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
name: xianyu-functional
|
||||
|
||||
x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=Local
|
||||
x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable
|
||||
x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=UTC
|
||||
x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable&timezone=UTC
|
||||
x-data-key: &data-key docker-functional-data-key-v1
|
||||
|
||||
services:
|
||||
mysql:
|
||||
@@ -12,8 +13,8 @@ services:
|
||||
MYSQL_DATABASE: xianyu
|
||||
MYSQL_USER: xianyu
|
||||
MYSQL_PASSWORD: xianyu_mysql_password
|
||||
TZ: Asia/Shanghai
|
||||
command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_0900_ai_ci"]
|
||||
TZ: UTC
|
||||
command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_0900_ai_ci", "--default-time-zone=+00:00"]
|
||||
ports:
|
||||
- "13306:3306"
|
||||
volumes:
|
||||
@@ -31,7 +32,8 @@ services:
|
||||
POSTGRES_DB: xianyu
|
||||
POSTGRES_USER: xianyu
|
||||
POSTGRES_PASSWORD: xianyu_postgres_password
|
||||
TZ: Asia/Shanghai
|
||||
TZ: UTC
|
||||
command: ["postgres", "-c", "timezone=UTC", "-c", "log_timezone=UTC"]
|
||||
ports:
|
||||
- "15432:5432"
|
||||
volumes:
|
||||
@@ -43,7 +45,10 @@ services:
|
||||
retries: 30
|
||||
|
||||
sqlite-seed-copy:
|
||||
image: alpine:3.22
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.test
|
||||
target: sqlite-tools
|
||||
restart: "no"
|
||||
volumes:
|
||||
- ./data:/source:ro
|
||||
@@ -53,9 +58,11 @@ services:
|
||||
- -ec
|
||||
- |
|
||||
rm -f /seed/xianyu_data.db /seed/xianyu_data.db-wal /seed/xianyu_data.db-shm
|
||||
cp /source/xianyu_data.db /seed/xianyu_data.db
|
||||
test ! -f /source/xianyu_data.db-wal || cp /source/xianyu_data.db-wal /seed/xianyu_data.db-wal
|
||||
test ! -f /source/xianyu_data.db-shm || cp /source/xianyu_data.db-shm /seed/xianyu_data.db-shm
|
||||
test -f /source/xianyu_data.db
|
||||
sqlite3 -readonly /source/xianyu_data.db ".timeout 30000" ".backup '/seed/xianyu_data.db'"
|
||||
test -s /seed/xianyu_data.db
|
||||
test "$(sqlite3 /seed/xianyu_data.db 'PRAGMA journal_mode=DELETE;')" = "delete"
|
||||
sqlite3 /seed/xianyu_data.db "PRAGMA quick_check" | grep -qx ok
|
||||
|
||||
seed-mysql:
|
||||
image: xianyu-go:functional
|
||||
@@ -70,8 +77,26 @@ services:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- sqlite_seed:/seed:ro
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *mysql-url, "-limit", "20"]
|
||||
|
||||
seed-sqlite:
|
||||
image: xianyu-go:functional
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.debian13
|
||||
restart: "no"
|
||||
depends_on:
|
||||
sqlite-seed-copy:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
volumes:
|
||||
- sqlite_seed:/seed:ro
|
||||
- app_sqlite_data:/app/data
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", "/app/data/xianyu-functional.db", "-limit", "20"]
|
||||
|
||||
seed-postgres:
|
||||
image: xianyu-go:functional
|
||||
restart: "no"
|
||||
@@ -82,6 +107,8 @@ services:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- sqlite_seed:/seed:ro
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *postgres-url, "-limit", "20"]
|
||||
|
||||
app-mysql:
|
||||
@@ -92,12 +119,36 @@ services:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
DATABASE_URL: *mysql-url
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
ports:
|
||||
- "18081:8080"
|
||||
- "28081:8080"
|
||||
volumes:
|
||||
- app_mysql_data:/app/data
|
||||
- app_mysql_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
|
||||
app-sqlite:
|
||||
image: xianyu-go:functional
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
seed-sqlite:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
DATABASE_URL: sqlite:///app/data/xianyu-functional.db
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
ports:
|
||||
- "28080:8080"
|
||||
volumes:
|
||||
- app_sqlite_data:/app/data
|
||||
- app_sqlite_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
interval: 5s
|
||||
@@ -112,12 +163,14 @@ services:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
DATABASE_URL: *postgres-url
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
ports:
|
||||
- "18082:8080"
|
||||
- "28082:8080"
|
||||
volumes:
|
||||
- app_postgres_data:/app/data
|
||||
- app_postgres_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
interval: 5s
|
||||
@@ -139,6 +192,15 @@ services:
|
||||
TEST_POSTGRES_URL: *postgres-url
|
||||
command: ["go", "test", "-race", "-timeout=20m", "./..."]
|
||||
|
||||
browser-integration-test:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.browser-test
|
||||
environment:
|
||||
RUN_BROWSER_INTEGRATION: "1"
|
||||
BROWSER_HEADLESS: "true"
|
||||
command: ["go", "test", "-timeout=2m", "./internal/browser", "-run", "TestTokenCaptchaCDPFallbackBrowserIntegration", "-v", "-count=1"]
|
||||
|
||||
go-vet:
|
||||
build:
|
||||
context: .
|
||||
@@ -158,26 +220,40 @@ services:
|
||||
context: .
|
||||
dockerfile: Dockerfile.test
|
||||
target: frontend-test
|
||||
command: ["sh", "-c", "npm test && npm run build"]
|
||||
command: ["sh", "-c", "npm run typecheck && npm test && npm run build"]
|
||||
|
||||
dbverify-mysql:
|
||||
image: xianyu-go:functional
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
command: ["/app/xianyu-dbverify", *mysql-url]
|
||||
|
||||
dbverify-sqlite:
|
||||
image: xianyu-go:functional
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
volumes:
|
||||
- sqlite_verify_data:/app/data
|
||||
command: ["/app/xianyu-dbverify", "/app/data/verify.db"]
|
||||
|
||||
dbverify-postgres:
|
||||
image: xianyu-go:functional
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
command: ["/app/xianyu-dbverify", *postgres-url]
|
||||
|
||||
functional-test:
|
||||
image: curlimages/curl:8.16.0
|
||||
image: xianyu-go:functional
|
||||
restart: "no"
|
||||
depends_on:
|
||||
app-sqlite:
|
||||
condition: service_healthy
|
||||
app-mysql:
|
||||
condition: service_healthy
|
||||
app-postgres:
|
||||
@@ -190,5 +266,10 @@ volumes:
|
||||
mysql8_data:
|
||||
postgres17_data:
|
||||
sqlite_seed:
|
||||
sqlite_verify_data:
|
||||
app_sqlite_data:
|
||||
app_mysql_data:
|
||||
app_postgres_data:
|
||||
app_mysql_browser_data:
|
||||
app_postgres_browser_data:
|
||||
app_sqlite_browser_data:
|
||||
@@ -0,0 +1,285 @@
|
||||
# 滑块认证冻结规范
|
||||
|
||||
> **冻结级别:最高。当前滑块认证逻辑是已验证的生产行为,不得修改。**
|
||||
>
|
||||
> 除非用户在当前任务中明确要求修改滑块认证,否则任何开发者或自动化代理都不得编辑、重构、优化、重命名、移动或删除本规范保护的实现和测试,也不得通过修改调用方、浏览器配置或共享工具间接改变其行为。
|
||||
|
||||
本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。
|
||||
|
||||
## 1. 保护范围
|
||||
|
||||
以下文件为直接保护对象:
|
||||
|
||||
- `internal/browser/slider.go`
|
||||
- `internal/browser/slider_test.go`
|
||||
- `internal/browser/token_captcha.go`
|
||||
- `internal/browser/token_captcha_test.go`
|
||||
- `internal/browser/token_captcha_fallback.go`
|
||||
- `internal/browser/token_captcha_fallback_integration_test.go`
|
||||
- `internal/browser/token_captcha_orchestrator_test.go`
|
||||
|
||||
下列行为即使位于其他文件中,也属于冻结范围:
|
||||
|
||||
- `TokenCaptchaRecover` / `TokenCaptchaRecoverWithEngine` 的调用顺序、参数和返回语义。
|
||||
- 账号级持久化 Chromium profile 的目录解析、互斥、复用和释放时机。
|
||||
- 验证链接的获取、过期判断、重新获取时机和重试次数。
|
||||
- Cookie 注入、旧 `x5sec` 快照、新 `x5sec` 判定、合并和持久化。
|
||||
- Playwright 主引擎与直接 Chromium/CDP 备用引擎的启用条件和先后顺序。
|
||||
- 滑块 DOM 选择器及其优先级、同 frame 可见性要求、距离计算、轨迹、时序、成功判定、失败恢复和日志诊断。
|
||||
|
||||
禁止以“格式化”“去重”“抽取公共函数”“升级 Playwright”“增强兼容性”“提高成功率”“清理测试”等名义绕过冻结规则。
|
||||
|
||||
## 2. 标准 DOM 契约
|
||||
|
||||
当前无验证码(NC)页面的标准元素为:
|
||||
|
||||
| 角色 | 首选选择器 | 标准尺寸 |
|
||||
| --- | --- | --- |
|
||||
| 滑块按钮 | `#nc_1_n1z` | 宽 `42px` |
|
||||
| 滑轨 | `#nc_1_n1t` | 宽 `300px` |
|
||||
|
||||
标准滑动距离固定按可用轨道宽度计算:
|
||||
|
||||
```text
|
||||
distance = track.width - button.width
|
||||
= 300px - 42px
|
||||
= 258px
|
||||
```
|
||||
|
||||
不可把 `300px` 当作标准拖动距离,不可增加超调补偿。主引擎标准 NC 拖动的最终 X 必须精确落在 `258px`。
|
||||
|
||||
查找顺序和约束固定如下:
|
||||
|
||||
1. 在主 frame 和所有 iframe 中,优先查找同一 frame 内同时可见的 `#nc_1_n1z` 与 `#nc_1_n1t`。
|
||||
2. 仅在精确选择器组合未找到时,才按现有顺序使用宽松选择器。
|
||||
3. 按钮与轨道必须同时可见且位于同一 frame;不可跨 frame 拼接元素。
|
||||
|
||||
主引擎按钮选择器顺序:
|
||||
|
||||
```text
|
||||
#nc_1_n1z
|
||||
.nc_iconfont
|
||||
.btn_slide
|
||||
#scratch-captcha-btn
|
||||
.scratch-captcha-slider .button
|
||||
```
|
||||
|
||||
主引擎轨道选择器顺序:
|
||||
|
||||
```text
|
||||
#nc_1_n1t
|
||||
.nc_scale
|
||||
.nc_1_n1t
|
||||
```
|
||||
|
||||
备用引擎必须精确等待可见的 `#nc_1_n1z`。轨道选择器顺序为:
|
||||
|
||||
```text
|
||||
#nc_1_n1t
|
||||
.nc_scale
|
||||
#nc_1__scale_text
|
||||
.nc-lang-cnt
|
||||
#nc_1_wrapper
|
||||
.nc_wrapper
|
||||
```
|
||||
|
||||
刮刮乐验证码继续通过 `scratch-captcha`、`scratch-captcha-btn` 或 `scratch-captcha-slider` 标记识别,并只滑标准距离的 `25%–35%`。不得把这条降级兼容逻辑用于标准 NC DOM。
|
||||
|
||||
## 3. 主引擎行为
|
||||
|
||||
主引擎使用 Playwright 和账号现有的持久化浏览器上下文,最多执行 3 次滑块尝试。
|
||||
|
||||
### 3.1 页面准备
|
||||
|
||||
- 浏览器总生命周期上限为 `45s`。
|
||||
- 页面导航等待 `domcontentloaded`,导航超时为 `10s`;导航异常只记录告警并继续检查页面。
|
||||
- 页面加载后随机等待 `0.3–0.8s`,移动鼠标到 `(640, 360)`,滚动 `200–500px`,并保留现有短暂停顿。
|
||||
- 页面包含“抱歉,页面访问出现了问题”时,判定验证链接过期。
|
||||
- 页面包含 `STATUS_BREAKPOINT` 或“崩溃”时,判定验证页崩溃。
|
||||
- 拖动前必须保存所有域上的旧 `x5sec` 值,供严格成功判定使用。
|
||||
|
||||
### 3.2 距离计算
|
||||
|
||||
距离计算顺序固定为:
|
||||
|
||||
1. 用 DOM `getBoundingClientRect()` 计算 `track.width - button.width`。
|
||||
2. DOM 计算不可用时,用 Playwright bounding box 计算同一差值。
|
||||
3. 两者均不可用时,主引擎保留 `220–259px` 的现有降级距离。
|
||||
4. 仅刮刮乐场景再乘 `0.25–0.35`。
|
||||
|
||||
标准 NC 几何信息存在时,必须使用精确差值,不得随机化距离。
|
||||
|
||||
### 3.3 拖动轨迹
|
||||
|
||||
主引擎轨迹冻结为以下行为:
|
||||
|
||||
- 按钮按下前,从按钮左侧附近自然接近,再悬停、对准按钮中心并停顿。
|
||||
- 按下后使用恰好 6 个高层轨迹点。
|
||||
- 轨迹分为加速、匀速、减速三段;带小幅 Y 轴抖动。
|
||||
- X 轴不超调,最后一个点强制等于计算出的精确距离。
|
||||
- 保留每个点的短随机计划延时,同时按真实墙钟时间补偿,使移动阶段处于 `480–900ms` 目标窗口。
|
||||
- 顺序固定为 `mouse down → 分段移动 → mouse up → 兼容性 click 事件`。
|
||||
- 标准 NC 不得添加尾部超调、回拉或额外轨迹点。
|
||||
|
||||
拖动完成后保留 `800ms` 等待,再进入严格成功检查。
|
||||
|
||||
## 4. 严格成功条件
|
||||
|
||||
Token 风控滑块只有同时满足以下两个条件才算成功:
|
||||
|
||||
1. 浏览器上下文出现相对拖动前快照全新的、非空的 `x5sec`;旧值不得重复计为成功。
|
||||
2. 当前页面已经离开 punish/captcha URL。
|
||||
|
||||
以下 URL 标记任一存在时,仍视为停留在验证页:
|
||||
|
||||
```text
|
||||
punish
|
||||
x5step=2
|
||||
action=captcha
|
||||
purecaptcha
|
||||
/captcha
|
||||
```
|
||||
|
||||
`.nc-container` 消失、滑块隐藏、成功图标出现或 frame 断开都不能单独证明 Token 风控成功。严格路径必须以“新 `x5sec` + 离开验证 URL”为准。
|
||||
|
||||
严格检查期间,只要出现明确失败控件就立即按失败处理。主引擎拖动后最多等待 `5s` 进行严格确认;完成拖动后还会以 `250ms` 间隔等待新 Cookie,最长 `15s`。成功后收集浏览器上下文当前的 `x5*` Cookie,确保合并的是新签发的 `x5sec`,再合并回原 Cookie 字符串。
|
||||
|
||||
非 Token 场景调用通用 `solveSlider` 时,继续保留现有的可见成功标记或 `.nc-container` 消失判定;不得把该宽松判定用于 Token 风控路径。
|
||||
|
||||
## 5. 失败识别与恢复
|
||||
|
||||
明确失败控件固定为以下前三项:
|
||||
|
||||
```text
|
||||
#nc_1_refresh1
|
||||
.nc_iconfont.btn_refresh
|
||||
.errloading
|
||||
```
|
||||
|
||||
点击恢复时按以下优先级查找:
|
||||
|
||||
```text
|
||||
#nc_1_refresh1
|
||||
.nc_iconfont.btn_refresh
|
||||
.errloading
|
||||
[class*='refresh']
|
||||
```
|
||||
|
||||
`.nc-container` 只能在其文本包含下列失败/重试词之一时点击:
|
||||
|
||||
```text
|
||||
重试 刷新 失败 retry refresh failed
|
||||
```
|
||||
|
||||
禁止无条件点击初始 `.nc-container`,因为这可能误触发拖动。
|
||||
|
||||
恢复状态机固定如下:
|
||||
|
||||
1. 优先点击可见的失败/刷新控件。
|
||||
2. 控件可能延迟出现,首次未找到时按现有逻辑最多短暂等待 `800ms` 并轮询。
|
||||
3. 点击后最多等待 `4s`,确认按钮和轨道重新出现,且按钮回到轨道起点 `±3px` 内。
|
||||
4. 点击恢复失败或滑块未归位时,重载原页面。
|
||||
5. 重载等待 `domcontentloaded`,单次超时最多 `8s`;重载后最多等待 `5s` 确认滑块归位。
|
||||
6. 主引擎两次尝试之间保留 `1–2s` 随机等待;总尝试次数保持 3 次。
|
||||
|
||||
不得用“元素重新出现”替代“元素重新出现且按钮回到原点”的确认。
|
||||
|
||||
## 6. 引擎编排
|
||||
|
||||
固定执行顺序为:
|
||||
|
||||
```text
|
||||
Playwright 主引擎
|
||||
→ 链接过期时,关闭当前持久化上下文后重新获取链接并重试主引擎
|
||||
→ 主引擎发生非链接过期失败时,按配置进入直接 Chromium/CDP 备用引擎
|
||||
→ 备用引擎仍必须取得新的 x5sec 才能成功
|
||||
```
|
||||
|
||||
约束如下:
|
||||
|
||||
- 获取新验证链接的 provider 不得在主引擎持有同账号持久化 profile 锁时调用,避免同账号锁死。
|
||||
- 过期链接最多触发现有的 2 次链接刷新;最终仍过期时直接失败,不把过期 URL 交给备用引擎重放。
|
||||
- 进入备用引擎前可再获取一次新链接和更新后的 Cookie。
|
||||
- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。
|
||||
- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。
|
||||
- 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。
|
||||
|
||||
## 7. 备用引擎行为
|
||||
|
||||
备用引擎直接启动 Chromium,通过 `DevToolsActivePort` 连接 CDP,不改用 Playwright 的常规 launch 流程。它必须:
|
||||
|
||||
- 与主引擎使用同一账号持久化 profile 目录。
|
||||
- 保持账号级互斥和全局续期槽位控制。
|
||||
- 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。
|
||||
- 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。
|
||||
- headless 时使用 `--headless=new`。
|
||||
- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。
|
||||
|
||||
备用距离规则固定如下:
|
||||
|
||||
1. 按钮和轨道 bounding box 都存在时,精确使用 `track.width - button.width`;标准 DOM 必须得到 `258px`。
|
||||
2. 仅轨道宽度可用时,保留基于轨道宽度的 `70%–90%` 加 `-20–20px` 偏移,并限制在 `200–600px`。
|
||||
3. 轨道几何信息不可用时,才按 viewport 宽度使用现有随机范围。
|
||||
|
||||
备用引擎保留 3 种尝试模式:
|
||||
|
||||
| 尝试 | 计划移动时间 | 轨迹点数 | 特征 |
|
||||
| --- | --- | --- | --- |
|
||||
| 第 1 次 | `1.5–4s` | `60–150` | 常规 |
|
||||
| 第 2 次 | `0.9–1.3s` | `30–60` | 急促,按下/释放等待更短 |
|
||||
| 第 3 次 | `1–2s` | `50–90` | 常规 |
|
||||
|
||||
备用轨迹保留现有加速、匀速、减速、犹豫、Y 轴趋势与抖动、偶发轻微超调及回正、清洗和重采样行为。这个行为与主引擎“不得超调”的规则不同,不得相互替换。每次失败后复用第 5 节的恢复流程,最多尝试 3 次;成功仍要求新的 `x5sec` 且已经离开 punish/captcha URL。
|
||||
|
||||
## 8. 诊断日志
|
||||
|
||||
以下诊断字段属于冻结行为,不得删除或降级:
|
||||
|
||||
- 页面 URL 和 frame URL,且必须去掉 query 与 fragment,避免日志泄露验证参数。
|
||||
- 按钮、轨道 bounding box 和 class。
|
||||
- 计算出的滑动距离。
|
||||
- 轨迹点数、计划时长/延时、目标移动时长、真实移动时长和总耗时。
|
||||
- 最终 `left`、最终 class 或最终 X 偏移。
|
||||
- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。
|
||||
- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。
|
||||
|
||||
页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
||||
|
||||
| 工具 | DOM 标记 |
|
||||
| --- | --- |
|
||||
| Requestly | `rq-implicit-test-rule-widget` |
|
||||
| PikPak | `#__PIKPAK_EXTENSION__` |
|
||||
| DeepL | `deepl-input-controller` |
|
||||
| 沉浸式翻译 | `#immersive-translate-browser-popup` |
|
||||
|
||||
## 9. 必须保留的验证
|
||||
|
||||
任何获得用户明确授权的滑块改动,都必须至少保持以下验证通过:
|
||||
|
||||
```bash
|
||||
go test ./internal/browser
|
||||
go test ./internal/engine ./internal/account ./internal/server
|
||||
go build ./cmd/server
|
||||
go vet ./internal/browser ./internal/engine ./internal/account ./internal/server ./cmd/server
|
||||
```
|
||||
|
||||
同时必须保留直接 Chromium 集成场景:
|
||||
|
||||
- 主引擎首次滑动成功。
|
||||
- 主引擎首次失败并隐藏滑块,点击 `.errloading` 恢复后第二次成功。
|
||||
- 直接 Chromium/CDP 备用引擎使用同一恢复流程后成功。
|
||||
- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。
|
||||
- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。
|
||||
|
||||
不得删除、跳过、弱化或改写断言来让行为变化通过测试。
|
||||
|
||||
## 10. 唯一变更流程
|
||||
|
||||
只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中:
|
||||
|
||||
1. 说明要改变本文哪一条冻结契约及原因。
|
||||
2. 同步更新实现、单元测试、真实 Chromium 集成测试和本文。
|
||||
3. 完成第 9 节验证并报告结果。
|
||||
4. 不得把一次授权推定为后续任务的持续授权。
|
||||
|
||||
没有上述明确授权时,遇到与滑块相关的需求或测试失败,应停止修改滑块代码,保留现场并向用户说明冲突。
|
||||
+5
-4
@@ -8,6 +8,7 @@ import ItemList from './components/ItemList';
|
||||
import Settings from './components/Settings';
|
||||
import Rules from './components/Rules';
|
||||
import Notifications from './components/Notifications';
|
||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
||||
import { login, logout, verifySession } from './services/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
|
||||
@@ -157,8 +158,8 @@ const App: React.FC = () => {
|
||||
|
||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in">
|
||||
<div className="text-center mb-8">
|
||||
<div className="w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4" style={{ filter: 'drop-shadow(0 8px 20px rgba(0,148,247,0.3))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
|
||||
<div className="mx-auto mb-6 flex justify-center">
|
||||
<YdisksBrandIcon sizeClass="w-24 h-24" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">系统尚未初始化</h2>
|
||||
<p className="text-gray-600 font-medium">为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。</p>
|
||||
@@ -202,8 +203,8 @@ const App: React.FC = () => {
|
||||
|
||||
{/* Header with Logo */}
|
||||
<div className="text-center mb-10">
|
||||
<div className="w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 cursor-pointer group p-4" style={{ filter: 'drop-shadow(0 8px 20px rgba(0,148,247,0.3))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full group-hover:scale-110 transition-transform" />
|
||||
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
|
||||
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
|
||||
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
|
||||
|
||||
+374
-137
@@ -9,27 +9,32 @@ import {
|
||||
generateQRLogin,
|
||||
checkQRLoginStatus,
|
||||
completeQRVerification,
|
||||
updateAccountRemark,
|
||||
updateAccountAutoConfirm,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountCookie,
|
||||
refreshAccountProfile,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountSettings,
|
||||
passwordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
cancelPasswordLogin,
|
||||
updateAccountAISettings,
|
||||
getAllAISettings,
|
||||
getAccountAISettings,
|
||||
getNotificationChannels,
|
||||
getAccountBindings,
|
||||
setAccountBindings,
|
||||
getLongLoginSettings,
|
||||
setLongLoginSettings,
|
||||
} from '../services/api';
|
||||
import { shouldUpdateAccountPause } from './accountPause';
|
||||
import {
|
||||
Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2,
|
||||
RefreshCw, Save, User, Clock, MessageCircle,
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell
|
||||
} from 'lucide-react';
|
||||
import { buildAccountLoginInfoUpdate } from './accountEdit';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
import { createQRLoginPoller } from './qrPolling';
|
||||
import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
|
||||
type ModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
@@ -41,13 +46,12 @@ const AccountList: React.FC = () => {
|
||||
const [showQRModal, setShowQRModal] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const [qrStatus, setQrStatus] = useState<string>('pending');
|
||||
const [verificationUrl, setVerificationUrl] = useState<string>('');
|
||||
const [verificationScreenshot, setVerificationScreenshot] = useState<string>('');
|
||||
const [faceQrUrl, setFaceQrUrl] = useState<string>('');
|
||||
const [qrSessionId, setQrSessionId] = useState<string>('');
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
const [activeModal, setActiveModal] = useState<ModalType>(null);
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||
@@ -79,11 +83,34 @@ const AccountList: React.FC = () => {
|
||||
custom_prompts: '',
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [passwordLoginView, setPasswordLoginView] = useState<{
|
||||
sessionId: string;
|
||||
status: 'idle' | 'processing' | 'verification_required' | 'success' | 'failed';
|
||||
message: string;
|
||||
qrCodeUrl: string;
|
||||
}>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
|
||||
const qrCloseTimerRef = useRef<ReturnType<typeof window.setTimeout> | null>(null);
|
||||
const qrRequestGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const accountLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const bindingsLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const aiLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const accountLoadAbortRef = useRef<AbortController | null>(null);
|
||||
const bindingsLoadAbortRef = useRef<AbortController | null>(null);
|
||||
const aiLoadAbortRef = useRef<AbortController | null>(null);
|
||||
const qrGenerateAbortRef = useRef<AbortController | null>(null);
|
||||
const passwordPollAbortRef = useRef<AbortController | null>(null);
|
||||
const qrCloseTimerRef = useRef<number | null>(null);
|
||||
const passwordPollTimerRef = useRef<number | null>(null);
|
||||
const passwordPollGenerationRef = useRef(0);
|
||||
if (qrPollerRef.current === null) {
|
||||
qrPollerRef.current = createQRLoginPoller();
|
||||
}
|
||||
if (qrRequestGateRef.current === null) {
|
||||
qrRequestGateRef.current = createLatestRequestGate();
|
||||
}
|
||||
if (accountLoadGateRef.current === null) accountLoadGateRef.current = createLatestRequestGate();
|
||||
if (bindingsLoadGateRef.current === null) bindingsLoadGateRef.current = createLatestRequestGate();
|
||||
if (aiLoadGateRef.current === null) aiLoadGateRef.current = createLatestRequestGate();
|
||||
|
||||
const clearQRCloseTimer = () => {
|
||||
if (qrCloseTimerRef.current !== null) {
|
||||
@@ -92,11 +119,20 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const clearPasswordPollTimer = () => {
|
||||
if (passwordPollTimerRef.current !== null) {
|
||||
window.clearTimeout(passwordPollTimerRef.current);
|
||||
passwordPollTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const stopQRPolling = () => {
|
||||
qrPollerRef.current?.stop();
|
||||
};
|
||||
|
||||
const closeQRModal = () => {
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
qrRequestGateRef.current?.cancel();
|
||||
stopQRPolling();
|
||||
clearQRCloseTimer();
|
||||
setShowQRModal(false);
|
||||
@@ -111,37 +147,20 @@ const AccountList: React.FC = () => {
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const refreshRuntimeStatuses = async () => {
|
||||
try {
|
||||
const statuses = await getAccountRuntimeStatuses();
|
||||
setAccounts(current => current.map(account => {
|
||||
const status = statuses[account.id];
|
||||
if (!status) return account;
|
||||
return {
|
||||
...account,
|
||||
runtime_state: status.state,
|
||||
runtime_message: status.message || '',
|
||||
runtime_connected: status.connected,
|
||||
runtime_updated_at: status.updated_at,
|
||||
};
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Failed to load account runtime statuses:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const loadAccounts = async () => {
|
||||
const generation = accountLoadGateRef.current!.next();
|
||||
accountLoadAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
accountLoadAbortRef.current = controller;
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getAccountDetails();
|
||||
|
||||
// 获取所有账号的AI设置
|
||||
let allAISettings: Record<string, AIReplySettings> = {};
|
||||
try {
|
||||
allAISettings = await getAllAISettings();
|
||||
} catch (e) {
|
||||
console.error('Failed to load AI settings:', e);
|
||||
}
|
||||
const options = { signal: controller.signal };
|
||||
const [detailsResult, aiResult] = await Promise.allSettled([getAccountDetails(options), getAllAISettings(options)]);
|
||||
if (!accountLoadGateRef.current?.isCurrent(generation)) return;
|
||||
if (detailsResult.status === 'rejected') throw detailsResult.reason;
|
||||
const data = detailsResult.value;
|
||||
const allAISettings = aiResult.status === 'fulfilled' ? aiResult.value : {};
|
||||
if (aiResult.status === 'rejected') console.error('Failed to load AI settings:', aiResult.reason);
|
||||
|
||||
// 合并AI设置到账号数据
|
||||
const accountsWithAI = data.map(account => ({
|
||||
@@ -153,25 +172,62 @@ const AccountList: React.FC = () => {
|
||||
custom_prompts: allAISettings[account.id]?.custom_prompts ?? '',
|
||||
}));
|
||||
|
||||
setAccounts(accountsWithAI);
|
||||
window.setTimeout(refreshRuntimeStatuses, 0);
|
||||
if (accountLoadGateRef.current?.isCurrent(generation)) setAccounts(accountsWithAI);
|
||||
} catch (error) {
|
||||
console.error('Failed to load accounts:', error);
|
||||
if (accountLoadGateRef.current?.isCurrent(generation) && !controller.signal.aborted) {
|
||||
console.error('Failed to load accounts:', error);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (accountLoadGateRef.current?.isCurrent(generation)) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadAccounts();
|
||||
const timer = window.setInterval(refreshRuntimeStatuses, 10_000);
|
||||
return () => window.clearInterval(timer);
|
||||
let cancelled = false;
|
||||
let timer: number | null = null;
|
||||
const runtimeController = new AbortController();
|
||||
|
||||
const pollRuntimeStatuses = async () => {
|
||||
try {
|
||||
const statuses = await getAccountRuntimeStatuses({ signal: runtimeController.signal, timeoutMs: 10_000 });
|
||||
if (!cancelled) {
|
||||
setAccounts(current => mergeAccountRuntimeStatuses(current, statuses));
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) console.error('Failed to load account runtime statuses:', error);
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
// 运行时状态只读取本地内存;短轮询让风控恢复提示在约 2 秒内收敛。
|
||||
timer = window.setTimeout(() => void pollRuntimeStatuses(), 2_000);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadAccounts().finally(() => {
|
||||
if (!cancelled) void pollRuntimeStatuses();
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
runtimeController.abort();
|
||||
if (timer !== null) window.clearTimeout(timer);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopQRPolling();
|
||||
qrRequestGateRef.current?.cancel();
|
||||
accountLoadGateRef.current?.cancel();
|
||||
bindingsLoadGateRef.current?.cancel();
|
||||
aiLoadGateRef.current?.cancel();
|
||||
accountLoadAbortRef.current?.abort();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearQRCloseTimer();
|
||||
passwordPollGenerationRef.current += 1;
|
||||
clearPasswordPollTimer();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -228,14 +284,19 @@ const AccountList: React.FC = () => {
|
||||
};
|
||||
|
||||
const loadNotificationBindings = async (accountId: string) => {
|
||||
const generation = bindingsLoadGateRef.current!.next();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
bindingsLoadAbortRef.current = controller;
|
||||
setBindingsLoading(true);
|
||||
setBindingsLoaded(false);
|
||||
setBindingsDirty(false);
|
||||
setBindingsLoadError('');
|
||||
const [channelsResult, bindingsResult] = await Promise.allSettled([
|
||||
getNotificationChannels(),
|
||||
getAccountBindings(accountId),
|
||||
getNotificationChannels({ signal: controller.signal }),
|
||||
getAccountBindings(accountId, { signal: controller.signal }),
|
||||
]);
|
||||
if (!bindingsLoadGateRef.current?.isCurrent(generation)) return;
|
||||
if (channelsResult.status === 'fulfilled') {
|
||||
setNotifChannels(channelsResult.value.data || []);
|
||||
} else {
|
||||
@@ -253,6 +314,10 @@ const AccountList: React.FC = () => {
|
||||
};
|
||||
|
||||
const openEditModal = async (account: AccountDetail) => {
|
||||
passwordPollGenerationRef.current += 1;
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
setEditingAccount(account);
|
||||
setEditForm({
|
||||
remark: account.remark || account.note || '',
|
||||
@@ -266,14 +331,41 @@ const AccountList: React.FC = () => {
|
||||
clear_password: false,
|
||||
});
|
||||
setActiveModal('edit');
|
||||
await loadNotificationBindings(account.id);
|
||||
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
const [, longLoginResult] = await Promise.allSettled([
|
||||
loadNotificationBindings(account.id),
|
||||
getLongLoginSettings(account.id),
|
||||
]);
|
||||
if (longLoginResult.status === 'fulfilled') {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
|
||||
} else {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleLongLoginToggle = async () => {
|
||||
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
|
||||
const enabled = !longLogin.enabled;
|
||||
setLongLogin(current => ({ ...current, saving: true, error: '' }));
|
||||
try {
|
||||
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||
} catch (error) {
|
||||
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||
}
|
||||
};
|
||||
|
||||
const openAIModal = async (account: AccountDetail) => {
|
||||
const generation = aiLoadGateRef.current!.next();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
aiLoadAbortRef.current = controller;
|
||||
setEditingAccount(account);
|
||||
setActiveModal('ai-settings');
|
||||
setSaving(true);
|
||||
try {
|
||||
const settings = await getAccountAISettings(account.id);
|
||||
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||
if (!aiLoadGateRef.current?.isCurrent(generation)) return;
|
||||
setAiSettings({
|
||||
ai_enabled: settings.ai_enabled ?? false,
|
||||
max_discount_percent: settings.max_discount_percent ?? 10,
|
||||
@@ -282,11 +374,10 @@ const AccountList: React.FC = () => {
|
||||
custom_prompts: settings.custom_prompts ?? '',
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to load AI settings:', e);
|
||||
if (aiLoadGateRef.current?.isCurrent(generation)) console.error('Failed to load AI settings:', e);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
if (aiLoadGateRef.current?.isCurrent(generation)) setSaving(false);
|
||||
}
|
||||
setActiveModal('ai-settings');
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
@@ -294,40 +385,40 @@ const AccountList: React.FC = () => {
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
const promises: Promise<any>[] = [];
|
||||
const payload: Parameters<typeof updateAccountSettings>[1] = {};
|
||||
|
||||
// 更新备注
|
||||
if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) {
|
||||
promises.push(updateAccountRemark(editingAccount.id, editForm.remark));
|
||||
payload.remark = editForm.remark;
|
||||
}
|
||||
|
||||
// 更新Cookie
|
||||
if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) {
|
||||
promises.push(updateAccountCookie(editingAccount.id, editForm.cookie));
|
||||
payload.cookie = editForm.cookie;
|
||||
}
|
||||
|
||||
// 更新自动确认
|
||||
if (editForm.auto_confirm !== editingAccount.auto_confirm) {
|
||||
promises.push(updateAccountAutoConfirm(editingAccount.id, editForm.auto_confirm));
|
||||
payload.auto_confirm = editForm.auto_confirm;
|
||||
}
|
||||
|
||||
// 更新暂停时长
|
||||
if (editForm.pause_duration !== (editingAccount.pause_duration || 0)) {
|
||||
promises.push(updateAccountPauseDuration(editingAccount.id, editForm.pause_duration));
|
||||
}
|
||||
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) {
|
||||
payload.pause_duration = editForm.pause_duration;
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
|
||||
if (loginInfo) {
|
||||
promises.push(updateAccountLoginInfo(editingAccount.id, loginInfo));
|
||||
Object.assign(payload, loginInfo);
|
||||
}
|
||||
|
||||
// 只有成功加载且用户确实改动后才覆盖,避免加载失败被误解释成解绑全部。
|
||||
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) {
|
||||
promises.push(setAccountBindings(editingAccount.id, selectedChannelIds));
|
||||
payload.channel_ids = selectedChannelIds;
|
||||
}
|
||||
|
||||
await Promise.all(promises);
|
||||
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
|
||||
setActiveModal(null);
|
||||
loadAccounts();
|
||||
} catch (error) {
|
||||
@@ -338,6 +429,25 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestartPause = async () => {
|
||||
if (!editingAccount || editForm.pause_duration <= 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
|
||||
setEditingAccount({
|
||||
...editingAccount,
|
||||
pause_duration: editForm.pause_duration,
|
||||
paused: result?.paused === true,
|
||||
paused_until: Number(result?.paused_until || 0),
|
||||
});
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
alert(error instanceof Error ? error.message : '重新暂停失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAISettings = async () => {
|
||||
if (!editingAccount) return;
|
||||
setSaving(true);
|
||||
@@ -354,13 +464,122 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => {
|
||||
let res = await completeQRVerification(sessionId, target?.id);
|
||||
if (res.requires_confirmation) {
|
||||
const confirmed = confirm(`扫码返回的账号ID是 ${res.scanned_account_id || '未知'},确认覆盖 ${target?.id || '当前账号'} 的授权吗?`);
|
||||
if (!confirmed) return '';
|
||||
res = await completeQRVerification(sessionId, target?.id, true);
|
||||
const pollPasswordLogin = async (sessionId: string, generation: number) => {
|
||||
passwordPollAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
passwordPollAbortRef.current = controller;
|
||||
try {
|
||||
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
|
||||
if (generation !== passwordPollGenerationRef.current) return;
|
||||
if (result.status === 'success') {
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({
|
||||
sessionId,
|
||||
status: 'success',
|
||||
message: result.message || '账号密码登录成功,授权信息已更新',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
|
||||
await loadAccounts();
|
||||
return;
|
||||
}
|
||||
if (result.status === 'processing' || result.status === 'verification_required') {
|
||||
setPasswordLoginView({
|
||||
sessionId,
|
||||
status: result.status,
|
||||
message: result.message || (result.status === 'verification_required' ? '账号触发风控,需要完成人脸识别' : '登录处理中'),
|
||||
qrCodeUrl: result.qr_code_url || '',
|
||||
});
|
||||
clearPasswordPollTimer();
|
||||
passwordPollTimerRef.current = window.setTimeout(() => void pollPasswordLogin(sessionId, generation), 1500);
|
||||
return;
|
||||
}
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({
|
||||
sessionId,
|
||||
status: 'failed',
|
||||
message: result.error || result.message || '密码登录失败,请检查账号信息后重试',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
} catch (error) {
|
||||
if (generation !== passwordPollGenerationRef.current) return;
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({
|
||||
sessionId,
|
||||
status: 'failed',
|
||||
message: error instanceof Error ? error.message : '查询密码登录状态失败',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handlePasswordLogin = async () => {
|
||||
if (!editingAccount) return;
|
||||
const account = editForm.username.trim();
|
||||
if (!account || !editForm.login_password) {
|
||||
alert('请先填写登录账号和本次登录密码');
|
||||
return;
|
||||
}
|
||||
clearPasswordPollTimer();
|
||||
passwordPollAbortRef.current?.abort();
|
||||
const generation = ++passwordPollGenerationRef.current;
|
||||
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
|
||||
try {
|
||||
const result = await passwordLogin({
|
||||
account_id: editingAccount.id,
|
||||
account,
|
||||
password: editForm.login_password,
|
||||
show_browser: editForm.show_browser,
|
||||
});
|
||||
if (generation !== passwordPollGenerationRef.current) return;
|
||||
if (!result.success || !result.session_id) {
|
||||
throw new Error(result.message || '无法启动密码登录');
|
||||
}
|
||||
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
|
||||
await pollPasswordLogin(result.session_id, generation);
|
||||
} catch (error) {
|
||||
if (generation !== passwordPollGenerationRef.current) return;
|
||||
setPasswordLoginView({
|
||||
sessionId: '',
|
||||
status: 'failed',
|
||||
message: error instanceof Error ? error.message : '启动密码登录失败',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelPasswordLogin = async () => {
|
||||
const sessionId = passwordLoginView.sessionId;
|
||||
passwordPollGenerationRef.current += 1;
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearPasswordPollTimer();
|
||||
if (sessionId) {
|
||||
try {
|
||||
await cancelPasswordLogin(sessionId);
|
||||
} catch (error) {
|
||||
console.error('取消密码登录失败', error);
|
||||
}
|
||||
}
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
};
|
||||
|
||||
const closeEditModal = async () => {
|
||||
bindingsLoadGateRef.current?.cancel();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') {
|
||||
await handleCancelPasswordLogin();
|
||||
}
|
||||
setActiveModal(null);
|
||||
};
|
||||
|
||||
const closeAIModal = () => {
|
||||
aiLoadGateRef.current?.cancel();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
setActiveModal(null);
|
||||
};
|
||||
|
||||
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => {
|
||||
const res = await completeQRVerification(sessionId, target?.id);
|
||||
if (!res.success || !res.account_id) {
|
||||
throw new Error(res.message || '保存扫码授权失败');
|
||||
}
|
||||
@@ -369,27 +588,30 @@ const AccountList: React.FC = () => {
|
||||
|
||||
const startQRLogin = async (target?: AccountDetail) => {
|
||||
stopQRPolling();
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
qrGenerateAbortRef.current = controller;
|
||||
const requestGeneration = qrRequestGateRef.current!.next();
|
||||
clearQRCloseTimer();
|
||||
const targetAccount = target || null;
|
||||
setQrReauthTarget(targetAccount);
|
||||
setShowQRModal(true);
|
||||
setQrStatus('loading');
|
||||
setQrCodeUrl('');
|
||||
setQrSessionId('');
|
||||
setVerificationUrl('');
|
||||
setVerificationScreenshot('');
|
||||
setFaceQrUrl('');
|
||||
try {
|
||||
const res = await generateQRLogin();
|
||||
const res = await generateQRLogin({ signal: controller.signal });
|
||||
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||
if (res.success && res.qr_code_url && res.session_id) {
|
||||
const generatedSessionID = res.session_id;
|
||||
setQrCodeUrl(res.qr_code_url);
|
||||
setQrSessionId(res.session_id);
|
||||
setQrStatus('waiting');
|
||||
|
||||
qrPollerRef.current?.start(res.session_id, checkQRLoginStatus, {
|
||||
qrPollerRef.current?.start(generatedSessionID, checkQRLoginStatus, {
|
||||
onSuccess: async () => {
|
||||
try {
|
||||
const accountId = await completeAndPersistQRSession(res.session_id, targetAccount);
|
||||
const accountId = await completeAndPersistQRSession(generatedSessionID, targetAccount);
|
||||
if (!accountId) {
|
||||
setQrStatus('error');
|
||||
return;
|
||||
@@ -414,7 +636,6 @@ const AccountList: React.FC = () => {
|
||||
},
|
||||
onVerificationRequired: (statusRes) => {
|
||||
setQrStatus('verification');
|
||||
setVerificationUrl(statusRes.verification_url || '');
|
||||
if (statusRes.face_qr_url) {
|
||||
setFaceQrUrl(statusRes.face_qr_url);
|
||||
}
|
||||
@@ -425,29 +646,11 @@ const AccountList: React.FC = () => {
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||
setQrStatus('error');
|
||||
}
|
||||
};
|
||||
|
||||
// 用户完成风控验证后,点"我已完成验证"调用后端提取真实 cookie。
|
||||
const handleCompleteVerification = async () => {
|
||||
if (!qrSessionId) return;
|
||||
setQrStatus('loading');
|
||||
try {
|
||||
const accountId = await completeAndPersistQRSession(qrSessionId, qrReauthTarget);
|
||||
if (accountId) {
|
||||
stopQRPolling();
|
||||
setQrStatus('success');
|
||||
scheduleQRModalClose();
|
||||
} else {
|
||||
setQrStatus('verification');
|
||||
}
|
||||
} catch (e) {
|
||||
setQrStatus('verification');
|
||||
alert('处理失败:' + (e instanceof Error ? e.message : String(e)));
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-[#0094f7] animate-spin"/></div>;
|
||||
|
||||
const filteredAccounts = accounts.filter(account => {
|
||||
@@ -555,7 +758,7 @@ const AccountList: React.FC = () => {
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
{account.auto_confirm && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Check className="w-3 h-3"/> 自动确认发货</span>}
|
||||
{account.pause_duration > 0 && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Clock className="w-3 h-3"/> 暂停{account.pause_duration}分钟</span>}
|
||||
{account.paused && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Clock className="w-3 h-3"/> 暂停处理中</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -626,7 +829,7 @@ const AccountList: React.FC = () => {
|
||||
{/* QR Code Modal */}
|
||||
{showQRModal && createPortal(
|
||||
<div className="modal-overlay-centered">
|
||||
<div className="modal-container relative" style={{maxWidth: '24rem'}}>
|
||||
<div className="modal-container relative" style={{maxWidth: '26rem'}}>
|
||||
<button
|
||||
onClick={closeQRModal}
|
||||
className="absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors"
|
||||
@@ -645,9 +848,9 @@ const AccountList: React.FC = () => {
|
||||
: '请打开闲鱼APP扫描下方二维码'}
|
||||
</p>
|
||||
|
||||
<div className="w-64 h-64 bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-8 relative">
|
||||
<div className={`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${qrStatus === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
|
||||
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-[#0094f7] animate-spin" />}
|
||||
{qrStatus === 'waiting' && <img src={qrCodeUrl} alt="QR Code" className="w-full h-full p-2" />}
|
||||
{qrStatus === 'waiting' && <SquareQRCode src={qrCodeUrl} alt="闲鱼登录二维码" className="p-2" />}
|
||||
{qrStatus === 'success' && (
|
||||
<div className="absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in">
|
||||
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
|
||||
@@ -656,43 +859,18 @@ const AccountList: React.FC = () => {
|
||||
<span className="font-bold text-lg">登录成功</span>
|
||||
</div>
|
||||
)}
|
||||
{qrStatus === 'error' && (
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-red-500 font-bold mb-2">获取失败</span>
|
||||
<button onClick={() => startQRLogin(qrReauthTarget || undefined)} className="text-xs bg-gray-200 px-3 py-1 rounded-full flex items-center gap-1 hover:bg-gray-300"><RefreshCw className="w-3 h-3"/> 重试</button>
|
||||
</div>
|
||||
)}
|
||||
{qrStatus === 'verification' && (
|
||||
<div className="flex flex-col items-center px-4">
|
||||
<span className="font-bold text-gray-900 mb-2">需要安全验证</span>
|
||||
<span className="text-xs text-gray-500 mb-3 text-center">
|
||||
{faceQrUrl
|
||||
? '请用手机闲鱼扫描下方二维码完成人脸验证,验证通过后将自动登录。'
|
||||
: '正在准备验证二维码,请保持页面打开。'}
|
||||
</span>
|
||||
{faceQrUrl ? (
|
||||
<img src={faceQrUrl} alt="人脸验证二维码" className="w-full max-w-[210px] rounded-xl border bg-white p-2 mb-2" />
|
||||
) : verificationScreenshot ? (
|
||||
<img src={verificationScreenshot} alt="验证页面" className="w-full rounded-xl border mb-2" style={{maxHeight: 200, objectFit: 'contain'}} />
|
||||
) : (
|
||||
<div className="w-full h-32 bg-gray-100 rounded-xl flex items-center justify-center mb-2">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-gray-400" />
|
||||
</div>
|
||||
)}
|
||||
{verificationUrl && (
|
||||
<a href={verificationUrl} target="_blank" rel="noopener noreferrer" className="mt-2 text-sm font-bold text-[#0094f7] flex items-center gap-1">
|
||||
<ExternalLink className="w-4 h-4" />打开安全验证页面
|
||||
</a>
|
||||
)}
|
||||
<button type="button" onClick={handleCompleteVerification} className="mt-3 ios-btn-primary px-4 py-2 rounded-xl text-sm font-bold">
|
||||
我已完成验证
|
||||
</button>
|
||||
<span className="text-xs text-gray-400 mt-2">验证完成后点击确认,系统会提取并保存登录状态。</span>
|
||||
</div>
|
||||
)}
|
||||
{qrStatus === 'error' && (
|
||||
<div className="px-5 text-center">
|
||||
<span className="block text-red-600 font-bold">二维码获取失败</span>
|
||||
<span className="mt-2 block text-xs leading-5 text-gray-500">请关闭窗口后重新发起扫码登录。</span>
|
||||
</div>
|
||||
)}
|
||||
{qrStatus === 'verification' && (
|
||||
<RiskVerificationPanel faceQrUrl={faceQrUrl} verificationScreenshot={verificationScreenshot} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl">二维码有效期为5分钟,请尽快扫码。</p>
|
||||
{qrStatus !== 'verification' && <p className="text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl">二维码有效期为5分钟,请尽快扫码。</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -710,7 +888,7 @@ const AccountList: React.FC = () => {
|
||||
<p className="text-sm text-gray-500 mt-1">{editingAccount.nickname || editingAccount.remark || editingAccount.id}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setActiveModal(null)}
|
||||
onClick={() => void closeEditModal()}
|
||||
className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-500" />
|
||||
@@ -793,6 +971,16 @@ const AccountList: React.FC = () => {
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">设置后会暂停处理该账号的订单,到时间后自动恢复</p>
|
||||
{editForm.pause_duration > 0 && !editingAccount.paused && editForm.pause_duration === (editingAccount.pause_duration || 0) && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void handleRestartPause()}
|
||||
className="mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50"
|
||||
>
|
||||
立即按当前时长重新暂停
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 登录信息 */}
|
||||
@@ -802,6 +990,22 @@ const AccountList: React.FC = () => {
|
||||
登录信息
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4">
|
||||
<div>
|
||||
<div className="font-bold text-gray-900">保存登录信息</div>
|
||||
<div className="mt-1 text-xs text-gray-500">状态直接读取并修改闲鱼官方长登录设置</div>
|
||||
{longLogin.error && <div className="mt-1 text-xs text-red-600">{longLogin.error}</div>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="保存登录信息"
|
||||
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
|
||||
onClick={() => void handleLongLoginToggle()}
|
||||
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
>
|
||||
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">用户名</label>
|
||||
<input
|
||||
@@ -859,6 +1063,39 @@ const AccountList: React.FC = () => {
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<div className="rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||
<div>
|
||||
<div className="font-bold text-blue-950">立即执行账号密码登录</div>
|
||||
<div className="text-xs text-blue-700 mt-1">需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。</div>
|
||||
</div>
|
||||
{(passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') ? (
|
||||
<button type="button" onClick={handleCancelPasswordLogin} className="px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100">
|
||||
取消登录
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" onClick={handlePasswordLogin} className="px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap">
|
||||
密码登录刷新授权
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{passwordLoginView.message && (
|
||||
<div className={`text-sm font-medium ${passwordLoginView.status === 'failed' ? 'text-red-700' : passwordLoginView.status === 'success' ? 'text-green-700' : 'text-blue-800'}`}>
|
||||
{passwordLoginView.message}
|
||||
</div>
|
||||
)}
|
||||
{passwordLoginView.status === 'verification_required' && (
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900">
|
||||
<div className="font-extrabold">账号已触发平台风控,需要完成人脸识别</div>
|
||||
<div className="text-xs mt-1 leading-5">请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。</div>
|
||||
{passwordLoginView.qrCodeUrl && (
|
||||
<div className="mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white">
|
||||
<SquareQRCode src={passwordLoginView.qrCodeUrl} alt="密码登录风控二维码" className="p-2" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -918,7 +1155,7 @@ const AccountList: React.FC = () => {
|
||||
<div className="modal-footer">
|
||||
<div className="flex gap-3 w-full">
|
||||
<button
|
||||
onClick={() => setActiveModal(null)}
|
||||
onClick={() => void closeEditModal()}
|
||||
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
|
||||
disabled={saving}
|
||||
>
|
||||
@@ -952,7 +1189,7 @@ const AccountList: React.FC = () => {
|
||||
<p className="text-sm text-gray-500 mt-1">{editingAccount.nickname || editingAccount.remark || editingAccount.id}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setActiveModal(null)}
|
||||
onClick={closeAIModal}
|
||||
className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-500" />
|
||||
@@ -1055,7 +1292,7 @@ const AccountList: React.FC = () => {
|
||||
<div className="modal-footer">
|
||||
<div className="flex gap-3 w-full">
|
||||
<button
|
||||
onClick={() => setActiveModal(null)}
|
||||
onClick={closeAIModal}
|
||||
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
|
||||
disabled={saving}
|
||||
>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../types';
|
||||
import { getCards, createCard, updateCard, deleteCard, batchCreateCards, appendCardData } from '../services/api';
|
||||
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus } from 'lucide-react';
|
||||
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus, Search, SlidersHorizontal } from 'lucide-react';
|
||||
import { filterCards } from './cardListState';
|
||||
|
||||
type AddCardForm = {
|
||||
name: string;
|
||||
@@ -17,6 +18,14 @@ type AddCardForm = {
|
||||
api_params: string;
|
||||
};
|
||||
|
||||
type EditCardForm = Partial<Card> & {
|
||||
api_url?: string;
|
||||
api_method?: 'GET' | 'POST';
|
||||
api_timeout?: number;
|
||||
api_headers?: string;
|
||||
api_params?: string;
|
||||
};
|
||||
|
||||
const emptyAddForm = (): AddCardForm => ({
|
||||
name: '',
|
||||
type: 'data',
|
||||
@@ -35,7 +44,7 @@ const CardList: React.FC = () => {
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [showAddModal, setShowAddModal] = useState(false);
|
||||
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
|
||||
const [editForm, setEditForm] = useState<Partial<Card>>({});
|
||||
const [editForm, setEditForm] = useState<EditCardForm>({});
|
||||
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
|
||||
|
||||
// 批量导入
|
||||
@@ -47,6 +56,8 @@ const CardList: React.FC = () => {
|
||||
const [appendTargetId, setAppendTargetId] = useState<string>('');
|
||||
const [appendContent, setAppendContent] = useState('');
|
||||
const [appendResult, setAppendResult] = useState<{ added: number } | null>(null);
|
||||
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
|
||||
const [nameSearch, setNameSearch] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
getCards().then(setCards);
|
||||
@@ -112,7 +123,7 @@ const CardList: React.FC = () => {
|
||||
// 根据类型设置内容
|
||||
if (editForm.type === 'api') {
|
||||
updateData.api_config = {
|
||||
url: editForm.api_url?.trim(),
|
||||
url: editForm.api_url?.trim() || '',
|
||||
method: editForm.api_method as 'GET' | 'POST',
|
||||
timeout: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers?.trim() || undefined,
|
||||
@@ -205,6 +216,10 @@ const CardList: React.FC = () => {
|
||||
};
|
||||
|
||||
const dataCards = cards.filter(c => c.type === 'data');
|
||||
const filteredCards = useMemo(
|
||||
() => filterCards(cards, typeFilter, nameSearch),
|
||||
[cards, nameSearch, typeFilter],
|
||||
);
|
||||
|
||||
const downloadCardTemplate = () => {
|
||||
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
|
||||
@@ -298,28 +313,61 @@ const CardList: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
|
||||
<div className="flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
|
||||
<div className="relative sm:w-48">
|
||||
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<select
|
||||
aria-label="按卡密类型筛选"
|
||||
value={typeFilter}
|
||||
onChange={event => setTypeFilter(event.target.value as Card['type'] | '')}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">全部类型</option>
|
||||
<option value="data">批量卡密</option>
|
||||
<option value="text">文本</option>
|
||||
<option value="api">API</option>
|
||||
<option value="image">图片</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative w-full sm:max-w-sm">
|
||||
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="search"
|
||||
aria-label="按卡密名称搜索"
|
||||
placeholder="搜索卡密名称..."
|
||||
value={nameSearch}
|
||||
onChange={event => setNameSearch(event.target.value)}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="whitespace-nowrap px-1 text-xs font-bold text-gray-400">
|
||||
显示 {filteredCards.length} / {cards.length} 组
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<table className="w-full table-fixed text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
|
||||
<th className="px-8 py-5 w-[18%]">卡密名称</th>
|
||||
<th className="px-6 py-5 w-[12%]">卡密组ID</th>
|
||||
<th className="px-6 py-5 w-[10%]">类型</th>
|
||||
<th className="px-6 py-5 w-[22%]">内容/库存</th>
|
||||
<th className="px-6 py-5 w-[18%]">描述</th>
|
||||
<th className="px-6 py-5 w-[10%]">状态</th>
|
||||
<th className="px-6 py-5 w-[10%] text-right">操作</th>
|
||||
<th className="w-[23%] px-5 py-5">卡密名称</th>
|
||||
<th className="w-[8%] px-3 py-5">卡密组ID</th>
|
||||
<th className="w-[7%] px-2 py-5">类型</th>
|
||||
<th className="w-[27%] px-5 py-5">内容/库存</th>
|
||||
<th className="w-[19%] px-5 py-5">描述</th>
|
||||
<th className="w-[7%] px-2 py-5">状态</th>
|
||||
<th className="w-[9%] px-3 py-5 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50">
|
||||
{cards.map((card) => {
|
||||
{filteredCards.map((card) => {
|
||||
// 计算库存或内容预览
|
||||
let stockInfo = '';
|
||||
if (card.type === 'data' && card.data_content) {
|
||||
const lines = card.data_content.split('\n').filter(line => line.trim());
|
||||
stockInfo = `库存: ${lines.length} 条`;
|
||||
} else if (card.type === 'text' && card.text_content) {
|
||||
stockInfo = card.text_content.substring(0, 20) + (card.text_content.length > 20 ? '...' : '');
|
||||
stockInfo = card.text_content;
|
||||
} else if (card.type === 'api' && card.api_config) {
|
||||
stockInfo = card.api_config.url;
|
||||
} else if (card.type === 'image' && card.image_url) {
|
||||
@@ -328,26 +376,26 @@ const CardList: React.FC = () => {
|
||||
|
||||
return (
|
||||
<tr key={card.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
|
||||
<td className="px-8 py-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors">
|
||||
<td className="px-5 py-5 align-middle">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
|
||||
<CardIcon type={card.type} />
|
||||
</div>
|
||||
<span className="font-bold text-gray-900">{card.name}</span>
|
||||
<span className="line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900" title={card.name}>{card.name}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-3 py-5">
|
||||
<button
|
||||
onClick={() => copyCardID(card.id)}
|
||||
className="inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors"
|
||||
className="inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200"
|
||||
title="复制卡密组ID,用于批量铺货表格"
|
||||
>
|
||||
{card.id}
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
<span className="truncate">{card.id}</span>
|
||||
<Copy className="h-3 w-3 shrink-0" />
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className={`px-3 py-1.5 rounded-lg text-xs font-bold ${
|
||||
<td className="px-2 py-5">
|
||||
<span className={`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${
|
||||
card.type === 'text' ? 'bg-blue-50 text-blue-600' :
|
||||
card.type === 'data' ? 'bg-purple-50 text-purple-600' :
|
||||
card.type === 'api' ? 'bg-blue-50 text-blue-600' :
|
||||
@@ -358,20 +406,20 @@ const CardList: React.FC = () => {
|
||||
card.type === 'api' ? 'API' : '图片'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className="text-sm text-gray-600 font-mono block truncate" title={stockInfo}>
|
||||
<td className="px-5 py-5">
|
||||
<span className="line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600" title={stockInfo}>
|
||||
{stockInfo}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-5 py-5">
|
||||
<span
|
||||
className="text-sm text-gray-500 block max-w-[200px] truncate"
|
||||
className="block truncate text-sm text-gray-500"
|
||||
title={card.description || '-'}
|
||||
>
|
||||
{card.description || '-'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<td className="px-2 py-5">
|
||||
<button
|
||||
onClick={() => toggleCardStatus(card)}
|
||||
className={`w-12 h-8 rounded-full relative transition-colors ${
|
||||
@@ -383,20 +431,20 @@ const CardList: React.FC = () => {
|
||||
}`}></div>
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<td className="px-3 py-5">
|
||||
<div className="flex items-center justify-end gap-0.5">
|
||||
<button
|
||||
onClick={() => handleEdit(card)}
|
||||
className="p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors"
|
||||
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black"
|
||||
title="编辑"
|
||||
>
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(card.id)}
|
||||
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors"
|
||||
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
>
|
||||
<Trash2 className="w-5 h-5" />
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
@@ -407,10 +455,10 @@ const CardList: React.FC = () => {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{cards.length === 0 && (
|
||||
{filteredCards.length === 0 && (
|
||||
<div className="py-20 text-center text-gray-400">
|
||||
<Package className="w-12 h-12 mx-auto mb-4 opacity-30" />
|
||||
<p>暂无卡密配置,请点击右上角添加。</p>
|
||||
<p>{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -849,7 +897,7 @@ const CardList: React.FC = () => {
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5">
|
||||
上传表格,每行一个卡密组。表头:<code className="bg-blue-100/70 px-1.5 py-0.5 rounded">名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值</code>。
|
||||
类型填 text/data/image/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。
|
||||
类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
|
||||
import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
|
||||
import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
|
||||
|
||||
@@ -14,6 +15,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: 'bg-green-100 text-green-700',
|
||||
cancelled: 'bg-gray-100 text-gray-500',
|
||||
refunding: 'bg-red-100 text-red-600',
|
||||
unknown: 'bg-gray-100 text-gray-500',
|
||||
};
|
||||
|
||||
const labels = {
|
||||
@@ -23,6 +25,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: '已完成',
|
||||
cancelled: '已取消',
|
||||
refunding: '退款中',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -63,36 +66,50 @@ const Dashboard: React.FC = () => {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
// 参与统计的订单列表
|
||||
const [validOrders, setValidOrders] = useState<Order[]>([]);
|
||||
const [validOrdersTotal, setValidOrdersTotal] = useState(0);
|
||||
const [validOrdersTruncated, setValidOrdersTruncated] = useState(false);
|
||||
const [ordersLoading, setOrdersLoading] = useState(false);
|
||||
// 商品列表
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const rangeRequestSequence = useRef(0);
|
||||
|
||||
// 颜色配置
|
||||
const COLORS = ['#0094f7', '#3B82F6', '#10B981', '#F59E0B', '#8B5CF6'];
|
||||
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
|
||||
const loadValidOrders = (range: TimeRange) => {
|
||||
const { startDate, endDate } = getDateRange(range, new Date(), customStartDate, customEndDate);
|
||||
setOrdersLoading(true);
|
||||
getValidOrders({ start_date: startDate, end_date: endDate })
|
||||
.then(setValidOrders)
|
||||
.catch(error => setLoadError(error instanceof Error ? error.message : '订单加载失败'))
|
||||
.finally(() => setOrdersLoading(false));
|
||||
};
|
||||
|
||||
const loadAnalytics = (range: TimeRange) => {
|
||||
const currentRange = getDateRange(range, new Date(), customStartDate, customEndDate);
|
||||
const loadRange = async (range: TimeRange) => {
|
||||
let currentRange;
|
||||
try {
|
||||
currentRange = getDateRange(range, new Date(), customStartDate, customEndDate);
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : '日期范围无效');
|
||||
return;
|
||||
}
|
||||
const { startDate, endDate } = currentRange;
|
||||
const params = { start_date: startDate, end_date: endDate };
|
||||
|
||||
const previous = getPreviousDateRange(currentRange);
|
||||
getOrderAnalytics({ start_date: previous.startDate, end_date: previous.endDate })
|
||||
.then(setPreviousAnalytics)
|
||||
.catch(error => setLoadError(error instanceof Error ? error.message : '历史统计加载失败'));
|
||||
|
||||
getOrderAnalytics(params)
|
||||
.then(setAnalytics)
|
||||
.catch(error => setLoadError(error instanceof Error ? error.message : '统计加载失败'));
|
||||
const sequence = ++rangeRequestSequence.current;
|
||||
setOrdersLoading(true);
|
||||
setLoadError('');
|
||||
try {
|
||||
const [currentAnalytics, previousResult, orders] = await Promise.all([
|
||||
getOrderAnalytics(params),
|
||||
getOrderAnalytics({ start_date: previous.startDate, end_date: previous.endDate }),
|
||||
getValidOrders(params),
|
||||
]);
|
||||
if (sequence !== rangeRequestSequence.current) return;
|
||||
setAnalytics(currentAnalytics);
|
||||
setPreviousAnalytics(previousResult);
|
||||
setValidOrders(orders.orders);
|
||||
setValidOrdersTotal(orders.total);
|
||||
setValidOrdersTruncated(orders.truncated);
|
||||
} catch (error) {
|
||||
if (sequence === rangeRequestSequence.current) {
|
||||
setLoadError(error instanceof Error ? error.message : '经营数据加载失败');
|
||||
}
|
||||
} finally {
|
||||
if (sequence === rangeRequestSequence.current) setOrdersLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 计算趋势百分比
|
||||
@@ -112,26 +129,25 @@ const Dashboard: React.FC = () => {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getDashboardStats().then(setStats).catch(error => setLoadError(error instanceof Error ? error.message : '概览加载失败'));
|
||||
getItems().then(items => {
|
||||
setItems(items);
|
||||
let cancelled = false;
|
||||
Promise.all([getDashboardStats(), getItems()]).then(([dashboardStats, itemList]) => {
|
||||
if (cancelled) return;
|
||||
setStats(dashboardStats);
|
||||
setItems(itemList);
|
||||
// 建立 item_id 到 item_title 的映射
|
||||
const nameMap: Record<string, string> = {};
|
||||
items.forEach(item => {
|
||||
itemList.forEach(item => {
|
||||
nameMap[item.item_id] = item.item_title || item.item_id;
|
||||
});
|
||||
setItemNames(nameMap);
|
||||
}).catch(error => setLoadError(error instanceof Error ? error.message : '商品加载失败'));
|
||||
}).catch(error => {
|
||||
if (!cancelled) setLoadError(error instanceof Error ? error.message : '概览加载失败');
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setLoadError('');
|
||||
loadAnalytics(timeRange);
|
||||
}, [timeRange]);
|
||||
|
||||
// 加载订单列表
|
||||
useEffect(() => {
|
||||
loadValidOrders(timeRange);
|
||||
if (timeRange !== 'custom') void loadRange(timeRange);
|
||||
}, [timeRange]);
|
||||
|
||||
if (loadError && (!stats || !analytics)) {
|
||||
@@ -277,8 +293,7 @@ const Dashboard: React.FC = () => {
|
||||
onClick={() => {
|
||||
try {
|
||||
setLoadError('');
|
||||
loadAnalytics('custom');
|
||||
loadValidOrders('custom');
|
||||
void loadRange('custom');
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : '日期范围无效');
|
||||
}
|
||||
@@ -314,7 +329,7 @@ const Dashboard: React.FC = () => {
|
||||
/>
|
||||
<StatCard
|
||||
title="库存卡密余量"
|
||||
value={stats.total_cards}
|
||||
value={stats.available_card_stock}
|
||||
icon={Package}
|
||||
colorClass="bg-purple-500"
|
||||
/>
|
||||
@@ -498,7 +513,12 @@ const Dashboard: React.FC = () => {
|
||||
{/* 参与统计的订单列表 */}
|
||||
<div className="lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col">
|
||||
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]">
|
||||
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
|
||||
<div>
|
||||
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
|
||||
{validOrdersTruncated && (
|
||||
<p className="text-xs text-amber-700 mt-1">当前显示最近 {validOrders.length} / {validOrdersTotal} 条,搜索仅覆盖已加载明细。</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative">
|
||||
<input
|
||||
placeholder="搜索订单号/商品/买家..."
|
||||
@@ -569,7 +589,7 @@ const Dashboard: React.FC = () => {
|
||||
<td className="px-6 py-4">
|
||||
<div className="text-sm font-bold text-gray-800">{order.buyer_id}</div>
|
||||
{order.created_at && (
|
||||
<div className="text-xs text-gray-400 mt-1">{order.created_at}</div>
|
||||
<div className="text-xs text-gray-400 mt-1">{formatLocalDateTime(order.created_at)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
|
||||
@@ -628,7 +648,7 @@ const Dashboard: React.FC = () => {
|
||||
borderRadius: '6px',
|
||||
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
|
||||
}}
|
||||
formatter={(value: number) => `¥${value.toLocaleString()}`}
|
||||
formatter={(value) => `¥${Number(value || 0).toLocaleString()}`}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { selectActivePublishBatch } from './itemPublishBatchState';
|
||||
import { Item, AccountDetail, ShippingRule } from '../types';
|
||||
import {
|
||||
getItems,
|
||||
@@ -10,13 +11,15 @@ import {
|
||||
previewItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
deleteItemPublishBatch,
|
||||
cancelItemPublishBatch,
|
||||
retryFailedItemPublishBatch,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
getShippingRules
|
||||
} from '../services/api';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
|
||||
interface ItemListProps {
|
||||
onConfigureDelivery: (item: Item) => void;
|
||||
@@ -46,6 +49,7 @@ interface PublishBatchDetailRow {
|
||||
item_id: string;
|
||||
item_url: string;
|
||||
error_message: string;
|
||||
failure_kind: string;
|
||||
images?: string[];
|
||||
}
|
||||
|
||||
@@ -58,6 +62,7 @@ interface PublishBatchDetail {
|
||||
failed: number;
|
||||
pending: number;
|
||||
running: number;
|
||||
retryable: number;
|
||||
rows: PublishBatchDetailRow[];
|
||||
}
|
||||
|
||||
@@ -72,6 +77,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [selectedAccount, setSelectedAccount] = useState<string>('');
|
||||
const [accountFilter, setAccountFilter] = useState<string>('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
@@ -90,6 +96,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
rows: PublishBatchPreviewRow[];
|
||||
} | null>(null);
|
||||
const [batchDetail, setBatchDetail] = useState<PublishBatchDetail | null>(null);
|
||||
const [recentBatch, setRecentBatch] = useState<PublishBatchDetail | null>(null);
|
||||
const batchPollInFlight = useRef(false);
|
||||
const [selectedItem, setSelectedItem] = useState<Item | null>(null);
|
||||
const [editForm, setEditForm] = useState<Partial<Item>>({});
|
||||
const [addForm, setAddForm] = useState({
|
||||
@@ -137,31 +145,41 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([getAccountDetails(), getItems(), getShippingRules()])
|
||||
.then(([accountList, itemList, ruleList]) => {
|
||||
Promise.all([getAccountDetails(), getItems(), getShippingRules(), getItemPublishBatches(20)])
|
||||
.then(([accountList, itemList, ruleList, batches]) => {
|
||||
setAccounts(accountList);
|
||||
setItems(itemList);
|
||||
setShippingRules(ruleList);
|
||||
const recoverable = batches.find(batch => ['running', 'canceling'].includes(batch.status))
|
||||
|| batches.find(batch => batch.status !== 'preview');
|
||||
setRecentBatch(recoverable || null);
|
||||
})
|
||||
.catch((e) => console.error('加载商品配置失败:', e));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showBatchModal || !batchDetail?.id || batchDetail.status !== 'running') return;
|
||||
if (!showBatchModal || !batchDetail?.id || !['running', 'canceling'].includes(batchDetail.status)) return;
|
||||
const timer = window.setInterval(async () => {
|
||||
if (batchPollInFlight.current) return;
|
||||
batchPollInFlight.current = true;
|
||||
try {
|
||||
const detail = await getItemPublishBatch(batchDetail.id);
|
||||
setBatchDetail(detail);
|
||||
if (detail.status !== 'running') {
|
||||
setRecentBatch(detail);
|
||||
if (!['running', 'canceling'].includes(detail.status)) {
|
||||
setBatchPhase('done');
|
||||
await loadItems();
|
||||
await loadShippingRules();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('刷新批量铺货进度失败:', error);
|
||||
} finally {
|
||||
batchPollInFlight.current = false;
|
||||
}
|
||||
}, 3000);
|
||||
return () => window.clearInterval(timer);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [showBatchModal, batchDetail?.id, batchDetail?.status]);
|
||||
|
||||
const handleSync = async () => {
|
||||
@@ -295,13 +313,43 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const openBatchModal = () => {
|
||||
const openBatchModal = async () => {
|
||||
setBatchPhase('upload');
|
||||
setBatchPreview(null);
|
||||
setBatchDetail(null);
|
||||
setBatchFile(null);
|
||||
setBatchImagesZip(null);
|
||||
setShowBatchModal(true);
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
const batches = await getItemPublishBatches(20);
|
||||
const recoverable = selectActivePublishBatch(batches);
|
||||
if (recoverable?.id) {
|
||||
const detail = await getItemPublishBatch(recoverable.id);
|
||||
setRecentBatch(detail);
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('恢复最近批量铺货任务失败:', error);
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openRecentBatchResult = async () => {
|
||||
if (!recentBatch?.id) return;
|
||||
setBatchLoading(true);
|
||||
setShowBatchModal(true);
|
||||
try {
|
||||
const detail = await getItemPublishBatch(recentBatch.id);
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
} catch (error) {
|
||||
console.error('加载最近批量铺货结果失败:', error);
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePreviewBatch = async () => {
|
||||
@@ -333,6 +381,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const started = await startItemPublishBatch(batchPreview.preview_id);
|
||||
const detail = await getItemPublishBatch(started.batch_id || batchPreview.preview_id);
|
||||
setBatchDetail(detail);
|
||||
setRecentBatch(detail);
|
||||
setBatchPhase(detail.status === 'running' ? 'running' : 'done');
|
||||
} catch (error: any) {
|
||||
console.error('启动批量铺货失败:', error);
|
||||
@@ -347,9 +396,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
if (!confirm('确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。')) return;
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
await cancelItemPublishBatch(batchDetail.id);
|
||||
setBatchDetail(await getItemPublishBatch(batchDetail.id));
|
||||
setBatchPhase('done');
|
||||
const result = await cancelItemPublishBatch(batchDetail.id);
|
||||
const detail = await getItemPublishBatch(batchDetail.id);
|
||||
setBatchDetail(detail);
|
||||
setBatchPhase(result?.status === 'canceling' || detail.status === 'canceling' ? 'running' : 'done');
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '取消失败');
|
||||
} finally {
|
||||
@@ -357,6 +407,24 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const abandonBatchPreview = async () => {
|
||||
const previewId = batchPreview?.preview_id;
|
||||
if (previewId && batchPhase === 'preview') {
|
||||
try {
|
||||
await deleteItemPublishBatch(previewId);
|
||||
} catch (error) {
|
||||
console.error('清理批量铺货预检失败:', error);
|
||||
}
|
||||
}
|
||||
setBatchPreview(null);
|
||||
setBatchPhase('upload');
|
||||
};
|
||||
|
||||
const closeBatchModal = async () => {
|
||||
await abandonBatchPreview();
|
||||
setShowBatchModal(false);
|
||||
};
|
||||
|
||||
const handleRetryBatchFailed = async () => {
|
||||
if (!batchDetail?.id) return;
|
||||
setBatchLoading(true);
|
||||
@@ -407,13 +475,16 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
|
||||
const rulesForItem = (item: Item) => shippingRules.filter(rule =>
|
||||
rule.cookie_id === item.cookie_id && rule.item_id === item.item_id
|
||||
);
|
||||
).length > 0
|
||||
? shippingRules.filter(rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id)
|
||||
: shippingRules.filter(rule => rule.cookie_id === item.cookie_id && !rule.item_id);
|
||||
|
||||
const batchStatusText = (status?: string) => {
|
||||
switch (status) {
|
||||
case 'preview': return '待确认';
|
||||
case 'pending': return '等待中';
|
||||
case 'running': return '发布中';
|
||||
case 'canceling': return '正在安全取消';
|
||||
case 'success': return '成功';
|
||||
case 'failed': return '失败';
|
||||
case 'completed': return '已完成';
|
||||
@@ -440,24 +511,72 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const accountMap = useMemo(
|
||||
() => new Map(accounts.map(account => [account.id, account])),
|
||||
[accounts],
|
||||
);
|
||||
const visibleItems = useMemo(
|
||||
() => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items,
|
||||
[accountFilter, items],
|
||||
);
|
||||
const accountName = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
};
|
||||
const accountNickname = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">商品管理</h2>
|
||||
<p className="text-gray-500 mt-2 text-sm">监控并管理所有账号下的闲鱼商品。</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<select
|
||||
className="ios-input px-4 py-3 rounded-xl text-sm"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">选择账号以同步</option>
|
||||
{accounts.map(acc => (
|
||||
<option key={acc.id} value={acc.id}>{acc.nickname}</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="flex min-w-[200px] flex-col gap-1.5">
|
||||
<label htmlFor="item-account-filter" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
|
||||
商品列表筛选
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Filter className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
id="item-account-filter"
|
||||
aria-label="按账号筛选商品列表"
|
||||
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
|
||||
value={accountFilter}
|
||||
onChange={event => setAccountFilter(event.target.value)}
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-[200px] flex-col gap-1.5">
|
||||
<label htmlFor="item-sync-account" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
|
||||
同步商品账号
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
id="item-sync-account"
|
||||
aria-label="选择要同步商品的账号"
|
||||
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
|
||||
value={selectedAccount}
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">请选择账号</option>
|
||||
{accounts.map(acc => (
|
||||
<option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSync}
|
||||
disabled={loading || !selectedAccount}
|
||||
@@ -481,17 +600,25 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
发布商品
|
||||
</button>
|
||||
<button
|
||||
onClick={openBatchModal}
|
||||
onClick={() => void openBatchModal()}
|
||||
className="px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100"
|
||||
>
|
||||
<UploadCloud className="w-4 h-4" />
|
||||
批量铺货
|
||||
{recentBatch && ['running', 'canceling'].includes(recentBatch.status) ? '继续批量任务' : '批量铺货'}
|
||||
</button>
|
||||
{recentBatch && !['running', 'canceling'].includes(recentBatch.status) && (
|
||||
<button
|
||||
onClick={() => void openRecentBatchResult()}
|
||||
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
最近批次结果
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{items.map(item => {
|
||||
{visibleItems.map(item => {
|
||||
const linkedRules = rulesForItem(item);
|
||||
const hasRule = linkedRules.length > 0;
|
||||
return (
|
||||
@@ -525,6 +652,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4">{item.item_title}</h3>
|
||||
<div className="mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(item.cookie_id)}>
|
||||
<User className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(item.cookie_id)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center text-[10px] text-gray-500 mb-2">
|
||||
<span className="bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]">ID: {item.item_id}</span>
|
||||
<span className={`inline-flex items-center gap-1 font-bold ${hasRule ? 'text-emerald-600' : 'text-amber-600'}`}>
|
||||
@@ -544,10 +675,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{items.length === 0 && (
|
||||
{visibleItems.length === 0 && (
|
||||
<div className="col-span-full py-20 text-center text-gray-400">
|
||||
<ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-30" />
|
||||
暂无商品数据,请选择账号进行同步
|
||||
{accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -597,7 +728,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<label className="block text-sm font-bold text-gray-700">所属账号</label>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={e => setAddForm({...addForm, cookie_id: e.target.value})}>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
@@ -649,7 +780,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<label className="block text-sm font-bold text-gray-700">发布账号</label>
|
||||
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => setPublishForm({...publishForm, cookie_id: e.target.value})}>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
@@ -734,7 +865,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<h3 className="text-xl font-extrabold text-gray-900">批量铺货</h3>
|
||||
<p className="text-xs text-gray-500 mt-1">上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。</p>
|
||||
</div>
|
||||
<button onClick={() => setShowBatchModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
|
||||
<button onClick={() => void closeBatchModal()} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
|
||||
<X className="w-5 h-5 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -779,7 +910,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
onChange={e => setSelectedAccount(e.target.value)}
|
||||
>
|
||||
<option value="">选择账号</option>
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
|
||||
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
|
||||
</select>
|
||||
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
|
||||
</div>
|
||||
@@ -846,7 +977,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-50 text-gray-700">
|
||||
{[
|
||||
['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'],
|
||||
['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'],
|
||||
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
|
||||
['描述', '可以留空', '留空时会使用商品标题作为描述'],
|
||||
['价格', '每个商品都要填', '只填数字,例如 19.90'],
|
||||
@@ -855,14 +986,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'],
|
||||
['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'],
|
||||
['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'],
|
||||
['付款后自动发货', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['付款后发送的卡密', '“付款后自动发货”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
|
||||
['评价后发送赠品', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['评价后发送的卡密', '“评价后发送赠品”填“是”时填写', '格式和付款后发送的卡密相同,也可以同时发送多个卡密组'],
|
||||
['超时未评价时提醒', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['发货几小时后提醒', '“超时未评价时提醒”填“是”时填写', '填写等待小时数;留空按 72 小时处理'],
|
||||
['提醒内容', '“超时未评价时提醒”填“是”时填写', '填写要发送给买家的求评价消息'],
|
||||
['最多提醒几次', '可以留空', '留空只提醒 1 次'],
|
||||
['付款发货启用', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['付款发货内容', '“付款发货启用”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
|
||||
['评价赠品启用', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['评价赠品内容', '“评价赠品启用”填“是”时填写', '格式和付款发货内容相同,也可以同时发送多个卡密组'],
|
||||
['求评价启用', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['求评价等待小时', '“求评价启用”填“是”时填写', '填写等待小时数;留空按 72 小时处理'],
|
||||
['求评价文案', '“求评价启用”填“是”时填写', '填写要发送给买家的求评价消息'],
|
||||
['求评价最多次数', '可以留空', '留空只提醒 1 次'],
|
||||
].map(([name, when, desc]) => (
|
||||
<tr key={name}>
|
||||
<td className="px-3 py-2 font-bold text-gray-900 whitespace-nowrap">{name}</td>
|
||||
@@ -995,7 +1126,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
)}
|
||||
{batchPhase === 'preview' && batchPreview && (
|
||||
<div className="flex gap-3 w-full">
|
||||
<button disabled={batchLoading} onClick={() => setBatchPhase('upload')} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
|
||||
<button disabled={batchLoading} onClick={() => void abandonBatchPreview()} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
|
||||
返回修改
|
||||
</button>
|
||||
<button disabled={batchLoading || batchPreview.valid <= 0} onClick={handleStartBatch} className="flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
|
||||
@@ -1010,18 +1141,22 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<button disabled={batchLoading} onClick={handleCancelBatch} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
|
||||
取消任务
|
||||
</button>
|
||||
) : batchDetail.status === 'canceling' ? (
|
||||
<button disabled className="flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold">
|
||||
正在保存远端结果并安全取消…
|
||||
</button>
|
||||
) : (
|
||||
<button onClick={() => window.open(`/items/publish-batches/${batchDetail.id}/result.csv`, '_blank')} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
|
||||
下载结果
|
||||
</button>
|
||||
)}
|
||||
{batchDetail.failed > 0 && batchDetail.status !== 'running' && (
|
||||
{batchDetail.retryable > 0 && !['running', 'canceling'].includes(batchDetail.status) && (
|
||||
<button disabled={batchLoading} onClick={handleRetryBatchFailed} className="flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
|
||||
<RefreshCw className={`w-4 h-4 ${batchLoading ? 'animate-spin' : ''}`} />
|
||||
重试失败项
|
||||
</button>
|
||||
)}
|
||||
{batchDetail.status !== 'running' && (
|
||||
{!['running', 'canceling'].includes(batchDetail.status) && (
|
||||
<button onClick={() => { setShowBatchModal(false); loadItems(); loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
|
||||
完成
|
||||
</button>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
|
||||
} from 'lucide-react';
|
||||
import { normalizeSMTPSettings } from '../smtpSettings';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig';
|
||||
|
||||
type ChannelTypeMeta = {
|
||||
label: string;
|
||||
@@ -139,18 +140,14 @@ const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
|
||||
icon: Mail,
|
||||
fields: [
|
||||
{ key: 'to_email', label: '收件邮箱', placeholder: 'receiver@example.com', required: true },
|
||||
{ key: 'smtp_server', label: '覆盖 SMTP 服务器', placeholder: 'smtp.qq.com', help: '留空时使用上方系统级 SMTP 配置' },
|
||||
{ key: 'smtp_port', label: '覆盖 SMTP 端口', placeholder: '587', type: 'number', help: '留空时使用系统级 SMTP 端口' },
|
||||
{ key: 'smtp_user', label: '覆盖发件邮箱', placeholder: 'you@qq.com', help: '留空时使用系统级发件邮箱' },
|
||||
{ key: 'smtp_password', label: '覆盖密码 / 授权码', type: 'password', help: '留空时使用系统级授权码' },
|
||||
],
|
||||
guide: {
|
||||
steps: [
|
||||
'先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码',
|
||||
'邮件渠道只需要填写收件邮箱',
|
||||
'如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段',
|
||||
'通常先保存页面中的系统 SMTP 配置',
|
||||
'邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP',
|
||||
'只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置',
|
||||
],
|
||||
note: '收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。',
|
||||
note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -188,6 +185,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
const [smtp, setSmtp] = useState<SystemSettings>({});
|
||||
const [smtpSaving, setSmtpSaving] = useState(false);
|
||||
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
|
||||
const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
name: '',
|
||||
@@ -228,6 +226,8 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
smtp_password: smtp.smtp_password || '',
|
||||
smtp_from_name: smtp.smtp_from_name || '',
|
||||
smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '',
|
||||
smtp_use_tls: smtp.smtp_use_tls !== false,
|
||||
smtp_use_ssl: smtp.smtp_use_ssl === true,
|
||||
});
|
||||
showToast('success', 'SMTP 配置已保存');
|
||||
} catch (e: any) {
|
||||
@@ -254,18 +254,28 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
|
||||
setShowChannelSmtpPassword(false);
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const openEdit = (ch: NotificationChannel) => {
|
||||
setEditing(ch);
|
||||
const normalizedEmailConfig = ch.type === 'email'
|
||||
? normalizeEmailChannelConfig({ ...(ch.config || {}) })
|
||||
: null;
|
||||
const config = normalizedEmailConfig
|
||||
? (normalizedEmailConfig.use_custom_smtp === true
|
||||
? enableCustomSMTP(normalizedEmailConfig, smtp)
|
||||
: normalizedEmailConfig)
|
||||
: { ...(ch.config || {}) };
|
||||
setForm({
|
||||
name: ch.name,
|
||||
type: ch.type,
|
||||
enabled: ch.enabled,
|
||||
config: { ...(ch.config || {}) },
|
||||
config,
|
||||
event_types: ch.event_types || [],
|
||||
});
|
||||
setShowChannelSmtpPassword(false);
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
@@ -281,9 +291,27 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
showToast('error', '请填写渠道名称');
|
||||
return;
|
||||
}
|
||||
let config = form.config;
|
||||
if (form.type === 'email') {
|
||||
config = buildEmailChannelConfig(form.config);
|
||||
if (config.use_custom_smtp) {
|
||||
const required = [
|
||||
['smtp_server', '独立 SMTP 服务器'],
|
||||
['smtp_port', '独立 SMTP 端口'],
|
||||
['smtp_user', '独立 SMTP 登录邮箱'],
|
||||
['smtp_password', '独立 SMTP 密码 / 授权码'],
|
||||
['smtp_from_address', '独立 SMTP 发件地址'],
|
||||
] as const;
|
||||
const missing = required.find(([key]) => !String(config[key] || '').trim());
|
||||
if (missing) {
|
||||
showToast('error', `请填写 ${missing[1]}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = { name: form.name.trim(), type: form.type, config: form.config, event_types: form.event_types, enabled: form.enabled };
|
||||
const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled };
|
||||
if (editing) {
|
||||
await updateNotificationChannel(editing.id, payload);
|
||||
} else {
|
||||
@@ -344,8 +372,9 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">通知设置</h2>
|
||||
<p className="text-gray-500 mt-2 font-medium">配置通知渠道,账号异常时主动推送告警</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={load}
|
||||
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"
|
||||
>
|
||||
@@ -540,9 +569,28 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={smtp.smtp_use_tls !== false}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : smtp.smtp_use_ssl })}
|
||||
/>
|
||||
STARTTLS(常用于 587 端口)
|
||||
</label>
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={smtp.smtp_use_ssl === true}
|
||||
onChange={e => setSmtp({ ...smtp, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : smtp.smtp_use_tls })}
|
||||
/>
|
||||
SSL/TLS 直连(常用于 465 端口)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSaveSmtp}
|
||||
disabled={smtpSaving}
|
||||
className="ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50"
|
||||
@@ -642,6 +690,137 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{form.type === 'email' && (
|
||||
<div className="overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40">
|
||||
<div className="flex items-center justify-between gap-4 p-4">
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-gray-900">SMTP 来源</div>
|
||||
<p className="mt-1 text-xs leading-5 text-gray-500">
|
||||
{form.config.use_custom_smtp === true
|
||||
? '当前渠道使用一套完整、独立的发件配置。'
|
||||
: '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const useCustom = form.config.use_custom_smtp === true;
|
||||
setForm({
|
||||
...form,
|
||||
config: useCustom
|
||||
? { ...form.config, use_custom_smtp: false }
|
||||
: enableCustomSMTP(form.config, smtp),
|
||||
});
|
||||
}}
|
||||
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
|
||||
aria-label="使用独立 SMTP"
|
||||
>
|
||||
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{form.config.use_custom_smtp === true && (
|
||||
<div className="space-y-4 border-t border-blue-100 bg-white/80 p-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 服务器 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="text"
|
||||
value={String(form.config.smtp_server || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })}
|
||||
placeholder="smtp.qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">SMTP 端口 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="number"
|
||||
value={String(form.config.smtp_port || 587)}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })}
|
||||
placeholder="587"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">登录邮箱 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="email"
|
||||
value={String(form.config.smtp_user || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">密码 / 授权码 <span className="text-red-500">*</span></label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showChannelSmtpPassword ? 'text' : 'password'}
|
||||
value={String(form.config.smtp_password || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })}
|
||||
placeholder="输入密码或授权码"
|
||||
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowChannelSmtpPassword(value => !value)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
{showChannelSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={String(form.config.smtp_from_name || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })}
|
||||
placeholder="闲鱼自动回复系统"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">发件邮箱地址 <span className="text-red-500">*</span></label>
|
||||
<input
|
||||
type="email"
|
||||
value={String(form.config.smtp_from_address || '')}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })}
|
||||
placeholder="your-email@qq.com"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.config.smtp_use_tls !== false}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : form.config.smtp_use_ssl } })}
|
||||
/>
|
||||
STARTTLS(常用于 587)
|
||||
</label>
|
||||
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.config.smtp_use_ssl === true}
|
||||
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : form.config.smtp_use_tls } })}
|
||||
/>
|
||||
SSL/TLS 直连(常用于 465)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-800">通知内容</label>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Order, OrderStatus, Item } from '../types';
|
||||
import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems } from '../services/api';
|
||||
import { AccountDetail, Order, OrderStatus, Item } from '../types';
|
||||
import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems, getAccountDetails } from '../services/api';
|
||||
import { Search, MoreHorizontal, Truck, RefreshCw, Copy, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, Phone, MapPin, Upload, ExternalLink, Trash2 } from 'lucide-react';
|
||||
import { failedOrderImportRows, normalizeOrderImportResult, OrderImportResult } from './orderImportState';
|
||||
import { formatLocalDateTime } from '../dateTime';
|
||||
|
||||
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
const styles = {
|
||||
@@ -12,6 +14,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: 'bg-green-100 text-green-700',
|
||||
cancelled: 'bg-gray-100 text-gray-500',
|
||||
refunding: 'bg-red-100 text-red-600',
|
||||
unknown: 'bg-gray-100 text-gray-500',
|
||||
};
|
||||
|
||||
const labels = {
|
||||
@@ -21,6 +24,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: '已完成',
|
||||
cancelled: '已取消',
|
||||
refunding: '退款中',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -32,11 +36,14 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
|
||||
const OrderList: React.FC = () => {
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [allOrders, setAllOrders] = useState<Order[]>([]); // 保存所有订单用于搜索
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [accountFilter, setAccountFilter] = useState('');
|
||||
const [searchText, setSearchText] = useState(''); // 搜索文本
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const requestSequence = useRef(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -51,76 +58,37 @@ const OrderList: React.FC = () => {
|
||||
const [shipLoading, setShipLoading] = useState(false);
|
||||
const [shipResult, setShipResult] = useState<{success: boolean; message: string} | null>(null);
|
||||
const [importFile, setImportFile] = useState<File | null>(null);
|
||||
const [importResult, setImportResult] = useState<OrderImportResult | null>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [syncingOrderId, setSyncingOrderId] = useState<string | null>(null);
|
||||
const [deletingOrderId, setDeletingOrderId] = useState<string | null>(null);
|
||||
|
||||
// 搜索过滤订单
|
||||
const filterOrders = (ordersToFilter: Order[]): Order[] => {
|
||||
if (!searchText.trim()) {
|
||||
return ordersToFilter;
|
||||
}
|
||||
|
||||
const searchLower = searchText.toLowerCase().trim();
|
||||
return ordersToFilter.filter(order =>
|
||||
order.order_id?.toLowerCase().includes(searchLower) ||
|
||||
order.item_id?.toLowerCase().includes(searchLower) ||
|
||||
order.buyer_id?.toLowerCase().includes(searchLower) ||
|
||||
order.item_title?.toLowerCase().includes(searchLower) ||
|
||||
order.receiver_name?.toLowerCase().includes(searchLower) ||
|
||||
order.receiver_phone?.toLowerCase().includes(searchLower)
|
||||
);
|
||||
};
|
||||
|
||||
const loadOrders = async () => {
|
||||
const sequence = ++requestSequence.current;
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
// 如果有搜索文本,加载所有页的数据;否则只加载当前页
|
||||
if (searchText.trim()) {
|
||||
// 搜索模式:循环加载所有页
|
||||
let allOrdersData: Order[] = [];
|
||||
let currentPage = 1;
|
||||
let hasMore = true;
|
||||
|
||||
while (hasMore) {
|
||||
const res = await getOrders(undefined, filter, currentPage, 100);
|
||||
allOrdersData = [...allOrdersData, ...res.data];
|
||||
hasMore = currentPage < res.total_pages;
|
||||
currentPage++;
|
||||
}
|
||||
|
||||
setAllOrders(allOrdersData);
|
||||
setOrders(filterOrders(allOrdersData));
|
||||
setTotalPages(1); // 搜索时不分页
|
||||
} else {
|
||||
// 普通模式:只加载当前页
|
||||
const res = await getOrders(undefined, filter, page, 20);
|
||||
setAllOrders(res.data);
|
||||
setOrders(filterOrders(res.data));
|
||||
setTotalPages(res.total_pages);
|
||||
}
|
||||
const res = await getOrders(accountFilter || undefined, filter, page, 20, debouncedSearch);
|
||||
if (sequence !== requestSequence.current) return;
|
||||
setOrders(res.data);
|
||||
setTotalPages(res.total_pages);
|
||||
} catch (e) {
|
||||
console.error('加载订单失败:', e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (sequence === requestSequence.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 当订单数据改变时,重新过滤订单
|
||||
useEffect(() => {
|
||||
setOrders(filterOrders(allOrders));
|
||||
}, [allOrders, searchText]);
|
||||
|
||||
// 从订单的 item_id 查找对应的商品名称(通过标题匹配)
|
||||
const getItemNameById = (orderId: string, orderItemTitle?: string): string => {
|
||||
const getItemNameById = (cookieId: string, orderId: string, orderItemTitle?: string): string => {
|
||||
// 如果订单有 item_title,优先使用
|
||||
if (orderItemTitle && orderItemTitle.trim()) {
|
||||
return orderItemTitle;
|
||||
}
|
||||
|
||||
// 尝试通过 item_id 直接匹配
|
||||
if (itemNames[orderId]) {
|
||||
return itemNames[orderId];
|
||||
if (itemNames[`${cookieId}:${orderId}`]) {
|
||||
return itemNames[`${cookieId}:${orderId}`];
|
||||
}
|
||||
|
||||
// 尝试在商品列表中查找相似标题的商品
|
||||
@@ -148,7 +116,7 @@ const OrderList: React.FC = () => {
|
||||
items.forEach(item => {
|
||||
// 使用 item_id 作为键,商品标题作为值
|
||||
if (item.item_id) {
|
||||
namesMap[item.item_id] = item.item_title || item.item_id;
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
@@ -158,27 +126,53 @@ const OrderList: React.FC = () => {
|
||||
const namesMap: Record<string, string> = {};
|
||||
itemsList.forEach(item => {
|
||||
if (item.item_id) {
|
||||
namesMap[item.item_id] = item.item_title || item.item_id;
|
||||
namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
|
||||
}
|
||||
});
|
||||
setItemNames(namesMap);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setPage(1);
|
||||
setDebouncedSearch(searchText.trim());
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
loadOrders();
|
||||
// 加载商品列表
|
||||
getItems().then((itemsList) => {
|
||||
}, [accountFilter, filter, page, debouncedSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([getAccountDetails(), getItems()]).then(([accountList, itemsList]) => {
|
||||
setAccounts(accountList);
|
||||
setItems(itemsList);
|
||||
buildItemNamesMapFrom(itemsList);
|
||||
}).catch((e) => {
|
||||
console.error('加载商品列表失败:', e);
|
||||
});
|
||||
}, [filter, page, searchText]);
|
||||
}, []);
|
||||
|
||||
const accountMap = useMemo(
|
||||
() => new Map(accounts.map(account => [account.id, account])),
|
||||
[accounts],
|
||||
);
|
||||
|
||||
const accountName = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
const name = account?.remark || account?.nickname;
|
||||
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
|
||||
};
|
||||
const accountNickname = (cookieId: string) => {
|
||||
const account = accountMap.get(cookieId);
|
||||
return account?.remark || account?.nickname || '未命名账号';
|
||||
};
|
||||
|
||||
const handleSync = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await syncOrders();
|
||||
const result = await syncOrders(accountFilter || undefined, filter);
|
||||
await loadOrders();
|
||||
if (result?.message) {
|
||||
alert(result.message);
|
||||
@@ -256,6 +250,9 @@ const OrderList: React.FC = () => {
|
||||
if (editingOrder.quantity !== undefined) {
|
||||
updateData.quantity = editingOrder.quantity;
|
||||
}
|
||||
if (editingOrder.item_title !== undefined) {
|
||||
updateData.item_title = editingOrder.item_title;
|
||||
}
|
||||
|
||||
await updateOrder(editingOrder.order_id, updateData);
|
||||
setShowEditModal(false);
|
||||
@@ -268,18 +265,32 @@ const OrderList: React.FC = () => {
|
||||
};
|
||||
|
||||
const handleImportOrders = async () => {
|
||||
if (!importFile) return;
|
||||
try {
|
||||
if (!importFile) return;
|
||||
setImporting(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', importFile);
|
||||
await importOrders(formData);
|
||||
setShowImportModal(false);
|
||||
setImportFile(null);
|
||||
loadOrders();
|
||||
alert('订单导入成功');
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '导入失败,请检查文件格式');
|
||||
}
|
||||
const result = normalizeOrderImportResult(await importOrders(formData));
|
||||
setImportResult(result);
|
||||
setImportFile(null);
|
||||
await loadOrders();
|
||||
if (result.failed_count === 0) {
|
||||
setShowImportModal(false);
|
||||
setImportResult(null);
|
||||
alert(`订单导入成功,共 ${result.success_count} 条`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '导入失败,请检查文件格式');
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const closeImportModal = () => {
|
||||
if (importing) return;
|
||||
setShowImportModal(false);
|
||||
setImportFile(null);
|
||||
setImportResult(null);
|
||||
};
|
||||
|
||||
const handleSyncSingle = async (orderId: string) => {
|
||||
@@ -304,7 +315,11 @@ const OrderList: React.FC = () => {
|
||||
setDeletingOrderId(orderId);
|
||||
try {
|
||||
await deleteOrder(orderId);
|
||||
setAllOrders(prev => prev.filter(o => o.order_id !== orderId));
|
||||
if (orders.length === 1 && page > 1) {
|
||||
setPage(current => current - 1);
|
||||
} else {
|
||||
await loadOrders();
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('删除订单失败:', error);
|
||||
alert(error?.message || '删除失败,请重试');
|
||||
@@ -326,7 +341,7 @@ const OrderList: React.FC = () => {
|
||||
<RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowImportModal(true)}
|
||||
onClick={() => { setImportResult(null); setShowImportModal(true); }}
|
||||
className="px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
@@ -345,10 +360,12 @@ const OrderList: React.FC = () => {
|
||||
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
|
||||
{[
|
||||
{k:'all', v:'全部'},
|
||||
{k:'processing', v:'处理中'},
|
||||
{k:'shipped', v:'已发货'},
|
||||
{k:'pending_ship', v:'待发货'},
|
||||
{k:'completed', v:'已完成'},
|
||||
{k:'cancelled', v:'已取消'},
|
||||
{k:'refunding', v:'其他'}
|
||||
{k:'refunding', v:'退款中'}
|
||||
].map(opt => (
|
||||
<button
|
||||
key={opt.k}
|
||||
@@ -359,7 +376,22 @@ const OrderList: React.FC = () => {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="relative w-full md:w-auto group">
|
||||
<div className="flex w-full md:w-auto flex-col sm:flex-row gap-3">
|
||||
<div className="relative">
|
||||
<UserIcon className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<select
|
||||
aria-label="按账号筛选订单"
|
||||
value={accountFilter}
|
||||
onChange={(event) => { setAccountFilter(event.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors" />
|
||||
<input
|
||||
type="text"
|
||||
@@ -368,6 +400,7 @@ const OrderList: React.FC = () => {
|
||||
onChange={(e) => { setSearchText(e.target.value); setPage(1); }}
|
||||
className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -397,10 +430,14 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-bold text-gray-900 line-clamp-1 text-sm">
|
||||
{getItemNameById(order.item_id, order.item_title)}
|
||||
{getItemNameById(order.cookie_id, order.item_id, order.item_title)}
|
||||
</div>
|
||||
<div className="mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700" title={accountNickname(order.cookie_id)}>
|
||||
<UserIcon className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(order.cookie_id)}</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-1 font-medium">订单ID: {order.order_id}</div>
|
||||
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {order.created_at}</div>
|
||||
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {formatLocalDateTime(order.created_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
@@ -538,6 +575,10 @@ const OrderList: React.FC = () => {
|
||||
<div className="text-xs text-gray-500 mb-1">订单号</div>
|
||||
<div className="font-mono text-sm font-bold text-gray-900">{selectedOrder.order_id}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500 mb-1">所属账号</div>
|
||||
<div className="truncate whitespace-nowrap text-sm font-bold text-blue-700" title={accountNickname(selectedOrder.cookie_id)}>{accountNickname(selectedOrder.cookie_id)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500 mb-1">状态</div>
|
||||
<StatusBadge status={selectedOrder.status} />
|
||||
@@ -552,7 +593,7 @@ const OrderList: React.FC = () => {
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<div className="text-xs text-gray-500 mb-1">创建时间</div>
|
||||
<div className="text-sm font-medium text-gray-700">{selectedOrder.created_at}</div>
|
||||
<div className="text-sm font-medium text-gray-700">{formatLocalDateTime(selectedOrder.created_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -566,7 +607,7 @@ const OrderList: React.FC = () => {
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<div className="font-bold text-gray-900 mb-1">
|
||||
{getItemNameById(selectedOrder.item_id, selectedOrder.item_title)}
|
||||
{getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">商品ID: {selectedOrder.item_id}</div>
|
||||
{selectedOrder.item_price && (
|
||||
@@ -640,7 +681,7 @@ const OrderList: React.FC = () => {
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<h3 className="text-2xl font-extrabold text-gray-900">插入订单</h3>
|
||||
<button
|
||||
onClick={() => setShowImportModal(false)}
|
||||
onClick={closeImportModal}
|
||||
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
@@ -660,30 +701,54 @@ const OrderList: React.FC = () => {
|
||||
<p className="text-xs text-gray-500 mt-2">支持 .xlsx、.csv、.tsv、.json 格式</p>
|
||||
</div>
|
||||
|
||||
{importFile && (
|
||||
{importFile && (
|
||||
<div className="p-3 bg-blue-50 rounded-xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="w-4 h-4 text-blue-600" />
|
||||
<span className="text-sm font-medium text-blue-900">{importFile.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{importResult && importResult.failed_count > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800">
|
||||
导入完成:成功 {importResult.success_count} 条,失败 {importResult.failed_count} 条
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto rounded-xl border border-gray-100">
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead className="sticky top-0 bg-gray-50 text-gray-500">
|
||||
<tr><th className="px-3 py-2">订单ID</th><th className="px-3 py-2">失败原因</th></tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{failedOrderImportRows(importResult).map((row, index) => (
|
||||
<tr key={`${row.order_id}-${index}`}>
|
||||
<td className="px-3 py-2 font-mono">{row.order_id}</td>
|
||||
<td className="px-3 py-2 text-red-600">{row.message || '导入失败'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
<div className="flex gap-3 w-full">
|
||||
<button
|
||||
onClick={() => setShowImportModal(false)}
|
||||
onClick={closeImportModal}
|
||||
disabled={importing}
|
||||
className="flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleImportOrders}
|
||||
disabled={!importFile}
|
||||
disabled={!importFile || importing}
|
||||
className="flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50"
|
||||
>
|
||||
导入订单
|
||||
{importing ? '正在导入…' : '导入订单'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -839,7 +904,7 @@ const OrderList: React.FC = () => {
|
||||
<input
|
||||
type="number"
|
||||
value={editingOrder.amount}
|
||||
onChange={(e) => setEditingOrder({ ...editingOrder, amount: parseFloat(e.target.value) })}
|
||||
onChange={(e) => setEditingOrder({ ...editingOrder, amount: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
|
||||
test('risk verification panel explains automatic refresh without manual controls', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<RiskVerificationPanel faceQrUrl="data:image/png;base64,abc" />,
|
||||
);
|
||||
expect(html).toContain('需要完成安全风控验证');
|
||||
expect(html).toContain('系统会自动检测并刷新登录状态');
|
||||
expect(html).toContain('max-h-[min(64vh,28rem)]');
|
||||
expect(html).not.toContain('<button');
|
||||
expect(html).not.toContain('我已');
|
||||
expect(html).not.toContain('重试');
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import { AlertTriangle, Loader2 } from 'lucide-react';
|
||||
|
||||
interface RiskVerificationPanelProps {
|
||||
faceQrUrl?: string;
|
||||
verificationScreenshot?: string;
|
||||
}
|
||||
|
||||
export const RiskVerificationPanel: React.FC<RiskVerificationPanelProps> = ({
|
||||
faceQrUrl,
|
||||
verificationScreenshot,
|
||||
}) => (
|
||||
<div className="w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center">
|
||||
<div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700">
|
||||
<AlertTriangle className="h-5 w-5" aria-hidden="true" />
|
||||
</div>
|
||||
<h4 className="break-words text-base font-extrabold leading-6 text-amber-900">
|
||||
需要完成安全风控验证
|
||||
</h4>
|
||||
<p className="mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800">
|
||||
当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。
|
||||
</p>
|
||||
|
||||
<div className="mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm">
|
||||
{faceQrUrl ? (
|
||||
<img src={faceQrUrl} alt="闲鱼安全风控验证二维码" className="block max-h-44 w-full object-contain" />
|
||||
) : verificationScreenshot ? (
|
||||
<img src={verificationScreenshot} alt="闲鱼风控验证页面" className="block max-h-44 w-full object-contain" />
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-2 text-amber-700">
|
||||
<Loader2 className="h-6 w-6 animate-spin" aria-hidden="true" />
|
||||
<span className="text-xs font-bold">正在准备风控二维码…</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500">
|
||||
请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
+187
-23
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import {
|
||||
AccountDetail,
|
||||
@@ -21,11 +21,16 @@ import {
|
||||
getDefaultReplies,
|
||||
getDefaultReply,
|
||||
getItems,
|
||||
getAutomationIssues,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
updateDefaultReply,
|
||||
updateReplyRule,
|
||||
updateShippingRule,
|
||||
resolveAutomationRun,
|
||||
resolveDeferredAutomationTask,
|
||||
AutomationRunIssue,
|
||||
DeferredAutomationIssue,
|
||||
} from '../services/api';
|
||||
import {
|
||||
AlertCircle,
|
||||
@@ -45,6 +50,13 @@ import {
|
||||
X,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
automationIssueKindLabel,
|
||||
canResolveAutomationIssue,
|
||||
filterAutomationIssues,
|
||||
loadAutomationPageData,
|
||||
} from './automationIssueState';
|
||||
import { commitIfLatest } from './latestRequest';
|
||||
|
||||
type RulesTab = 'automation' | 'reply' | 'default';
|
||||
|
||||
@@ -128,6 +140,7 @@ const buildReviewConfig = (raw?: string, patch: Record<string, number> = {}) =>
|
||||
const current = parseJSONObject(raw);
|
||||
return JSON.stringify({
|
||||
after_shipped_hours: Number(current.after_shipped_hours || 72),
|
||||
repeat_interval_hours: Number(current.repeat_interval_hours || 24),
|
||||
max_attempts: Number(current.max_attempts || 1),
|
||||
...patch,
|
||||
});
|
||||
@@ -199,6 +212,7 @@ const boolFlag = (value: unknown): boolean => value === true || value === 1 || v
|
||||
const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHandled }) => {
|
||||
const [activeTab, setActiveTab] = useState<RulesTab>('automation');
|
||||
const [automationRules, setAutomationRules] = useState<ShippingRule[]>([]);
|
||||
const [automationIssues, setAutomationIssues] = useState<{ runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }>({ runs: [], pending_tasks: [] });
|
||||
const [replyRules, setReplyRules] = useState<ReplyRule[]>([]);
|
||||
const [defaultReplies, setDefaultReplies] = useState<Record<string, DefaultReply>>({});
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
@@ -206,6 +220,9 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedAccountId, setSelectedAccountId] = useState('');
|
||||
const replyRulesRequest = useRef(0);
|
||||
const selectedAccountRef = useRef('');
|
||||
selectedAccountRef.current = selectedAccountId;
|
||||
|
||||
const [showAutomationModal, setShowAutomationModal] = useState(false);
|
||||
const [showReplyModal, setShowReplyModal] = useState(false);
|
||||
@@ -236,15 +253,25 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}, []);
|
||||
|
||||
const loadAutomationRules = useCallback(async () => {
|
||||
setAutomationRules(await getShippingRules());
|
||||
await loadAutomationPageData({
|
||||
loadRules: getShippingRules,
|
||||
loadIssues: getAutomationIssues,
|
||||
onRules: setAutomationRules,
|
||||
onIssues: setAutomationIssues,
|
||||
onIssuesError: error => console.warn('加载自动化异常列表失败,不阻断规则展示', error),
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadReplyRules = useCallback(async () => {
|
||||
if (!selectedAccountId) {
|
||||
setReplyRules([]);
|
||||
return;
|
||||
}
|
||||
setReplyRules(await getReplyRules(selectedAccountId));
|
||||
const cookieID = selectedAccountId;
|
||||
if (cookieID !== selectedAccountRef.current) return;
|
||||
const requestID = ++replyRulesRequest.current;
|
||||
setReplyRules([]);
|
||||
if (!cookieID) {
|
||||
return;
|
||||
}
|
||||
const rules = await getReplyRules(cookieID);
|
||||
commitIfLatest(requestID, replyRulesRequest.current, cookieID, selectedAccountRef.current, rules, setReplyRules);
|
||||
}, [selectedAccountId]);
|
||||
|
||||
const loadDefaultReplies = useCallback(async () => {
|
||||
@@ -267,11 +294,11 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}, [activeTab, loadAutomationRules, loadDefaultReplies, loadReplyRules]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadReferenceData();
|
||||
void loadReferenceData().catch(error => console.error('加载规则参考数据失败', error));
|
||||
}, [loadReferenceData]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
void refresh().catch(error => console.error('刷新规则页面失败', error));
|
||||
}, [refresh]);
|
||||
|
||||
const visibleAutomationRules = useMemo(
|
||||
@@ -279,6 +306,11 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
[automationRules, selectedAccountId],
|
||||
);
|
||||
|
||||
const visibleAutomationIssues = useMemo(
|
||||
() => filterAutomationIssues(automationIssues, selectedAccountId),
|
||||
[automationIssues, selectedAccountId],
|
||||
);
|
||||
|
||||
const visibleDefaultAccounts = useMemo(
|
||||
() => accounts.filter(account => !selectedAccountId || account.id === selectedAccountId),
|
||||
[accounts, selectedAccountId],
|
||||
@@ -565,6 +597,31 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}
|
||||
};
|
||||
|
||||
const handleResolveRunIssue = async (id: number, resolution: 'continue' | 'retry' | 'cancel') => {
|
||||
const prompt = resolution === 'continue'
|
||||
? '确认外部动作已经执行成功,并跳到下一步吗?'
|
||||
: resolution === 'retry'
|
||||
? '确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。'
|
||||
: '确认终止该自动化运行吗?';
|
||||
if (!confirm(prompt)) return;
|
||||
try {
|
||||
await resolveAutomationRun(id, resolution);
|
||||
await loadAutomationRules();
|
||||
} catch (error) {
|
||||
alert('处理失败:' + (error as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResolveDeferredIssue = async (id: number, resolution: 'retry' | 'dismiss') => {
|
||||
if (!confirm(resolution === 'retry' ? '确认重新执行该任务吗?' : '确认忽略并删除该异常任务吗?')) return;
|
||||
try {
|
||||
await resolveDeferredAutomationTask(id, resolution);
|
||||
await loadAutomationRules();
|
||||
} catch (error) {
|
||||
alert('处理失败:' + (error as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddReplyRule = () => {
|
||||
if (!selectedAccountId) {
|
||||
alert('请先选择账号');
|
||||
@@ -573,6 +630,9 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
setEditingReplyRule({
|
||||
keyword: '',
|
||||
reply_content: '',
|
||||
image_url: '',
|
||||
item_id: '',
|
||||
type: 'text',
|
||||
match_type: 'fuzzy',
|
||||
enabled: true,
|
||||
});
|
||||
@@ -581,7 +641,9 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
|
||||
const handleSaveReplyRule = async () => {
|
||||
if (!editingReplyRule || !selectedAccountId) return;
|
||||
const hasReplyContent = Boolean(editingReplyRule.reply_content?.trim() || editingReplyRule.image_url?.trim());
|
||||
const hasReplyContent = editingReplyRule.type === 'image'
|
||||
? Boolean(editingReplyRule.image_url?.trim())
|
||||
: Boolean(editingReplyRule.reply_content?.trim());
|
||||
if (!editingReplyRule.keyword?.trim() || !hasReplyContent) {
|
||||
alert('请填写关键词和回复内容');
|
||||
return;
|
||||
@@ -744,6 +806,46 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
})}
|
||||
</div>
|
||||
|
||||
{activeTab === 'automation' && (visibleAutomationIssues.runs.length > 0 || visibleAutomationIssues.pending_tasks.length > 0) && (
|
||||
<section className="rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-red-600 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-black text-red-900">需要人工处理的自动化任务</h3>
|
||||
<p className="text-sm text-red-700 mt-1">请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{visibleAutomationIssues.runs.map(issue => (
|
||||
<div key={`run-${issue.id}`} className="rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-bold text-gray-900">账号 {issue.cookie_id} · 订单 {issue.order_id || '-'} · 已记录发送 {issue.sent_count} 条</div>
|
||||
<div className="text-xs font-bold text-red-800 mt-1">{automationIssueKindLabel(issue.issue_kind)}</div>
|
||||
<div className="text-xs text-red-700 mt-1 break-words">{issue.error_message}</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 shrink-0">
|
||||
{canResolveAutomationIssue(issue, 'continue') && <button onClick={() => void handleResolveRunIssue(issue.id, 'continue')} className="px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold">已执行,继续下一步</button>}
|
||||
{canResolveAutomationIssue(issue, 'retry') && <button onClick={() => void handleResolveRunIssue(issue.id, 'retry')} className="px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold">未执行,安全重试</button>}
|
||||
{canResolveAutomationIssue(issue, 'cancel') && <button onClick={() => void handleResolveRunIssue(issue.id, 'cancel')} className="px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold">终止</button>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{visibleAutomationIssues.pending_tasks.map(issue => (
|
||||
<div key={`task-${issue.id}`} className="rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-bold text-gray-900">账号 {issue.cookie_id} · 延迟任务重试已达 {issue.attempt_count} 次</div>
|
||||
<div className="text-xs text-red-700 mt-1 break-words">{issue.error_message}</div>
|
||||
</div>
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<button onClick={() => void handleResolveDeferredIssue(issue.id, 'retry')} className="px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold">重新入队</button>
|
||||
<button onClick={() => void handleResolveDeferredIssue(issue.id, 'dismiss')} className="px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold">忽略</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{activeTab === 'automation' && (
|
||||
<div className="grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6">
|
||||
<aside className="space-y-4">
|
||||
@@ -1178,7 +1280,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="86400"
|
||||
max="3600"
|
||||
value={variant.delay_seconds || 0}
|
||||
onChange={event => updateVariant(index, { delay_seconds: Math.max(0, Number(event.target.value) || 0) })}
|
||||
className="w-28 ios-input px-2 py-1.5 rounded-lg text-xs"
|
||||
@@ -1209,7 +1311,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<Clock3 className="w-5 h-5 text-amber-600" />
|
||||
<h4 className="font-black text-gray-900">求评价计划</h4>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">发货后等待小时</label>
|
||||
<input
|
||||
@@ -1225,6 +1327,21 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">再次求评间隔小时</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
value={Number(reviewConfig.repeat_interval_hours || 24)}
|
||||
onChange={event => setEditingAutomationRule({
|
||||
...editingAutomationRule,
|
||||
config_json: buildReviewConfig(editingAutomationRule.config_json, {
|
||||
repeat_interval_hours: Math.max(1, Number(event.target.value) || 24),
|
||||
}),
|
||||
})}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">最多求评次数</label>
|
||||
<input
|
||||
@@ -1240,7 +1357,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<div className="md:col-span-3">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">求评价文案</label>
|
||||
<textarea
|
||||
value={editingAutomationRule.actions?.find(action => action.action_type === 'send_text')?.message_template || ''}
|
||||
@@ -1260,7 +1377,8 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<section className="bg-white rounded-3xl border border-gray-100 p-5">
|
||||
<div className="grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">优先级</label>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">优先级</label>
|
||||
<p className="text-xs text-gray-500 mb-2">数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。</p>
|
||||
<input
|
||||
type="number"
|
||||
value={editingAutomationRule.priority || 100}
|
||||
@@ -1316,6 +1434,40 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
|
||||
<div className="modal-body space-y-5">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">关联商品</label>
|
||||
<select
|
||||
value={editingReplyRule.item_id || ''}
|
||||
onChange={event => setEditingReplyRule({ ...editingReplyRule, item_id: event.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="">账号级回复</option>
|
||||
{items.filter(item => !selectedAccountId || item.cookie_id === selectedAccountId).map(item => (
|
||||
<option key={`${item.cookie_id}-${item.item_id}`} value={item.item_id}>{item.item_title || item.item_id}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">回复类型</label>
|
||||
<select
|
||||
value={editingReplyRule.type || 'text'}
|
||||
onChange={event => {
|
||||
const type = event.target.value as 'text' | 'image';
|
||||
setEditingReplyRule({
|
||||
...editingReplyRule,
|
||||
type,
|
||||
reply_content: type === 'text' ? editingReplyRule.reply_content : '',
|
||||
image_url: type === 'image' ? editingReplyRule.image_url : '',
|
||||
});
|
||||
}}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="text">文字</option>
|
||||
<option value="image">图片</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">关键词</label>
|
||||
<input
|
||||
@@ -1327,15 +1479,27 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">回复内容</label>
|
||||
<textarea
|
||||
value={editingReplyRule.reply_content || ''}
|
||||
onChange={event => setEditingReplyRule({ ...editingReplyRule, reply_content: event.target.value })}
|
||||
placeholder="自动回复的内容"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"
|
||||
/>
|
||||
</div>
|
||||
{editingReplyRule.type === 'image' ? (
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">图片 URL</label>
|
||||
<input
|
||||
value={editingReplyRule.image_url || ''}
|
||||
onChange={event => setEditingReplyRule({ ...editingReplyRule, image_url: event.target.value })}
|
||||
placeholder="https://..."
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">回复内容</label>
|
||||
<textarea
|
||||
value={editingReplyRule.reply_content || ''}
|
||||
onChange={event => setEditingReplyRule({ ...editingReplyRule, reply_content: event.target.value })}
|
||||
placeholder="自动回复的内容"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
|
||||
@@ -52,6 +52,7 @@ const Settings: React.FC = () => {
|
||||
|
||||
// Password visibility states
|
||||
const [showApiKey, setShowApiKey] = useState(false);
|
||||
const [showCaptchaSecret, setShowCaptchaSecret] = useState(false);
|
||||
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
|
||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||
const [credentialsSaving, setCredentialsSaving] = useState(false);
|
||||
@@ -389,6 +390,66 @@ const Settings: React.FC = () => {
|
||||
|
||||
{/* Right Column */}
|
||||
<div className="space-y-8">
|
||||
<section className="space-y-4">
|
||||
<h3 className="text-lg font-extrabold text-gray-800 flex items-center gap-2">
|
||||
<div className="p-1.5 rounded-lg bg-amber-500 text-white">
|
||||
<ShieldCheck className="w-4 h-4" />
|
||||
</div>
|
||||
远程过滑块配置
|
||||
</h3>
|
||||
|
||||
<div className="ios-card rounded-xl p-6 bg-white space-y-5">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">服务地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={settings['captcha.remote_service_url'] || ''}
|
||||
onChange={event => setSettings({...settings, 'captcha.remote_service_url': event.target.value})}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
|
||||
placeholder="https://example.com/internal/captcha/solve"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-800">服务秘钥</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showCaptchaSecret ? 'text' : 'password'}
|
||||
value={settings['captcha.remote_secret_key'] || ''}
|
||||
onChange={event => setSettings({...settings, 'captcha.remote_secret_key': event.target.value})}
|
||||
className="w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm"
|
||||
autoComplete="off"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCaptchaSecret(!showCaptchaSecret)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
|
||||
title={showCaptchaSecret ? '隐藏秘钥' : '显示秘钥'}
|
||||
>
|
||||
{showCaptchaSecret ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={String(settings['captcha.remote_pass_cookies'] || '').toLowerCase() === 'true'}
|
||||
onChange={event => setSettings({...settings, 'captcha.remote_pass_cookies': event.target.checked})}
|
||||
className="mt-0.5 w-4 h-4 rounded border-gray-300"
|
||||
/>
|
||||
<span>
|
||||
<span className="block text-sm font-bold text-amber-900">允许向远程服务传递账号 Cookie</span>
|
||||
<span className="block mt-1 text-xs text-amber-700">默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<p className="text-xs text-gray-500">
|
||||
配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<h3 className="text-lg font-extrabold text-gray-800 flex items-center gap-2">
|
||||
<div className="p-1.5 rounded-lg bg-gray-900 text-white">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React from 'react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
|
||||
import { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: string;
|
||||
@@ -24,8 +25,8 @@ const Sidebar: React.FC<SidebarProps> = ({ activeTab, isAdmin = false, onNavigat
|
||||
<div className="w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center gap-3 mb-12 px-2">
|
||||
<div className="w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5" style={{ filter: 'drop-shadow(0 4px 12px rgba(0,148,247,0.25))' }}>
|
||||
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
|
||||
<div className="shrink-0">
|
||||
<YdisksBrandIcon sizeClass="w-10 h-10" />
|
||||
</div>
|
||||
<h1 className="text-xl font-extrabold tracking-tight text-gray-900">Ydisks闲鱼助手 <span className="text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1">PRO</span></h1>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
|
||||
test('login QR code preserves a square aspect ratio without stretching', () => {
|
||||
const html = renderToStaticMarkup(<SquareQRCode src="data:image/png;base64,abc" alt="登录二维码" className="p-2" />);
|
||||
expect(html).toContain('aspect-square');
|
||||
expect(html).toContain('h-auto');
|
||||
expect(html).toContain('object-contain');
|
||||
expect(html).toContain('p-2');
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
|
||||
interface SquareQRCodeProps {
|
||||
src: string;
|
||||
alt: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const SquareQRCode: React.FC<SquareQRCodeProps> = ({ src, alt, className = '' }) => (
|
||||
<img
|
||||
src={src}
|
||||
alt={alt}
|
||||
className={`block aspect-square h-auto w-full object-contain ${className}`.trim()}
|
||||
/>
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import YdisksLogo, { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
describe('YdisksLogo', () => {
|
||||
test('uses the complete 256px brand coordinate system', () => {
|
||||
const html = renderToStaticMarkup(<YdisksLogo />);
|
||||
expect(html).toContain('viewBox="0 0 256 256"');
|
||||
expect(html).toContain('M121.73,57.0003');
|
||||
expect(html).toContain('fill="currentColor"');
|
||||
});
|
||||
|
||||
test('renders the complete gradient squircle brand wrapper', () => {
|
||||
const html = renderToStaticMarkup(<YdisksBrandIcon />);
|
||||
expect(html).toContain('viewBox="0 0 120 120"');
|
||||
expect(html).toContain('id="login-squircle-gradient"');
|
||||
expect(html).toContain('M 114.00 60.00');
|
||||
expect(html).toContain('w-12 h-12');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import React from 'react';
|
||||
|
||||
interface YdisksLogoProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface YdisksBrandIconProps {
|
||||
sizeClass?: string;
|
||||
logoClassName?: string;
|
||||
}
|
||||
|
||||
const YdisksLogo: React.FC<YdisksLogoProps> = ({ className = 'w-full h-full text-white' }) => (
|
||||
<svg className={className} viewBox="0 0 256 256" aria-hidden="true">
|
||||
<g stroke="none" fill="none" fillRule="evenodd">
|
||||
<path d="M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z" fill="currentColor" />
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
|
||||
sizeClass = 'w-12 h-12',
|
||||
logoClassName = 'w-full h-full text-white',
|
||||
}) => (
|
||||
<div className="relative z-10 flex items-center justify-center">
|
||||
<div className="absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25" />
|
||||
<div className={`relative ${sizeClass} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`}>
|
||||
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 120 120" aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id="login-squircle-gradient" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="#0094f7" />
|
||||
<stop offset="100%" stopColor="#287efe" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z" fill="url(#login-squircle-gradient)" />
|
||||
</svg>
|
||||
<div className="relative z-10 flex items-center justify-center w-full h-full">
|
||||
<YdisksLogo className={logoClassName} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default YdisksLogo;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { shouldUpdateAccountPause } from './accountPause';
|
||||
|
||||
describe('shouldUpdateAccountPause', () => {
|
||||
it('does not silently reapply the same duration after a pause has expired', () => {
|
||||
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: false })).toBe(false);
|
||||
});
|
||||
|
||||
it('does not restart an active unchanged pause', () => {
|
||||
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('sends changed values including explicit resume', () => {
|
||||
expect(shouldUpdateAccountPause(30, { pause_duration: 60, paused: true })).toBe(true);
|
||||
expect(shouldUpdateAccountPause(0, { pause_duration: 60, paused: true })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { AccountDetail } from '../types';
|
||||
|
||||
export const shouldUpdateAccountPause = (
|
||||
requestedMinutes: number,
|
||||
account: Pick<AccountDetail, 'pause_duration' | 'paused'>,
|
||||
): boolean => {
|
||||
const savedMinutes = account.pause_duration || 0;
|
||||
return requestedMinutes !== savedMinutes;
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { AccountDetail } from '../types';
|
||||
import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
|
||||
|
||||
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
|
||||
id: 'account-1',
|
||||
cookie: 'cookie',
|
||||
enabled: true,
|
||||
auto_confirm: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('mergeAccountRuntimeStatuses', () => {
|
||||
test('用最新在线状态替换风控恢复中的旧提示', () => {
|
||||
const result = mergeAccountRuntimeStatuses([
|
||||
account({
|
||||
runtime_state: 'connecting',
|
||||
runtime_message: 'token 风控验证已处理,正在重新获取登录凭证',
|
||||
runtime_updated_at: '2026-07-13T13:16:00+08:00',
|
||||
}),
|
||||
], {
|
||||
'account-1': {
|
||||
state: 'online',
|
||||
message: '消息服务连接正常',
|
||||
connected: true,
|
||||
failures: 0,
|
||||
updated_at: '2026-07-13T13:16:02+08:00',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
runtime_state: 'online',
|
||||
runtime_message: '消息服务连接正常',
|
||||
runtime_connected: true,
|
||||
runtime_updated_at: '2026-07-13T13:16:02+08:00',
|
||||
});
|
||||
});
|
||||
|
||||
test('忽略晚到达的旧状态响应', () => {
|
||||
const current = account({
|
||||
runtime_state: 'online',
|
||||
runtime_message: '消息服务连接正常',
|
||||
runtime_updated_at: '2026-07-13T13:16:02+08:00',
|
||||
});
|
||||
const result = mergeAccountRuntimeStatuses([current], {
|
||||
'account-1': {
|
||||
state: 'connecting',
|
||||
message: 'token 风控验证已处理,正在重新获取登录凭证',
|
||||
connected: false,
|
||||
failures: 0,
|
||||
updated_at: '2026-07-13T13:16:00+08:00',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result[0]).toBe(current);
|
||||
});
|
||||
|
||||
test('缺少对应运行时状态时保留账号对象', () => {
|
||||
const current = account();
|
||||
expect(mergeAccountRuntimeStatuses([current], {})[0]).toBe(current);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { AccountRuntimeStatus } from '../services/api';
|
||||
import type { AccountDetail } from '../types';
|
||||
|
||||
const isOlderStatus = (currentUpdatedAt?: string, incomingUpdatedAt?: string): boolean => {
|
||||
if (!currentUpdatedAt || !incomingUpdatedAt) return false;
|
||||
const currentTime = Date.parse(currentUpdatedAt);
|
||||
const incomingTime = Date.parse(incomingUpdatedAt);
|
||||
return Number.isFinite(currentTime) && Number.isFinite(incomingTime) && incomingTime < currentTime;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将运行时快照合并到账号列表。较晚到达的旧请求不能覆盖更新的状态。
|
||||
*/
|
||||
export const mergeAccountRuntimeStatuses = (
|
||||
accounts: AccountDetail[],
|
||||
statuses: Record<string, AccountRuntimeStatus>,
|
||||
): AccountDetail[] => accounts.map(account => {
|
||||
const status = statuses[account.id];
|
||||
if (!status || isOlderStatus(account.runtime_updated_at, status.updated_at)) return account;
|
||||
return {
|
||||
...account,
|
||||
runtime_state: status.state,
|
||||
runtime_message: status.message || '',
|
||||
runtime_connected: status.connected,
|
||||
runtime_updated_at: status.updated_at,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { AutomationRunIssue } from '../services/api';
|
||||
import { canResolveAutomationIssue, filterAutomationIssues, loadAutomationPageData } from './automationIssueState';
|
||||
|
||||
const issue = (cookieID: string, allowed: AutomationRunIssue['allowed_resolutions']): AutomationRunIssue => ({
|
||||
id: cookieID === 'a' ? 1 : 2,
|
||||
cookie_id: cookieID,
|
||||
order_id: 'o',
|
||||
trigger_type: 'buyer_reviewed',
|
||||
error_message: 'error',
|
||||
issue_kind: 'invalid_snapshot',
|
||||
allowed_resolutions: allowed,
|
||||
action_cursor: 0,
|
||||
sent_count: 0,
|
||||
updated_at: '',
|
||||
});
|
||||
|
||||
test('automation issue actions follow the backend policy', () => {
|
||||
const invalid = issue('a', ['cancel']);
|
||||
expect(canResolveAutomationIssue(invalid, 'cancel')).toBe(true);
|
||||
expect(canResolveAutomationIssue(invalid, 'continue')).toBe(false);
|
||||
expect(canResolveAutomationIssue(invalid, 'retry')).toBe(false);
|
||||
});
|
||||
|
||||
test('automation issues are filtered before deciding whether to show the panel', () => {
|
||||
const visible = filterAutomationIssues({ runs: [issue('a', ['cancel']), issue('b', ['retry', 'cancel'])], pending_tasks: [] }, 'missing');
|
||||
expect(visible.runs).toEqual([]);
|
||||
expect(visible.pending_tasks).toEqual([]);
|
||||
});
|
||||
|
||||
test('automation rules still load when the diagnostic issue request fails', async () => {
|
||||
const receivedRules: string[][] = [];
|
||||
const errors: unknown[] = [];
|
||||
await loadAutomationPageData({
|
||||
loadRules: async () => ['rule'],
|
||||
loadIssues: async () => { throw new Error('issues unavailable'); },
|
||||
onRules: rules => receivedRules.push(rules),
|
||||
onIssues: () => { throw new Error('must not receive issues'); },
|
||||
onIssuesError: error => errors.push(error),
|
||||
});
|
||||
expect(receivedRules).toEqual([['rule']]);
|
||||
expect(errors).toHaveLength(1);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { AutomationRunIssue, DeferredAutomationIssue } from '../services/api';
|
||||
|
||||
export type AutomationResolution = 'continue' | 'retry' | 'cancel';
|
||||
|
||||
export const canResolveAutomationIssue = (
|
||||
issue: AutomationRunIssue,
|
||||
resolution: AutomationResolution,
|
||||
): boolean => issue.allowed_resolutions.includes(resolution);
|
||||
|
||||
export const filterAutomationIssues = (
|
||||
issues: { runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] },
|
||||
cookieID: string,
|
||||
) => ({
|
||||
runs: issues.runs.filter(issue => !cookieID || issue.cookie_id === cookieID),
|
||||
pending_tasks: issues.pending_tasks.filter(issue => !cookieID || issue.cookie_id === cookieID),
|
||||
});
|
||||
|
||||
export const automationIssueKindLabel = (kind: AutomationRunIssue['issue_kind']): string => ({
|
||||
external_result_unknown: '外部动作结果未知',
|
||||
invalid_snapshot: '历史数据无法恢复',
|
||||
rule_unavailable: '规则不可用',
|
||||
partial_failure: '部分动作失败',
|
||||
execution_failed: '动作执行失败',
|
||||
}[kind] || '自动化异常');
|
||||
|
||||
export const loadAutomationPageData = async <TRule>(options: {
|
||||
loadRules: () => Promise<TRule[]>;
|
||||
loadIssues: () => Promise<{ runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }>;
|
||||
onRules: (rules: TRule[]) => void;
|
||||
onIssues: (issues: { runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }) => void;
|
||||
onIssuesError: (error: unknown) => void;
|
||||
}): Promise<void> => {
|
||||
const issuesPromise = options.loadIssues().then(options.onIssues).catch(options.onIssuesError);
|
||||
const rules = await options.loadRules();
|
||||
options.onRules(rules);
|
||||
await issuesPromise;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import type { Card } from '../types';
|
||||
import { filterCards } from './cardListState';
|
||||
|
||||
const cards = [
|
||||
{ id: 1, name: '年终总结 PPT', type: 'text' },
|
||||
{ id: 2, name: '年终总结兑换码', type: 'data' },
|
||||
{ id: 3, name: '产品介绍 PPT', type: 'text' },
|
||||
] as Card[];
|
||||
|
||||
describe('filterCards', () => {
|
||||
test('combines type and name filters with AND semantics', () => {
|
||||
expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
|
||||
});
|
||||
|
||||
test('matches names case-insensitively and ignores surrounding whitespace', () => {
|
||||
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Card } from '../types';
|
||||
|
||||
export const filterCards = (
|
||||
cards: Card[],
|
||||
typeFilter: Card['type'] | '',
|
||||
nameSearch: string,
|
||||
): Card[] => {
|
||||
const keyword = nameSearch.trim().toLocaleLowerCase();
|
||||
return cards.filter(card => (
|
||||
(!typeFilter || card.type === typeFilter)
|
||||
&& (!keyword || card.name.toLocaleLowerCase().includes(keyword))
|
||||
));
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { selectActivePublishBatch } from './itemPublishBatchState';
|
||||
|
||||
test('completed history does not replace the new batch upload flow', () => {
|
||||
expect(selectActivePublishBatch([{ id: 'done', status: 'completed' }])).toBeUndefined();
|
||||
expect(selectActivePublishBatch([
|
||||
{ id: 'done', status: 'completed' },
|
||||
{ id: 'active', status: 'running' },
|
||||
])?.id).toBe('active');
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface PublishBatchSummary {
|
||||
id?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export const selectActivePublishBatch = <T extends PublishBatchSummary>(batches: T[]): T | undefined =>
|
||||
batches.find(batch => batch.status === 'running' || batch.status === 'canceling');
|
||||
@@ -0,0 +1,11 @@
|
||||
import { expect, test, vi } from 'vitest';
|
||||
import { commitIfLatest } from './latestRequest';
|
||||
|
||||
test('stale account responses cannot replace the latest rules', () => {
|
||||
const commit = vi.fn();
|
||||
expect(commitIfLatest(1, 2, 'a', 'b', ['account-a'], commit)).toBe(false);
|
||||
expect(commit).not.toHaveBeenCalled();
|
||||
expect(commitIfLatest(2, 2, 'a', 'b', ['account-a'], commit)).toBe(false);
|
||||
expect(commitIfLatest(2, 2, 'b', 'b', ['account-b'], commit)).toBe(true);
|
||||
expect(commit).toHaveBeenCalledWith(['account-b']);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export const commitIfLatest = <T>(
|
||||
requestID: number,
|
||||
currentRequestID: number,
|
||||
requestKey: string,
|
||||
currentKey: string,
|
||||
value: T,
|
||||
commit: (value: T) => void,
|
||||
): boolean => {
|
||||
if (requestID !== currentRequestID || requestKey !== currentKey) return false;
|
||||
commit(value);
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { failedOrderImportRows, normalizeOrderImportResult } from './orderImportState';
|
||||
|
||||
test('order import state preserves row-level failure details for display', () => {
|
||||
const result = normalizeOrderImportResult({
|
||||
total: 2,
|
||||
success_count: 1,
|
||||
failed_count: 1,
|
||||
results: [
|
||||
{ order_id: 'ok', success: true, message: '订单已导入' },
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
],
|
||||
});
|
||||
expect(result.failed_count).toBe(1);
|
||||
expect(failedOrderImportRows(result)).toEqual([
|
||||
{ order_id: 'bad', success: false, message: '不支持的订单状态' },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface OrderImportRowResult {
|
||||
order_id: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface OrderImportResult {
|
||||
total: number;
|
||||
success_count: number;
|
||||
failed_count: number;
|
||||
results: OrderImportRowResult[];
|
||||
}
|
||||
|
||||
export const normalizeOrderImportResult = (value: any): OrderImportResult => ({
|
||||
total: Number(value?.total || 0),
|
||||
success_count: Number(value?.success_count || 0),
|
||||
failed_count: Number(value?.failed_count || 0),
|
||||
results: Array.isArray(value?.results) ? value.results.map((row: any) => ({
|
||||
order_id: String(row?.order_id || 'unknown'),
|
||||
success: row?.success === true,
|
||||
message: String(row?.message || ''),
|
||||
})) : [],
|
||||
});
|
||||
|
||||
export const failedOrderImportRows = (result: OrderImportResult | null): OrderImportRowResult[] =>
|
||||
result?.results.filter(row => !row.success) || [];
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import { createQRLoginPoller } from './qrPolling';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
@@ -25,7 +25,7 @@ test('QR poller clears the previous interval before starting another session', (
|
||||
vi.advanceTimersByTime(2000);
|
||||
|
||||
expect(checkStatus).toHaveBeenCalledTimes(1);
|
||||
expect(checkStatus).toHaveBeenCalledWith('sid-2');
|
||||
expect(checkStatus).toHaveBeenCalledWith('sid-2', expect.any(AbortSignal));
|
||||
});
|
||||
|
||||
test('QR poller stops on success and terminal errors', async () => {
|
||||
@@ -96,3 +96,57 @@ test('QR poller keeps polling during verification and stops on thrown errors', a
|
||||
expect(onPollError).toHaveBeenCalledWith(expect.any(Error));
|
||||
expect(poller.isActive()).toBe(false);
|
||||
});
|
||||
|
||||
test('QR poller never overlaps slow status requests', async () => {
|
||||
vi.useFakeTimers();
|
||||
let resolveStatus: ((value: { status: string }) => void) | undefined;
|
||||
const checkStatus = vi.fn(() => new Promise<{ status: string }>(resolve => {
|
||||
resolveStatus = resolve;
|
||||
}));
|
||||
const poller = createQRLoginPoller();
|
||||
poller.start('slow-session', checkStatus, {
|
||||
onSuccess: vi.fn(),
|
||||
onTerminalError: vi.fn(),
|
||||
onPollError: vi.fn(),
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
expect(checkStatus).toHaveBeenCalledTimes(1);
|
||||
|
||||
resolveStatus?.({ status: 'waiting' });
|
||||
await flushMicrotasks();
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(checkStatus).toHaveBeenCalledTimes(2);
|
||||
poller.stop();
|
||||
});
|
||||
|
||||
test('latest request gate rejects stale generation after switch or cancel', () => {
|
||||
const gate = createLatestRequestGate();
|
||||
const first = gate.next();
|
||||
const second = gate.next();
|
||||
|
||||
expect(gate.isCurrent(first)).toBe(false);
|
||||
expect(gate.isCurrent(second)).toBe(true);
|
||||
|
||||
gate.cancel();
|
||||
expect(gate.isCurrent(second)).toBe(false);
|
||||
});
|
||||
|
||||
test('stopping QR polling aborts the in-flight status request without reporting an error', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onPollError = vi.fn();
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
const checkStatus = vi.fn((_sessionId: string, signal?: AbortSignal) => {
|
||||
observedSignal = signal;
|
||||
return new Promise<{ status: string }>((_resolve, reject) => {
|
||||
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||
});
|
||||
});
|
||||
const poller = createQRLoginPoller();
|
||||
poller.start('sid', checkStatus, { onSuccess: vi.fn(), onTerminalError: vi.fn(), onPollError });
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
poller.stop();
|
||||
await flushMicrotasks();
|
||||
expect(observedSignal?.aborted).toBe(true);
|
||||
expect(onPollError).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -22,6 +22,22 @@ export interface QRLoginPollHandlers {
|
||||
|
||||
const terminalQRStatuses = new Set(['expired', 'cancelled', 'error', 'not_found']);
|
||||
|
||||
// createLatestRequestGate 让只能由“最后一次用户操作”提交结果的异步请求拥有
|
||||
// 明确代次。cancel 会使所有尚未返回的请求失效,但不要求底层 fetch 支持中断。
|
||||
export const createLatestRequestGate = () => {
|
||||
let generation = 0;
|
||||
return {
|
||||
next: () => {
|
||||
generation += 1;
|
||||
return generation;
|
||||
},
|
||||
cancel: () => {
|
||||
generation += 1;
|
||||
},
|
||||
isCurrent: (candidate: number) => candidate === generation,
|
||||
};
|
||||
};
|
||||
|
||||
export const createQRLoginPoller = (
|
||||
timers: QRLoginPollerTimers = {
|
||||
setInterval: globalThis.setInterval.bind(globalThis),
|
||||
@@ -29,8 +45,14 @@ export const createQRLoginPoller = (
|
||||
},
|
||||
) => {
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
let requestController: AbortController | null = null;
|
||||
let inFlightGeneration = -1;
|
||||
let generation = 0;
|
||||
|
||||
const stop = () => {
|
||||
generation += 1;
|
||||
requestController?.abort();
|
||||
requestController = null;
|
||||
if (interval !== null) {
|
||||
timers.clearInterval(interval);
|
||||
interval = null;
|
||||
@@ -39,15 +61,20 @@ export const createQRLoginPoller = (
|
||||
|
||||
const start = (
|
||||
sessionId: string,
|
||||
checkStatus: (sessionId: string) => Promise<QRLoginStatusResult>,
|
||||
checkStatus: (sessionId: string, signal?: AbortSignal) => Promise<QRLoginStatusResult>,
|
||||
handlers: QRLoginPollHandlers,
|
||||
intervalMs = 2000,
|
||||
) => {
|
||||
stop();
|
||||
const currentGeneration = generation;
|
||||
requestController = new AbortController();
|
||||
const signal = requestController.signal;
|
||||
interval = timers.setInterval(() => {
|
||||
if (inFlightGeneration === currentGeneration || currentGeneration !== generation) return;
|
||||
inFlightGeneration = currentGeneration;
|
||||
void (async () => {
|
||||
try {
|
||||
const statusRes = await checkStatus(sessionId);
|
||||
const statusRes = await checkStatus(sessionId, signal);
|
||||
if (statusRes.status === 'success') {
|
||||
stop();
|
||||
await handlers.onSuccess(statusRes);
|
||||
@@ -66,8 +93,11 @@ export const createQRLoginPoller = (
|
||||
handlers.onTerminalError(statusRes);
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted || currentGeneration !== generation) return;
|
||||
stop();
|
||||
handlers.onPollError(error);
|
||||
} finally {
|
||||
if (inFlightGeneration === currentGeneration) inFlightGeneration = -1;
|
||||
}
|
||||
})();
|
||||
}, intervalMs);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { formatLocalDateTime } from './dateTime';
|
||||
|
||||
describe('formatLocalDateTime', () => {
|
||||
test('uses the browser local timezone and the standard second-level format', () => {
|
||||
expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12');
|
||||
});
|
||||
|
||||
test('returns a placeholder for missing or invalid timestamps', () => {
|
||||
expect(formatLocalDateTime()).toBe('-');
|
||||
expect(formatLocalDateTime('not-a-date')).toBe('-');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const padTwoDigits = (value: number): string => String(value).padStart(2, '0');
|
||||
|
||||
/** Format a timestamp in the browser's current timezone. */
|
||||
export const formatLocalDateTime = (value?: string | number | Date | null): string => {
|
||||
if (value === undefined || value === null || value === '') return '-';
|
||||
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '-';
|
||||
|
||||
return [
|
||||
date.getFullYear(),
|
||||
padTwoDigits(date.getMonth() + 1),
|
||||
padTwoDigits(date.getDate()),
|
||||
].join('-') + ' ' + [
|
||||
padTwoDigits(date.getHours()),
|
||||
padTwoDigits(date.getMinutes()),
|
||||
padTwoDigits(date.getSeconds()),
|
||||
].join(':');
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from './notificationEmailConfig';
|
||||
|
||||
describe('email notification SMTP modes', () => {
|
||||
test('recognizes legacy channel overrides as custom SMTP', () => {
|
||||
expect(normalizeEmailChannelConfig({ to_email: 'to@example.com', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true);
|
||||
});
|
||||
|
||||
test('inherit mode removes every channel-level SMTP override', () => {
|
||||
expect(buildEmailChannelConfig({
|
||||
to_email: ' to@example.com ',
|
||||
use_custom_smtp: false,
|
||||
smtp_server: 'stale.example.com',
|
||||
smtp_use_tls: false,
|
||||
})).toEqual({ to_email: 'to@example.com', use_custom_smtp: false });
|
||||
});
|
||||
|
||||
test('custom mode starts from a complete copy of system SMTP settings', () => {
|
||||
const result = enableCustomSMTP({ to_email: 'to@example.com' }, {
|
||||
smtp_server: 'smtp.example.com',
|
||||
smtp_port: 465,
|
||||
smtp_user: 'from@example.com',
|
||||
smtp_password: 'secret',
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
use_custom_smtp: true,
|
||||
smtp_server: 'smtp.example.com',
|
||||
smtp_port: 465,
|
||||
smtp_from_address: 'from@example.com',
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
const smtpOverrideKeys = [
|
||||
'smtp_server',
|
||||
'smtp_port',
|
||||
'smtp_user',
|
||||
'smtp_password',
|
||||
'smtp_from_name',
|
||||
'smtp_from_address',
|
||||
'smtp_use_tls',
|
||||
'smtp_use_ssl',
|
||||
] as const;
|
||||
|
||||
const parseBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'string') {
|
||||
if (['true', '1', 'yes', 'on'].includes(value.toLowerCase())) return true;
|
||||
if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
|
||||
export const normalizeEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp');
|
||||
const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '');
|
||||
return {
|
||||
...config,
|
||||
use_custom_smtp: hasExplicitMode
|
||||
? parseBoolean(config.use_custom_smtp, false)
|
||||
: hasLegacyOverrides,
|
||||
};
|
||||
};
|
||||
|
||||
export const enableCustomSMTP = (
|
||||
config: Record<string, unknown>,
|
||||
systemSettings: Record<string, unknown>,
|
||||
): Record<string, unknown> => {
|
||||
const next: Record<string, unknown> = { ...config, use_custom_smtp: true };
|
||||
for (const key of smtpOverrideKeys) {
|
||||
if (String(next[key] ?? '').trim() === '' && systemSettings[key] !== undefined) {
|
||||
next[key] = systemSettings[key];
|
||||
}
|
||||
}
|
||||
next.smtp_port ||= 587;
|
||||
next.smtp_from_address ||= next.smtp_user || '';
|
||||
next.smtp_use_tls = parseBoolean(next.smtp_use_tls, true);
|
||||
next.smtp_use_ssl = parseBoolean(next.smtp_use_ssl, false);
|
||||
return next;
|
||||
};
|
||||
|
||||
export const buildEmailChannelConfig = (config: Record<string, unknown>): Record<string, unknown> => {
|
||||
const normalized = normalizeEmailChannelConfig(config);
|
||||
const result: Record<string, unknown> = {
|
||||
to_email: String(normalized.to_email ?? '').trim(),
|
||||
use_custom_smtp: normalized.use_custom_smtp === true,
|
||||
};
|
||||
if (result.use_custom_smtp) {
|
||||
for (const key of smtpOverrideKeys) result[key] = normalized[key];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
Generated
+29
@@ -16,6 +16,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"autoprefixer": "^10.4.23",
|
||||
"postcss": "^8.5.6",
|
||||
@@ -1437,6 +1439,26 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.2.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
||||
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react-dom": {
|
||||
"version": "19.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/use-sync-external-store": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
|
||||
@@ -1898,6 +1920,13 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
@@ -18,6 +19,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"autoprefixer": "^10.4.23",
|
||||
"postcss": "^8.5.6",
|
||||
|
||||
@@ -75,10 +75,23 @@ describe('request helpers', () => {
|
||||
const form = new FormData();
|
||||
form.set('name', 'value');
|
||||
await expect(postForm('/upload', form)).resolves.toBe('ok');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/upload', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith('/upload', expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: form,
|
||||
}));
|
||||
});
|
||||
|
||||
test('aborts requests at the configured timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const pending = get('/slow', undefined, { timeoutMs: 50 });
|
||||
const rejection = expect(pending).rejects.toThrow('请求超时');
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
await rejection;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
+66
-19
@@ -4,11 +4,19 @@ type QueryParams = Record<string, string | number | boolean | undefined | null>;
|
||||
|
||||
type JsonValue = unknown;
|
||||
|
||||
export type RequestControlOptions = {
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
type RequestOptions = {
|
||||
params?: QueryParams;
|
||||
body?: JsonValue;
|
||||
skipAuthLogout?: boolean;
|
||||
};
|
||||
} & RequestControlOptions;
|
||||
|
||||
const defaultRequestTimeoutMs = 30_000;
|
||||
const uploadRequestTimeoutMs = 10 * 60_000;
|
||||
|
||||
let authLogoutPending = false;
|
||||
|
||||
@@ -36,14 +44,26 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
const qs = buildQueryString(options.params);
|
||||
const fullUrl = `${url}${qs}`;
|
||||
|
||||
const res = await fetch(fullUrl, {
|
||||
method,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
...(options.body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? defaultRequestTimeoutMs);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(fullUrl, {
|
||||
method,
|
||||
credentials: 'include',
|
||||
signal: control.signal,
|
||||
headers: {
|
||||
...(options.body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
} catch (error) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '请求超时,请稍后重试');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
const isJson = contentType.includes('application/json');
|
||||
@@ -64,17 +84,29 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
return (await res.json()) as T;
|
||||
};
|
||||
|
||||
export const get = async <T>(url: string, params?: QueryParams): Promise<T> => request<T>('GET', url, { params });
|
||||
export const post = async <T>(url: string, body?: JsonValue, options?: { skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options });
|
||||
export const put = async <T>(url: string, body?: JsonValue): Promise<T> => request<T>('PUT', url, { body });
|
||||
export const del = async <T>(url: string, params?: QueryParams): Promise<T> => request<T>('DELETE', url, { params });
|
||||
export const get = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('GET', url, { params, ...options });
|
||||
export const post = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions & { skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options });
|
||||
export const put = async <T>(url: string, body?: JsonValue, options?: RequestControlOptions): Promise<T> => request<T>('PUT', url, { body, ...options });
|
||||
export const del = async <T>(url: string, params?: QueryParams, options?: RequestControlOptions): Promise<T> => request<T>('DELETE', url, { params, ...options });
|
||||
|
||||
export const postForm = async <T>(url: string, body: FormData): Promise<T> => {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body,
|
||||
});
|
||||
export const postForm = async <T>(url: string, body: FormData, options: RequestControlOptions = {}): Promise<T> => {
|
||||
const control = controlledSignal(options.signal, options.timeoutMs ?? uploadRequestTimeoutMs);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
signal: control.signal,
|
||||
body,
|
||||
});
|
||||
} catch (error) {
|
||||
if (control.signal.aborted) {
|
||||
throw new Error(options.signal?.aborted ? '请求已取消' : '上传超时,请稍后重试');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
control.cleanup();
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
const isJson = contentType.includes('application/json');
|
||||
@@ -90,3 +122,18 @@ export const postForm = async <T>(url: string, body: FormData): Promise<T> => {
|
||||
|
||||
return payload as T;
|
||||
};
|
||||
|
||||
const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number) => {
|
||||
const controller = new AbortController();
|
||||
const abortFromExternal = () => controller.abort(external?.reason);
|
||||
if (external?.aborted) abortFromExternal();
|
||||
else external?.addEventListener('abort', abortFromExternal, { once: true });
|
||||
const timer = globalThis.setTimeout(() => controller.abort(new DOMException('timeout', 'TimeoutError')), Math.max(1, timeoutMs));
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
external?.removeEventListener('abort', abortFromExternal);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -60,13 +60,25 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).toContain('setLoadError');
|
||||
});
|
||||
|
||||
test('email notification config uses backend recipient field names', () => {
|
||||
test('captcha remote settings expose the reference privacy and fallback semantics', () => {
|
||||
const settings = readFrontendFile('components/Settings.tsx');
|
||||
|
||||
expect(settings).toContain('远程过滑块配置');
|
||||
expect(settings).toContain("'captcha.remote_service_url'");
|
||||
expect(settings).toContain("'captcha.remote_secret_key'");
|
||||
expect(settings).toContain("'captcha.remote_pass_cookies'");
|
||||
expect(settings).toContain('默认关闭');
|
||||
expect(settings).toContain('只有网络不可用或超时才回退本机引擎');
|
||||
});
|
||||
|
||||
test('email notification config separates system and custom SMTP modes', () => {
|
||||
const notifications = readFrontendFile('components/Notifications.tsx');
|
||||
|
||||
expect(notifications).toContain('interface NotificationsProps');
|
||||
expect(notifications).toContain('isAdmin && (');
|
||||
expect(notifications).toContain("key: 'to_email'");
|
||||
expect(notifications).toContain('留空时使用上方系统级 SMTP 配置');
|
||||
expect(notifications).toContain('完整继承系统 SMTP');
|
||||
expect(notifications).toContain('use_custom_smtp');
|
||||
expect(notifications).not.toContain("key: 'from'");
|
||||
expect(notifications).not.toContain('注册验证码');
|
||||
});
|
||||
@@ -137,11 +149,26 @@ describe('frontend navigation routing', () => {
|
||||
expect(itemList).not.toContain('src={URL.createObjectURL(file)}');
|
||||
});
|
||||
|
||||
test('QR verification exposes both the external verification link and completion action', () => {
|
||||
test('QR verification removes the external link and clearly requires in-app risk verification', () => {
|
||||
const accounts = readFrontendFile('components/AccountList.tsx');
|
||||
expect(accounts).toContain('href={verificationUrl}');
|
||||
expect(accounts).toContain('rel="noopener noreferrer"');
|
||||
expect(accounts).toContain('onClick={handleCompleteVerification}');
|
||||
expect(accounts).toContain('我已完成验证');
|
||||
const riskPanel = readFrontendFile('components/RiskVerificationPanel.tsx');
|
||||
expect(accounts).not.toContain('href={verificationUrl}');
|
||||
expect(accounts).not.toContain('setVerificationUrl');
|
||||
expect(accounts).toContain('RiskVerificationPanel');
|
||||
expect(riskPanel).toContain('需要完成安全风控验证');
|
||||
expect(riskPanel).toContain('请勿在浏览器中打开验证链接');
|
||||
expect(riskPanel).toContain('系统会自动检测并刷新登录状态');
|
||||
expect(riskPanel).not.toContain('我已在闲鱼 App 完成验证');
|
||||
expect(riskPanel).not.toContain('<button');
|
||||
expect(riskPanel).not.toContain('重试');
|
||||
});
|
||||
|
||||
test('account editor exposes password-login refresh and never renders its verification URL', () => {
|
||||
const accounts = readFrontendFile('components/AccountList.tsx');
|
||||
expect(accounts).toContain('passwordLogin({');
|
||||
expect(accounts).toContain('checkPasswordLoginStatus(sessionId, controller.signal)');
|
||||
expect(accounts).toContain('密码登录刷新授权');
|
||||
expect(accounts).toContain('账号已触发平台风控,需要完成人脸识别');
|
||||
expect(accounts).not.toContain('result.verification_url');
|
||||
});
|
||||
});
|
||||
+194
-25
@@ -2,27 +2,86 @@ import { afterEach, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
addAccount,
|
||||
cancelPasswordLogin,
|
||||
deleteItemPublishBatch,
|
||||
checkPasswordLoginStatus,
|
||||
completeQRVerification,
|
||||
createNotificationChannel,
|
||||
getAccountDetails,
|
||||
getAutomationIssues,
|
||||
getItems,
|
||||
getItemPublishBatches,
|
||||
getNotificationChannels,
|
||||
getOrders,
|
||||
getOrderAnalytics,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getSystemSettings,
|
||||
getValidOrders,
|
||||
logout,
|
||||
importOrders,
|
||||
passwordLogin,
|
||||
resolveAutomationRun,
|
||||
resolveDeferredAutomationTask,
|
||||
syncOrders,
|
||||
updateReplyRule,
|
||||
deleteReplyRule,
|
||||
updateAccountCookie,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountSettings,
|
||||
updateItem,
|
||||
updateNotificationChannel,
|
||||
updateSystemSettings,
|
||||
updateShippingRule,
|
||||
} from './api';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateSystemSettings({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/system-settings', expect.objectContaining({ method: 'PUT', credentials: 'include' }));
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
});
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getItemPublishBatches(10)).resolves.toEqual([{ id: 'batch-1', status: 'running' }]);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items/publish-batches?limit=10', expect.objectContaining({ credentials: 'include' }));
|
||||
});
|
||||
|
||||
test('automation issue APIs expose and resolve quarantined work', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await expect(getAutomationIssues()).resolves.toEqual({ runs: [{ id: 1 }], pending_tasks: [{ id: 2 }] });
|
||||
await resolveAutomationRun(1, 'continue');
|
||||
await resolveDeferredAutomationTask(2, 'retry');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/automation-runs/1/resolve');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ resolution: 'continue' });
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/automation-pending-tasks/2/resolve');
|
||||
});
|
||||
|
||||
test('order multipart requests use the shared authenticated form request path', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await syncOrders('acc1', 'pending_ship');
|
||||
await importOrders(new FormData());
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
|
||||
});
|
||||
|
||||
test('legacy notification channel aliases are normalized for the editor', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 1, name: '旧飞书', type: 'lark', config: 'not-json', enabled: true }])));
|
||||
const result = await getNotificationChannels();
|
||||
expect(result.data?.[0]).toMatchObject({ type: 'feishu', config: {} });
|
||||
});
|
||||
|
||||
const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
@@ -30,30 +89,71 @@ const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), {
|
||||
});
|
||||
|
||||
test('getOrders normalizes backend order fields', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o1', order_status: 'shipped', quantity: '2' }],
|
||||
total: 1,
|
||||
})));
|
||||
const result = await getOrders(undefined, 'all', 1, 20);
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const result = await getOrders(undefined, 'all', 1, 20, ' buyer ');
|
||||
expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 });
|
||||
expect(result.total).toBe(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/orders?page=1&page_size=20&search=buyer', expect.objectContaining({ method: 'GET' }));
|
||||
});
|
||||
|
||||
test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ order_id: 'o-unknown', order_status: 'legacy_status' }],
|
||||
})));
|
||||
const result = await getOrders();
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
});
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
})));
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-480);
|
||||
const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(result).toEqual([expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })]);
|
||||
expect(result).toEqual({
|
||||
orders: [expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })],
|
||||
total: 1,
|
||||
truncated: false,
|
||||
});
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=480');
|
||||
});
|
||||
|
||||
test('completeQRVerification sends target account and mismatch confirmation', async () => {
|
||||
test('getOrderAnalytics sends the browser timezone offset', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ revenue_stats: {}, daily_stats: [], status_stats: [], city_stats: [] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(-330);
|
||||
await getOrderAnalytics({ start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('timezone_offset_minutes=330');
|
||||
});
|
||||
|
||||
test('paid orders are normalized to pending shipment', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ data: [{ order_id: 'o-paid', order_status: 'paid' }] })));
|
||||
const result = await getOrders();
|
||||
expect(result.data[0].status).toBe('pending_ship');
|
||||
});
|
||||
|
||||
test('completeQRVerification sends only the immutable target account', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await completeQRVerification('session-1', 'acc1', true);
|
||||
await completeQRVerification('session-1', 'acc1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/qr-login/complete-verification/session-1', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ target_account_id: 'acc1', confirm_mismatch: true }),
|
||||
body: JSON.stringify({ target_account_id: 'acc1' }),
|
||||
}));
|
||||
});
|
||||
|
||||
test('deleteItemPublishBatch removes an abandoned preview', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await deleteItemPublishBatch('preview-1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items/publish-batches/preview-1', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -87,6 +187,18 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('getItems forwards the selected account filter', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await getItems('account-2');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/items?cookie_id=account-2', expect.objectContaining({
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
|
||||
test('getSystemSettings normalizes numeric renewal retention', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
|
||||
ai_model: 'qwen-plus',
|
||||
@@ -137,6 +249,21 @@ test('account cookie APIs include login_method when provided', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('account editor settings use one aggregate request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountSettings('acc1', {
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
username: 'user', show_browser: true, channel_ids: [1, 2],
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/cookies/acc1/settings', expect.objectContaining({ method: 'PUT' }));
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
remark: 'main', auto_confirm: false, pause_duration: 5,
|
||||
username: 'user', show_browser: true, channel_ids: [1, 2],
|
||||
});
|
||||
});
|
||||
|
||||
test('getAccountDetails normalizes show_browser and never exposes password', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 'acc1',
|
||||
@@ -144,6 +271,8 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
auto_confirm: true,
|
||||
remark: '主账号',
|
||||
pause_duration: 0,
|
||||
paused_until: 1780000000,
|
||||
paused: true,
|
||||
username: 'login-user',
|
||||
show_browser: '1',
|
||||
login_password: 'should-not-leak',
|
||||
@@ -155,6 +284,8 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy
|
||||
username: 'login-user',
|
||||
show_browser: true,
|
||||
login_password: '',
|
||||
paused_until: 1780000000,
|
||||
paused: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -264,6 +395,7 @@ test('getShippingRules exposes buyer reviewed gift rules as automation rules', a
|
||||
|
||||
test('getReplyRules labels keyword matching according to engine contains behavior', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 42,
|
||||
keyword: '发货',
|
||||
reply: '马上安排',
|
||||
type: 'image',
|
||||
@@ -274,6 +406,7 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
const rules = await getReplyRules('acc1');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' }));
|
||||
expect(rules[0]).toMatchObject({
|
||||
id: '42',
|
||||
keyword: '发货',
|
||||
reply_content: '马上安排',
|
||||
match_type: 'fuzzy',
|
||||
@@ -283,29 +416,43 @@ test('getReplyRules labels keyword matching according to engine contains behavio
|
||||
});
|
||||
|
||||
test('updateReplyRule preserves keyword image metadata when saving text edits', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse([
|
||||
{ keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' },
|
||||
{ keyword: '发货', reply: '马上安排', item_id: 'item-1', type: 'text', image_url: '' },
|
||||
]))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true }));
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '1', keyword: '发货', reply_content: '稍后安排' }, 'acc1');
|
||||
await updateReplyRule({ id: '42', keyword: '发货', reply_content: '稍后安排', item_id: 'item-1' }, 'acc1');
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/keywords-with-item-id/acc1', expect.objectContaining({
|
||||
method: 'POST',
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/keywords-with-type/acc1/42', expect.objectContaining({
|
||||
method: 'PUT',
|
||||
credentials: 'include',
|
||||
}));
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
|
||||
keywords: [
|
||||
{ keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' },
|
||||
{ keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '' },
|
||||
],
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('updateReplyRule clears stale content when switching reply type', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateReplyRule({ id: '42', keyword: '发货', type: 'image', image_url: 'https://img.example/new.png' }, 'acc1');
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
|
||||
keyword: '发货', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/new.png',
|
||||
});
|
||||
});
|
||||
|
||||
test('deleteReplyRule deletes one stable keyword row instead of replacing the list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await deleteReplyRule('42', 'acc1');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/keywords-with-type/acc1/42', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
}));
|
||||
});
|
||||
|
||||
test('createNotificationChannel persists email recipient as to_email config', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
@@ -455,6 +602,28 @@ test('updateShippingRule posts every matching card action before confirm shipmen
|
||||
expect(body.actions[1].delay_seconds).toBe(0);
|
||||
});
|
||||
|
||||
test('updateShippingRule preserves text actions while editing card variants', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 4 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await updateShippingRule({
|
||||
id: '4',
|
||||
cookie_id: 'cookie-1',
|
||||
item_id: 'item-1',
|
||||
trigger_type: 'order_paid',
|
||||
variants: [{ spec_name: '', spec_value: '', card_id: 8, delivery_count: 1, enabled: true }],
|
||||
actions: [{ action_type: 'send_text', message_template: '发货提示', enabled: true, sort_order: 2 }],
|
||||
});
|
||||
|
||||
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(body.actions.map((action: { action_type: string }) => action.action_type)).toEqual([
|
||||
'send_card',
|
||||
'send_text',
|
||||
'confirm_shipment',
|
||||
]);
|
||||
expect(body.actions[1].message_template).toBe('发货提示');
|
||||
});
|
||||
|
||||
test('updateShippingRule posts review request text action without card requirement', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
+161
-105
@@ -1,10 +1,11 @@
|
||||
import { get, post, put, del, postForm } from '../request';
|
||||
import { get, post, put, del, postForm, type RequestControlOptions } from '../request';
|
||||
import {
|
||||
LoginResponse, AccountDetail, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction,
|
||||
NotificationChannel, NotificationEventType
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
|
||||
const normalizeSettings = (settings: Record<string, any>): SystemSettings => {
|
||||
const out: Record<string, any> = { ...settings };
|
||||
@@ -60,8 +61,8 @@ const accountAvatarURL = (item: any, version: string): string => {
|
||||
}
|
||||
};
|
||||
|
||||
export const getAccountDetails = async (): Promise<AccountDetail[]> => {
|
||||
const data = await get<any[]>('/cookies/details');
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||
const data = await get<any[]>('/cookies/details', undefined, options);
|
||||
const avatarVersion = Date.now().toString();
|
||||
return data.map(item => ({
|
||||
id: item.id,
|
||||
@@ -72,6 +73,8 @@ export const getAccountDetails = async (): Promise<AccountDetail[]> => {
|
||||
remark: item.remark,
|
||||
note: item.remark,
|
||||
pause_duration: item.pause_duration,
|
||||
paused_until: Number(item.paused_until || 0),
|
||||
paused: item.paused === true,
|
||||
username: item.username || '',
|
||||
login_password: '',
|
||||
show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true',
|
||||
@@ -90,32 +93,29 @@ export interface AccountRuntimeStatus {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export const getAccountRuntimeStatuses = async (): Promise<Record<string, AccountRuntimeStatus>> => {
|
||||
return get('/cookies/runtime-status');
|
||||
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, AccountRuntimeStatus>> => {
|
||||
return get('/cookies/runtime-status', undefined, options);
|
||||
};
|
||||
|
||||
export const generateQRLogin = async (): Promise<{ success: boolean; session_id?: string; qr_code_url?: string }> => {
|
||||
return post('/qr-login/generate');
|
||||
export const generateQRLogin = async (options?: RequestControlOptions): Promise<{ success: boolean; session_id?: string; qr_code_url?: string }> => {
|
||||
return post('/qr-login/generate', undefined, options);
|
||||
};
|
||||
|
||||
export const checkQRLoginStatus = async (sessionId: string): Promise<any> => {
|
||||
return get(`/qr-login/check/${sessionId}`);
|
||||
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<any> => {
|
||||
return get(`/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
export const completeQRVerification = async (
|
||||
sessionId: string,
|
||||
targetAccountId?: string,
|
||||
confirmMismatch = false,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
account_id?: string;
|
||||
scanned_account_id?: string;
|
||||
requires_confirmation?: boolean;
|
||||
message?: string;
|
||||
}> => {
|
||||
return post(`/qr-login/complete-verification/${sessionId}`, {
|
||||
target_account_id: targetAccountId || '',
|
||||
confirm_mismatch: confirmMismatch,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -143,6 +143,35 @@ export const updateAccountCookie = async (id: string, value: string, loginMethod
|
||||
return put(`/cookies/${id}`, { id, value, login_method: loginMethod });
|
||||
};
|
||||
|
||||
export interface AccountSettingsUpdate {
|
||||
cookie?: string;
|
||||
remark?: string;
|
||||
auto_confirm?: boolean;
|
||||
pause_duration?: number;
|
||||
username?: string;
|
||||
login_password?: string;
|
||||
clear_password?: boolean;
|
||||
show_browser?: boolean;
|
||||
channel_ids?: number[];
|
||||
}
|
||||
|
||||
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate): Promise<ApiResponse> => {
|
||||
return put(`/cookies/${id}/settings`, data);
|
||||
};
|
||||
|
||||
export interface LongLoginSettings {
|
||||
can_open_long_login: boolean;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const getLongLoginSettings = async (id: string): Promise<LongLoginSettings> => {
|
||||
return get(`/cookies/${id}/long-login`);
|
||||
};
|
||||
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean): Promise<LongLoginSettings> => {
|
||||
return put(`/cookies/${id}/long-login`, { enabled });
|
||||
};
|
||||
|
||||
export interface PasswordLoginStartResponse {
|
||||
success: boolean;
|
||||
session_id?: string;
|
||||
@@ -172,8 +201,8 @@ export const passwordLogin = async (data: {
|
||||
return post('/password-login', data);
|
||||
};
|
||||
|
||||
export const checkPasswordLoginStatus = async (sessionId: string): Promise<PasswordLoginStatusResponse> => {
|
||||
return get(`/password-login/check/${sessionId}`);
|
||||
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
|
||||
return get(`/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
export const cancelPasswordLogin = async (sessionId: string): Promise<ApiResponse> => {
|
||||
@@ -193,20 +222,30 @@ export const updateAccountLoginInfo = async (id: string, data: {
|
||||
return put(`/cookies/${id}/login-info`, data);
|
||||
};
|
||||
|
||||
export const getAllAISettings = async (): Promise<Record<string, AIReplySettings>> => {
|
||||
return get('/ai-reply-settings');
|
||||
export const getAllAISettings = async (options?: RequestControlOptions): Promise<Record<string, AIReplySettings>> => {
|
||||
return get('/ai-reply-settings', undefined, options);
|
||||
};
|
||||
|
||||
// Orders
|
||||
const normalizeOrderStatus = (value: unknown): Order['status'] => {
|
||||
const status = String(value || '');
|
||||
if (status === 'paid') return 'pending_ship';
|
||||
return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status)
|
||||
? status as Order['status']
|
||||
: 'unknown';
|
||||
};
|
||||
|
||||
export const getOrders = async (
|
||||
cookieId?: string,
|
||||
status?: string,
|
||||
page: number = 1,
|
||||
pageSize: number = 20
|
||||
pageSize: number = 20,
|
||||
search?: string,
|
||||
): Promise<PaginatedResponse<Order>> => {
|
||||
const params: any = { page, page_size: pageSize };
|
||||
if (cookieId) params.cookie_id = cookieId;
|
||||
if (status && status !== 'all') params.status = status;
|
||||
if (search?.trim()) params.search = search.trim();
|
||||
|
||||
const res = await get<any>('/api/orders', params);
|
||||
|
||||
@@ -215,7 +254,7 @@ export const getOrders = async (
|
||||
const orders = rawOrders.map((item: any) => ({
|
||||
...item,
|
||||
id: item.id || item.order_id,
|
||||
status: item.status || item.order_status || 'processing',
|
||||
status: normalizeOrderStatus(item.status || item.order_status),
|
||||
quantity: Number(item.quantity || 1),
|
||||
}));
|
||||
return {
|
||||
@@ -249,46 +288,23 @@ export const syncOrders = async (cookieId?: string, status?: string): Promise<an
|
||||
if (cookieId) formData.append('cookie_id', cookieId);
|
||||
if (status) formData.append('status', status);
|
||||
|
||||
// 使用 fetch 来发送 FormData(Cookie 会话,自动携带凭证)
|
||||
const response = await fetch('/api/orders/refresh', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok || result.success === false) {
|
||||
throw new Error(result.detail || result.message || `订单同步失败: ${response.status}`);
|
||||
}
|
||||
return result;
|
||||
return postForm('/api/orders/refresh', formData);
|
||||
};
|
||||
|
||||
export const syncSingleOrder = async (orderId: string): Promise<any> => {
|
||||
return post(`/api/orders/${orderId}/refresh`);
|
||||
};
|
||||
|
||||
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery', content?: string): Promise<any> => {
|
||||
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<any> => {
|
||||
return post('/api/orders/manual-ship', {
|
||||
order_ids: orderIds,
|
||||
ship_mode: shipMode,
|
||||
custom_content: content
|
||||
});
|
||||
}
|
||||
|
||||
export const importOrders = async (data: Partial<Order>[] | FormData): Promise<any> => {
|
||||
const isFormData = data instanceof FormData;
|
||||
const response = await fetch('/api/orders/import', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: isFormData ? data : JSON.stringify(data)
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok || result.success === false) {
|
||||
throw new Error(result.detail || result.message || `订单导入失败: ${response.status}`);
|
||||
}
|
||||
return result;
|
||||
const isFormData = data instanceof FormData;
|
||||
return isFormData ? postForm('/api/orders/import', data) : post('/api/orders/import', data);
|
||||
}
|
||||
|
||||
// Stats
|
||||
@@ -308,28 +324,43 @@ export const getOrderAnalytics = async (daysOrParams: number | {start_date: stri
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - daysOrParams);
|
||||
params = {
|
||||
start_date: startDate.toISOString().split('T')[0],
|
||||
end_date: endDate.toISOString().split('T')[0]
|
||||
start_date: formatLocalDate(startDate),
|
||||
end_date: formatLocalDate(endDate)
|
||||
};
|
||||
} else {
|
||||
params = daysOrParams;
|
||||
}
|
||||
|
||||
return get('/analytics/orders', params);
|
||||
return get('/analytics/orders', {
|
||||
...params,
|
||||
timezone_offset_minutes: -new Date().getTimezoneOffset(),
|
||||
});
|
||||
}
|
||||
|
||||
export const getValidOrders = async (dateRange: {start_date: string; end_date: string}): Promise<Order[]> => {
|
||||
export interface ValidOrdersResult {
|
||||
orders: Order[];
|
||||
total: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export const getValidOrders = async (dateRange: {start_date: string; end_date: string}): Promise<ValidOrdersResult> => {
|
||||
const res = await get<any>('/analytics/orders/valid', {
|
||||
start_date: dateRange.start_date,
|
||||
end_date: dateRange.end_date
|
||||
end_date: dateRange.end_date,
|
||||
timezone_offset_minutes: -new Date().getTimezoneOffset(),
|
||||
});
|
||||
const orders = Array.isArray(res) ? res : (res.orders || []);
|
||||
return orders.map((order: any) => ({
|
||||
const normalized = orders.map((order: any) => ({
|
||||
...order,
|
||||
id: order.id || order.order_id,
|
||||
status: order.status || order.order_status || 'processing',
|
||||
status: normalizeOrderStatus(order.status || order.order_status),
|
||||
quantity: Number(order.quantity || 1),
|
||||
}));
|
||||
return {
|
||||
orders: normalized,
|
||||
total: Array.isArray(res) ? normalized.length : Number(res.total ?? normalized.length),
|
||||
truncated: Array.isArray(res) ? false : res.truncated === true,
|
||||
};
|
||||
}
|
||||
|
||||
// Cards
|
||||
@@ -395,8 +426,8 @@ export const appendCardData = async (cardId: string | number, content: string):
|
||||
const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
export const getItems = async (): Promise<Item[]> => {
|
||||
const res = await get<any>('/items');
|
||||
export const getItems = async (cookieId?: string): Promise<Item[]> => {
|
||||
const res = await get<any>('/items', cookieId ? { cookie_id: cookieId } : undefined);
|
||||
const items = Array.isArray(res) ? res : (res.items || []);
|
||||
return items.map((item: any) => ({
|
||||
...item,
|
||||
@@ -465,6 +496,15 @@ export const getItemPublishBatch = async (batchId: string): Promise<any> => {
|
||||
return get(`/items/publish-batches/${batchId}`);
|
||||
}
|
||||
|
||||
export const getItemPublishBatches = async (limit = 20): Promise<any[]> => {
|
||||
const res = await get<any>('/items/publish-batches', { limit });
|
||||
return Array.isArray(res) ? res : (res.batches || []);
|
||||
}
|
||||
|
||||
export const deleteItemPublishBatch = async (batchId: string): Promise<any> => {
|
||||
return del(`/items/publish-batches/${batchId}`);
|
||||
}
|
||||
|
||||
export const cancelItemPublishBatch = async (batchId: string): Promise<any> => {
|
||||
return post(`/items/publish-batches/${batchId}/cancel`, {});
|
||||
}
|
||||
@@ -553,8 +593,9 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
|
||||
triggerName[triggerType] || '自动化规则',
|
||||
rule.item_title || rule.item_id || rule.cookie_id || '',
|
||||
].filter(Boolean).join(' - ');
|
||||
const preservedNonCardActions = (rule.actions || []).filter(action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment');
|
||||
const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0
|
||||
? rule.variants.map((variant, index) => ({
|
||||
? [...rule.variants.map((variant, index) => ({
|
||||
action_type: 'send_card' as const,
|
||||
card_id: variant.card_id,
|
||||
delivery_count: variant.delivery_count || 1,
|
||||
@@ -566,7 +607,7 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
|
||||
spec_value: variant.spec_value || '',
|
||||
delay_override: variant.delay_override === true,
|
||||
}),
|
||||
}))
|
||||
})), ...preservedNonCardActions]
|
||||
: (rule.actions && rule.actions.length > 0 ? rule.actions : [{
|
||||
action_type: 'send_card' as const,
|
||||
card_id: rule.card_group_id || 0,
|
||||
@@ -599,8 +640,45 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
|
||||
|
||||
export const deleteShippingRule = async (id: string): Promise<any> => del(`/automation-rules/${id}`);
|
||||
|
||||
export interface AutomationRunIssue {
|
||||
id: number;
|
||||
cookie_id: string;
|
||||
order_id: string;
|
||||
trigger_type: string;
|
||||
error_message: string;
|
||||
issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
|
||||
allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
|
||||
action_cursor: number;
|
||||
sent_count: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface DeferredAutomationIssue {
|
||||
id: number;
|
||||
cookie_id: string;
|
||||
trigger_type: string;
|
||||
error_message: string;
|
||||
attempt_count: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export const getAutomationIssues = async (): Promise<{ runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }> => {
|
||||
const result = await get<any>('/automation-issues');
|
||||
return {
|
||||
runs: Array.isArray(result?.runs) ? result.runs : [],
|
||||
pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [],
|
||||
};
|
||||
};
|
||||
|
||||
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<any> =>
|
||||
post(`/automation-runs/${id}/resolve`, { resolution });
|
||||
|
||||
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<any> =>
|
||||
post(`/automation-pending-tasks/${id}/resolve`, { resolution });
|
||||
|
||||
// Rules - 关键词回复规则 (使用关键词API)
|
||||
type KeywordRowPayload = {
|
||||
id: string;
|
||||
keyword: string;
|
||||
reply: string;
|
||||
item_id: string;
|
||||
@@ -609,6 +687,7 @@ type KeywordRowPayload = {
|
||||
};
|
||||
|
||||
const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
|
||||
id: String(item?.id || ''),
|
||||
keyword: item?.keyword || '',
|
||||
reply: item?.reply || '',
|
||||
item_id: item?.item_id || '',
|
||||
@@ -624,8 +703,8 @@ const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPaylo
|
||||
export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> => {
|
||||
if (!cookieId) return [];
|
||||
const keywords = await getKeywordRowsWithType(cookieId);
|
||||
return keywords.map((item: any, index: number) => ({
|
||||
id: String(index),
|
||||
return keywords.map((item: any) => ({
|
||||
id: item.id,
|
||||
keyword: item.keyword || '',
|
||||
reply_content: item.reply || '',
|
||||
match_type: 'fuzzy' as const,
|
||||
@@ -637,41 +716,21 @@ export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> =>
|
||||
}
|
||||
|
||||
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<any> => {
|
||||
const keywords = await getKeywordRowsWithType(cookieId);
|
||||
|
||||
if (rule.id) {
|
||||
const index = parseInt(rule.id);
|
||||
if (index >= 0 && index < keywords.length) {
|
||||
const current = keywords[index];
|
||||
keywords[index] = {
|
||||
...current,
|
||||
keyword: rule.keyword ?? current.keyword,
|
||||
reply: rule.reply_content ?? current.reply,
|
||||
item_id: rule.item_id ?? current.item_id,
|
||||
type: rule.type ?? current.type,
|
||||
image_url: rule.image_url ?? current.image_url,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
keywords.push({
|
||||
keyword: rule.keyword || '',
|
||||
reply: rule.reply_content || '',
|
||||
item_id: rule.item_id || '',
|
||||
type: rule.type || 'text',
|
||||
image_url: rule.image_url || '',
|
||||
});
|
||||
}
|
||||
|
||||
return post(`/keywords-with-item-id/${cookieId}`, { keywords });
|
||||
const type = rule.type || 'text';
|
||||
const payload = {
|
||||
keyword: rule.keyword || '',
|
||||
reply: type === 'text' ? (rule.reply_content || '') : '',
|
||||
item_id: rule.item_id || '',
|
||||
type,
|
||||
image_url: type === 'image' ? (rule.image_url || '') : '',
|
||||
};
|
||||
return rule.id
|
||||
? put(`/keywords-with-type/${cookieId}/${rule.id}`, payload)
|
||||
: post(`/keywords-with-item-id/${cookieId}`, payload);
|
||||
}
|
||||
|
||||
export const deleteReplyRule = async (id: string, cookieId: string): Promise<any> => {
|
||||
const keywords = await getKeywordRowsWithType(cookieId);
|
||||
const index = parseInt(id);
|
||||
if (index >= 0 && index < keywords.length) {
|
||||
keywords.splice(index, 1);
|
||||
}
|
||||
return post(`/keywords-with-item-id/${cookieId}`, { keywords });
|
||||
return del(`/keywords-with-type/${cookieId}/${id}`);
|
||||
}
|
||||
|
||||
// Settings
|
||||
@@ -681,17 +740,14 @@ export const getSystemSettings = async (): Promise<SystemSettings> => {
|
||||
};
|
||||
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<ApiResponse> => {
|
||||
// API expects individual PUTs, but we'll loop in the service for convenience or assume bulk endpoint if updated
|
||||
// Based on docs 12.2, we iterate.
|
||||
const promises = Object.entries(settings).filter(([, value]) => value !== undefined && value !== null).map(([key, value]) => {
|
||||
return put(`/system-settings/${key}`, { value: String(value) });
|
||||
});
|
||||
await Promise.all(promises);
|
||||
return { success: true, message: 'Settings saved' };
|
||||
const payload = Object.fromEntries(
|
||||
Object.entries(settings).filter(([, value]) => value !== undefined && value !== null),
|
||||
);
|
||||
return put('/system-settings', payload);
|
||||
};
|
||||
|
||||
export const getAccountAISettings = async (cookieId: string): Promise<AIReplySettings> => {
|
||||
return get(`/ai-reply-settings/${cookieId}`);
|
||||
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettings> => {
|
||||
return get(`/ai-reply-settings/${cookieId}`, undefined, options);
|
||||
}
|
||||
|
||||
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>): Promise<ApiResponse> => {
|
||||
@@ -731,19 +787,19 @@ const stringifyNotificationEventTypes = (events?: NotificationEventType[]): stri
|
||||
return clean.length > 0 ? JSON.stringify(clean) : '';
|
||||
};
|
||||
|
||||
export const getNotificationChannels = async (): Promise<{ success: boolean; data?: NotificationChannel[] }> => {
|
||||
const result = await get<any[]>('/notification-channels');
|
||||
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ success: boolean; data?: NotificationChannel[] }> => {
|
||||
const result = await get<any[]>('/notification-channels', undefined, options);
|
||||
const channels = (result || []).map((item: any) => {
|
||||
let parsedConfig;
|
||||
try {
|
||||
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
|
||||
} catch {
|
||||
parsedConfig = undefined;
|
||||
parsedConfig = {};
|
||||
}
|
||||
return {
|
||||
id: String(item.id),
|
||||
name: item.name,
|
||||
type: item.type === 'ding_talk' ? 'dingtalk' : item.type,
|
||||
type: item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type),
|
||||
config: parsedConfig,
|
||||
event_types: parseNotificationEventTypes(item.event_types),
|
||||
enabled: item.enabled,
|
||||
@@ -809,8 +865,8 @@ export const deleteAccountNotifications = async (cookieId: string): Promise<ApiR
|
||||
}
|
||||
|
||||
// 账号 ↔ 渠道 绑定(覆盖式)
|
||||
export const getAccountBindings = async (cookieId: string): Promise<number[]> => {
|
||||
const result = await get<{ cookie_id: string; channel_ids: number[] }>(`/message-notifications/${cookieId}`);
|
||||
export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise<number[]> => {
|
||||
const result = await get<{ cookie_id: string; channel_ids: number[] }>(`/message-notifications/${cookieId}`, undefined, options);
|
||||
return result?.channel_ids || [];
|
||||
}
|
||||
|
||||
|
||||
@@ -26,4 +26,11 @@ describe('normalizeSMTPSettings', () => {
|
||||
smtp_from_address: 'new@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
test('normalizes persisted SMTP transport strings', () => {
|
||||
expect(normalizeSMTPSettings({ smtp_use_tls: 'false', smtp_use_ssl: 'true' })).toMatchObject({
|
||||
smtp_use_tls: false,
|
||||
smtp_use_ssl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,20 @@
|
||||
export const normalizeSMTPSettings = (settings: Record<string, any>): Record<string, any> => {
|
||||
const legacyFrom = String(settings.smtp_from || '').trim();
|
||||
const legacyIsAddress = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(legacyFrom);
|
||||
return {
|
||||
return {
|
||||
...settings,
|
||||
smtp_from_name: settings.smtp_from_name || (legacyIsAddress ? '' : legacyFrom),
|
||||
smtp_from_address: settings.smtp_from_address || (legacyIsAddress ? legacyFrom : settings.smtp_user || ''),
|
||||
};
|
||||
smtp_from_address: settings.smtp_from_address || (legacyIsAddress ? legacyFrom : settings.smtp_user || ''),
|
||||
smtp_use_tls: parseSettingBoolean(settings.smtp_use_tls, true),
|
||||
smtp_use_ssl: parseSettingBoolean(settings.smtp_use_ssl, false),
|
||||
};
|
||||
};
|
||||
|
||||
const parseSettingBoolean = (value: unknown, fallback: boolean): boolean => {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'string') {
|
||||
if (['true', '1', 'yes', 'on'].includes(value.toLowerCase())) return true;
|
||||
if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
@@ -10,13 +10,14 @@
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"moduleResolution": "bundler",
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"allowJs": true,
|
||||
"allowJs": false,
|
||||
"jsx": "react-jsx",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
@@ -26,4 +27,4 @@
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -35,6 +35,8 @@ export interface AccountDetail {
|
||||
remark?: string;
|
||||
note?: string; // alias for remark
|
||||
pause_duration?: number;
|
||||
paused_until?: number;
|
||||
paused?: boolean;
|
||||
// 登录信息
|
||||
username?: string;
|
||||
login_password?: string;
|
||||
@@ -62,7 +64,8 @@ export type OrderStatus =
|
||||
| 'shipped'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| 'refunding';
|
||||
| 'refunding'
|
||||
| 'unknown';
|
||||
|
||||
export interface Order {
|
||||
id: string;
|
||||
@@ -207,6 +210,7 @@ export interface DashboardStats {
|
||||
total_cards: number;
|
||||
total_keywords: number;
|
||||
total_orders: number;
|
||||
available_card_stock: number;
|
||||
}
|
||||
|
||||
export interface OrderAnalytics {
|
||||
@@ -214,7 +218,7 @@ export interface OrderAnalytics {
|
||||
total_amount: number;
|
||||
total_orders: number;
|
||||
};
|
||||
daily_stats: Array<{ date: string; amount: number }>;
|
||||
daily_stats: Array<{ date: string; amount: number; order_count: number }>;
|
||||
item_stats?: Array<{
|
||||
item_id: string;
|
||||
order_count: number;
|
||||
@@ -235,6 +239,9 @@ export interface SystemSettings {
|
||||
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
|
||||
log_format?: 'text' | 'json' | string;
|
||||
renewal_log_retention_days?: number;
|
||||
'captcha.remote_service_url'?: string;
|
||||
'captcha.remote_secret_key'?: string;
|
||||
'captcha.remote_pass_cookies'?: boolean | string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,18 @@ export default defineConfig({
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-issues': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-runs': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-pending-tasks': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/notification-channels': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { UserConfig } from 'vite';
|
||||
import config from './vite.config';
|
||||
|
||||
test('development server proxies every automation API prefix', () => {
|
||||
const proxy = (config as UserConfig).server?.proxy;
|
||||
expect(proxy).toBeDefined();
|
||||
expect(proxy).toHaveProperty('/automation-rules');
|
||||
expect(proxy).toHaveProperty('/automation-issues');
|
||||
expect(proxy).toHaveProperty('/automation-runs');
|
||||
expect(proxy).toHaveProperty('/automation-pending-tasks');
|
||||
});
|
||||
@@ -61,7 +61,11 @@ func (m *Manager) StartAll(ctx context.Context) error {
|
||||
return fmt.Errorf("加载账号失败: %w", err)
|
||||
}
|
||||
for cookieID, cookieValue := range all {
|
||||
if !m.store.Cookies.GetStatus(ctx, cookieID) {
|
||||
enabled, statusErr := m.store.Cookies.Status(ctx, cookieID)
|
||||
if statusErr != nil {
|
||||
return fmt.Errorf("读取账号 %s 启用状态: %w", cookieID, statusErr)
|
||||
}
|
||||
if !enabled {
|
||||
m.logger.Info("账号已禁用,跳过启动", "account", cookieID)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -12,8 +13,34 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/ws"
|
||||
)
|
||||
|
||||
type fakeWSDialer struct{}
|
||||
|
||||
func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) {
|
||||
return fakeWSConn{}, nil
|
||||
}
|
||||
|
||||
type fakeWSConn struct{}
|
||||
|
||||
func (fakeWSConn) Register(context.Context, string, string) error { return nil }
|
||||
func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
func (fakeWSConn) Close() error { return nil }
|
||||
func (fakeWSConn) SendText(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。
|
||||
// refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan
|
||||
// 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。
|
||||
@@ -98,6 +125,7 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri
|
||||
Handler: mgr.handler,
|
||||
Logger: mgr.logger,
|
||||
MTop: mtopClient,
|
||||
WSDialer: fakeWSDialer{},
|
||||
})
|
||||
accCtx, accCancel := context.WithCancel(runCtx)
|
||||
ma := &managedAccount{
|
||||
@@ -332,8 +360,8 @@ func TestRestart(t *testing.T) {
|
||||
t.Fatal("Restart 后应是新实例,不是旧实例")
|
||||
}
|
||||
// 新实例的 CookieStr 应反映最新 DB 值。
|
||||
if newMA.acc.CookieStr != "unb=1; _m_h5_tk=new-refreshed;" {
|
||||
t.Fatalf("新实例 CookieStr=%q want new-refreshed", newMA.acc.CookieStr)
|
||||
if got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=new-refreshed;" {
|
||||
t.Fatalf("新实例 CookieStr=%q want new-refreshed", got)
|
||||
}
|
||||
|
||||
// 旧实例的 done 应已关闭(被 Stop)。
|
||||
@@ -386,8 +414,8 @@ func TestStart_SkipsRunning(t *testing.T) {
|
||||
if after != original {
|
||||
t.Fatal("Start 运行中账号不应替换实例")
|
||||
}
|
||||
if after.acc.CookieStr != "unb=1; _m_h5_tk=t;" {
|
||||
t.Fatalf("实例 CookieStr 不应变,got %q", after.acc.CookieStr)
|
||||
if got := after.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=t;" {
|
||||
t.Fatalf("实例 CookieStr 不应变,got %q", got)
|
||||
}
|
||||
|
||||
mgr.Stop("running-acc")
|
||||
@@ -416,6 +444,9 @@ func TestStart_RestartsExited(t *testing.T) {
|
||||
mgr.mu.Lock()
|
||||
mgr.runCtx = ctx
|
||||
mgr.mu.Unlock()
|
||||
if err := mgr.store.Cookies.Save(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := mgr.Start(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;"); err != nil {
|
||||
t.Fatalf("Start 已退出账号应成功,got %v", err)
|
||||
@@ -428,8 +459,8 @@ func TestStart_RestartsExited(t *testing.T) {
|
||||
if newMA == exitedMA {
|
||||
t.Fatal("应替换为全新实例")
|
||||
}
|
||||
if newMA.acc.CookieStr != "unb=1; _m_h5_tk=brand-new;" {
|
||||
t.Fatalf("新实例 CookieStr=%q want brand-new", newMA.acc.CookieStr)
|
||||
if got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=brand-new;" {
|
||||
t.Fatalf("新实例 CookieStr=%q want brand-new", got)
|
||||
}
|
||||
// done 不应已关闭(新实例在运行)。
|
||||
select {
|
||||
|
||||
+249
-248
@@ -1,12 +1,13 @@
|
||||
// Package adapter 是账号运行时与外部能力(浏览器自动化、通知、自动化中心)的装配层。
|
||||
// Package adapter 是账号运行时与外部能力(风控验证、通知、自动化中心)的装配层。
|
||||
//
|
||||
// 它实现 engine.Handler 与 automation.OrderDetailFetcher,把系统事件转发到自动化中心、
|
||||
// 把订单详情抓取/密码登录刷新接到浏览器、把账号告警推到通知器。业务逻辑集中在此,
|
||||
// 把订单详情抓取/凭证续期接到 Go 协议客户端、把账号告警推到通知器。业务逻辑集中在此,
|
||||
// cmd/server 只负责构造与接线。
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
@@ -20,32 +21,37 @@ import (
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// browserManager 是 adapter 所需的浏览器能力最小契约。*browser.Manager 实现该接口;
|
||||
// 测试可注入桩实现,避免依赖 Chromium。
|
||||
// browserManager 只暴露风控验证能力。普通 Token、Cookie 续期、订单和
|
||||
// WebSocket 流程不得通过 Chromium 实现。
|
||||
type browserManager interface {
|
||||
FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*browser.OrderDetail, error)
|
||||
CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error)
|
||||
PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
|
||||
}
|
||||
|
||||
type browserQuickRenewer interface {
|
||||
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaRecoverer interface {
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaEngineRecoverer interface {
|
||||
TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (cookies, engine string, err error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaSnapshotReader interface {
|
||||
TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (cookies string, snapshot []cookierefresh.BrowserCookie, err error)
|
||||
}
|
||||
|
||||
type tokenCaptchaRequester interface {
|
||||
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
|
||||
}
|
||||
|
||||
type orderDetailClient interface {
|
||||
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
|
||||
}
|
||||
|
||||
// Adapter 实现 engine.Handler 与 automation.OrderDetailFetcher,
|
||||
// 把系统消息、订单详情抓取和密码登录刷新接到浏览器与自动化中心。
|
||||
// 把系统消息、订单详情抓取和协议级凭证续期接到 Go 客户端与自动化中心。
|
||||
//
|
||||
// 自动发货只走 automation.Center;用户聊天消息由 Account 内部 ReplyService 处理,
|
||||
// 故 HandleChatMessage 为空实现。
|
||||
@@ -58,6 +64,7 @@ type Adapter struct {
|
||||
renewSvc xrenew.Service
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
orderMTop orderDetailClient
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
@@ -88,6 +95,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
logger: logger,
|
||||
cooldown: renewal.GlobalCooldown,
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordProcessing: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
@@ -115,6 +123,9 @@ func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
|
||||
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
|
||||
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
|
||||
|
||||
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
|
||||
func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
|
||||
return nil
|
||||
@@ -160,14 +171,7 @@ func classifyAccountAlertEvent(title, body string) string {
|
||||
}
|
||||
|
||||
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (*mtop.RefreshResult, bool) {
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL, deviceID string) (*mtop.RefreshResult, bool) {
|
||||
start := time.Now()
|
||||
var logID int64
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
@@ -196,31 +200,58 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
metadataJSON = d.MetadataJSON
|
||||
}
|
||||
|
||||
freshAccessToken := ""
|
||||
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
|
||||
if a.captchaReq == nil {
|
||||
return "", false, "", nil
|
||||
}
|
||||
deviceID := ""
|
||||
if unb := protocol.TransCookies(currentCookies)["unb"]; unb != "" {
|
||||
deviceID = protocol.GenerateDeviceID(unb)
|
||||
}
|
||||
res, err := a.captchaReq.RequestFreshCaptchaURLContext(runCtx, currentCookies, deviceID)
|
||||
if err != nil || res == nil {
|
||||
return "", false, "", err
|
||||
}
|
||||
freshAccessToken = res.AccessToken
|
||||
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
newCookies, err := br.TokenCaptchaRecover(ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider)
|
||||
newCookies := ""
|
||||
captchaEngine := "playwright"
|
||||
remoteHandled := false
|
||||
captchaHeadless := browser.ResolveHeadless(showBrowser)
|
||||
var err error
|
||||
if remoteConfig := a.loadRemoteCaptchaConfig(ctx); remoteConfig != nil {
|
||||
newCookies, remoteHandled, err = solveRemoteCaptcha(
|
||||
ctx, newRemoteCaptchaHTTPClient(), *remoteConfig,
|
||||
cookieID, verificationURL, cookieStr, deviceID, provider,
|
||||
)
|
||||
if remoteHandled {
|
||||
captchaEngine = "remote"
|
||||
} else if err != nil {
|
||||
a.logger.Warn("远程过滑块不可用,回退本机逻辑", "account", cookieID, "err", err)
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
if !remoteHandled {
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "远程服务不可用且浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return nil, false
|
||||
}
|
||||
if withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
} else {
|
||||
newCookies, err = br.TokenCaptchaRecover(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "failed",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块处理失败,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: "playwright",
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
@@ -232,13 +263,40 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, cookierefresh.MetadataWithoutSnapshot(metadataJSON), time.Now().Unix()); err != nil {
|
||||
var cookieSnapshot []cookierefresh.BrowserCookie
|
||||
snapshotComplete := false
|
||||
if !remoteHandled {
|
||||
if reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
|
||||
if readErr != nil {
|
||||
a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
|
||||
} else {
|
||||
cookieSnapshot = cookierefresh.NormalizeSnapshot(profileSnapshot)
|
||||
if cookieSnapshot == nil {
|
||||
cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
snapshotComplete = true
|
||||
newCookies = profileCookies
|
||||
}
|
||||
}
|
||||
}
|
||||
if !snapshotComplete {
|
||||
if existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
|
||||
snapshotComplete = true
|
||||
}
|
||||
}
|
||||
updatedMetadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshotComplete {
|
||||
updatedMetadata = cookierefresh.MetadataWithSnapshot(metadataJSON, cookieSnapshot)
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, updatedMetadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "error",
|
||||
ProcessingResult: "滑块完成但保存 Cookie 失败",
|
||||
CaptchaEngine: "playwright",
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
@@ -251,14 +309,19 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "success",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块验证成功,已合并 x5sec,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: "playwright",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块验证成功(%s),已更新登录凭证,耗时: %.2f秒", captchaEngine, time.Since(start).Seconds()),
|
||||
CaptchaEngine: captchaEngine,
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
|
||||
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
|
||||
return &mtop.RefreshResult{AccessToken: freshAccessToken, UpdatedCookies: newCookies}, true
|
||||
return &mtop.RefreshResult{
|
||||
UpdatedCookies: newCookies,
|
||||
CookieSnapshot: cookieSnapshot,
|
||||
CookieSnapshotComplete: snapshotComplete,
|
||||
CookieStateChanged: newCookies != cookieStr || snapshotComplete,
|
||||
}, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
@@ -270,14 +333,14 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时启动浏览器,
|
||||
// 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*automation.OrderDetail, error) {
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
|
||||
// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if a.browser == nil {
|
||||
return nil, fmt.Errorf("订单缺少规格/数量信息且浏览器自动化未启用")
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
@@ -296,12 +359,47 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
}
|
||||
}
|
||||
a.lastOrderFetch = time.Now()
|
||||
detail, err := a.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, true)
|
||||
credentialUnlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer credentialUnlock()
|
||||
account, err := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
|
||||
}
|
||||
if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
_ = a.store.Cookies.Save(ctx, cookieID, detail.UpdatedCookies, 0)
|
||||
if account == nil || (strings.TrimSpace(account.Value) == "" && !hasCompleteCookieSnapshot(account.MetadataJSON)) {
|
||||
return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
|
||||
}
|
||||
cookieStr := account.Value
|
||||
var requestCtx context.Context
|
||||
var cookieSession *mtop.CookieSession
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(account.MetadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
if sessionChanged {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, authoritativeSnapshot)
|
||||
}
|
||||
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
}
|
||||
}
|
||||
if fetchErr != nil {
|
||||
return nil, fetchErr
|
||||
}
|
||||
if detail == nil {
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
}
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
@@ -309,7 +407,12 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
}, nil
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的浏览器抓取。
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
|
||||
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
|
||||
order, err := a.store.Orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
@@ -324,88 +427,44 @@ func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automa
|
||||
}, true
|
||||
}
|
||||
|
||||
// OnPasswordLoginRefresh 连续失败时恢复 Cookie。
|
||||
//
|
||||
// 恢复顺序是“轻量续期 -> 浏览器快速续期 -> 密码登录”。轻量续期/快速续期复用旧 Cookie
|
||||
// 刷新登录态;这比账号密码登录更轻,风控压力也更小。
|
||||
// 同一账号冷却 engine.PasswordLoginMinGap,避免短时间反复触发浏览器恢复。
|
||||
// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
|
||||
// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
|
||||
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if ok, remain := cooldown.TryPasswordLogin(cookieID); !ok {
|
||||
a.logger.Warn("密码登录刷新冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", "login_cooldown", fmt.Sprintf("密码登录刷新冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
if ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
|
||||
a.logger.Warn("协议续期冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
if !a.beginPasswordLogin(cookieID) {
|
||||
a.logger.Warn("密码登录刷新已在处理中", "account", cookieID)
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
defer a.finishPasswordLogin(cookieID)
|
||||
|
||||
d, err := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil {
|
||||
a.logger.Warn("密码登录刷新失败:读取账号详情失败", "account", cookieID, "err", err)
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
if a.tryLightRenewBeforePassword(ctx, d) {
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "密码登录前轻量续期成功")
|
||||
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, d)
|
||||
if renewed {
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
|
||||
if latest, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && latest != nil && latest.Value != "" && latest.Value != d.Value {
|
||||
a.logger.Info("密码登录前检测到 DB Cookie 已被外部更新,跳过密码登录", "account", cookieID)
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "cookie_already_updated_externally", "数据库中的 Cookie 已被外部更新,跳过密码登录")
|
||||
return true
|
||||
message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
|
||||
if renewErr != nil {
|
||||
message += ":" + renewErr.Error()
|
||||
}
|
||||
|
||||
if a.browser == nil {
|
||||
a.logger.Warn("密码登录刷新失败:浏览器自动化已禁用,接口轻量续期也未恢复", "account", cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "browser_disabled", "浏览器自动化已禁用,接口轻量续期未恢复")
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" {
|
||||
msg := "账号已掉线且未配置账号密码"
|
||||
a.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID)
|
||||
if err := a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg); err != nil {
|
||||
a.logger.Warn("未配置账号密码时停用账号失败", "account", cookieID, "err", err)
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "no_credentials", "no_credentials", msg)
|
||||
return false
|
||||
}
|
||||
cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
a.handlePasswordLoginError(ctx, cookieID, err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", passwordLoginFailureReason(err), err.Error())
|
||||
return false
|
||||
}
|
||||
cookieStr := browser.MarshalCookies(cookies)
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
a.logger.Warn("密码登录刷新失败:浏览器未返回 cookie", "account", cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "empty_cookies", "浏览器未返回 cookie")
|
||||
return false
|
||||
}
|
||||
if err := a.store.Cookies.Save(ctx, cookieID, cookieStr, d.UserID); err != nil {
|
||||
a.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "cookie_update_failed", err.Error())
|
||||
return false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
_ = a.store.Cookies.MarkLogin(ctx, cookieID, "password", time.Now().Unix())
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "账号密码登录刷新成功")
|
||||
a.logger.Info("密码登录刷新 cookie 成功", "account", cookieID)
|
||||
return true
|
||||
a.logger.Warn("协议续期未恢复账号", "account", cookieID, "err", renewErr)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountOffline, engine.AlertLevelWarn, "账号需要重新扫码", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "qr_login_required", message)
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
@@ -434,7 +493,7 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
|
||||
if err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
CookieID: cookieID,
|
||||
UserID: userID,
|
||||
Method: "password",
|
||||
Method: "protocol",
|
||||
Status: status,
|
||||
Message: truncateMessage(message, 500),
|
||||
TriggerReason: "令牌/Session过期",
|
||||
@@ -444,28 +503,10 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
|
||||
DurationMS: 0,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}); err != nil {
|
||||
a.logger.Warn("记录密码登录日志失败", "account", cookieID, "err", err)
|
||||
a.logger.Warn("记录协议续期日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func passwordLoginFailureReason(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
msg := err.Error()
|
||||
if isPasswordLoginBadCredentials(msg) {
|
||||
return "bad_credentials"
|
||||
}
|
||||
event := browser.PasswordLoginEventFromError(err)
|
||||
if event.Reason != "" {
|
||||
return event.Reason
|
||||
}
|
||||
if event.Status == browser.PasswordLoginStatusVerificationRequired {
|
||||
return "verification_required"
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
|
||||
func truncateMessage(s string, n int) string {
|
||||
if n <= 0 || len(s) <= n {
|
||||
return s
|
||||
@@ -473,147 +514,107 @@ func truncateMessage(s string, n int) string {
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) bool {
|
||||
func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDetail) (bool, error) {
|
||||
if d == nil {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
current := d.Value
|
||||
api := a.renewSvc
|
||||
save := func(cookieStr string) {
|
||||
if strings.TrimSpace(cookieStr) == "" || cookieStr == current {
|
||||
return
|
||||
save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
|
||||
if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
|
||||
return nil
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON), time.Now().Unix()); err != nil {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
|
||||
if completeSnapshot != nil {
|
||||
// API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// 服务端删除和新的 Domain/Path/expiry 属性。
|
||||
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
valueChanged := cookieStr != current
|
||||
current = cookieStr
|
||||
d.Value = cookieStr
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, d.ID)
|
||||
}
|
||||
}
|
||||
apiRenew := func(cookieStr string) (*xrenew.Result, error) {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
return api.RenewAPIFirst(runCtx, cookieStr)
|
||||
}
|
||||
browserRenew := func(cookieStr string) (string, error) {
|
||||
if a.browser == nil {
|
||||
return "", fmt.Errorf("浏览器自动化未启用")
|
||||
}
|
||||
if br, ok := a.browser.(browserQuickRenewer); ok {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
}
|
||||
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return browser.MarshalCookies(m), nil
|
||||
}
|
||||
|
||||
hasLongLogin := strings.TrimSpace(protocol.TransCookies(current)["havana_lgc2_77"]) != ""
|
||||
if hasLongLogin {
|
||||
browserCookies := current
|
||||
if renewed, err := browserRenew(current); err == nil && renewed != "" {
|
||||
browserCookies = renewed
|
||||
save(browserCookies)
|
||||
} else if err != nil {
|
||||
a.logger.Warn("密码登录前浏览器续期失败,继续尝试接口续期", "account", d.ID, "err", err)
|
||||
}
|
||||
if res, err := apiRenew(browserCookies); err == nil && res != nil {
|
||||
save(res.NewCookies)
|
||||
if res.Success {
|
||||
a.logger.Info("密码登录前浏览器+接口续期成功,跳过密码登录", "account", d.ID)
|
||||
return true
|
||||
d.MetadataJSON = metadata
|
||||
if valueChanged && a.store.Tokens != nil {
|
||||
if err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
|
||||
// Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
|
||||
// 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
|
||||
a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
|
||||
}
|
||||
}
|
||||
return false
|
||||
return nil
|
||||
}
|
||||
|
||||
res, err := apiRenew(current)
|
||||
if err == nil && res != nil {
|
||||
save(res.NewCookies)
|
||||
if res.Success {
|
||||
a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
|
||||
return true
|
||||
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
res, err := api.RenewAPIFirst(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
completeSnapshot = res.CookieSnapshot
|
||||
if completeSnapshot == nil {
|
||||
completeSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingProtocolRenew(d.ID, res)
|
||||
// 官网 Promise 超时只记录错误,不把当前登录态判定为失效。
|
||||
return true, nil
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
browserInput := current
|
||||
if res != nil && strings.TrimSpace(res.NewCookies) != "" {
|
||||
browserInput = res.NewCookies
|
||||
}
|
||||
browserCookies, err := browserRenew(browserInput)
|
||||
if err != nil || browserCookies == "" {
|
||||
return false
|
||||
}
|
||||
save(browserCookies)
|
||||
verify, err := apiRenew(browserCookies)
|
||||
if err != nil || verify == nil {
|
||||
return false
|
||||
}
|
||||
save(verify.NewCookies)
|
||||
if verify.Success {
|
||||
a.logger.Info("密码登录前浏览器续期并通过接口验证,跳过密码登录", "account", d.ID)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string, err error) {
|
||||
msg := err.Error()
|
||||
a.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err)
|
||||
if isPasswordLoginDisableError(msg) {
|
||||
_ = a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
if isPasswordLoginBadCredentials(msg) {
|
||||
a.markPasswordError(cookieID)
|
||||
}
|
||||
func (a *Adapter) watchPendingProtocolRenew(cookieID string, result *xrenew.Result) {
|
||||
if result == nil || !result.HasPending() || a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
if isPasswordLoginRetryableVerification(msg) {
|
||||
a.markPasswordError(cookieID)
|
||||
}
|
||||
}
|
||||
|
||||
func isPasswordLoginBadCredentials(msg string) bool {
|
||||
return strings.Contains(msg, "账密错误") ||
|
||||
strings.Contains(msg, "账号密码错误") ||
|
||||
strings.Contains(msg, "用户名或密码错误") ||
|
||||
strings.Contains(msg, "账号或密码错误") ||
|
||||
strings.Contains(msg, "密码错误")
|
||||
}
|
||||
|
||||
func isPasswordLoginDisableError(msg string) bool {
|
||||
return isPasswordLoginBadCredentials(msg) ||
|
||||
strings.Contains(msg, "账号不存在") ||
|
||||
strings.Contains(msg, "账号已被冻结") ||
|
||||
strings.Contains(msg, "账号被冻结") ||
|
||||
strings.Contains(msg, "账户被冻结") ||
|
||||
strings.Contains(msg, "账号已锁定") ||
|
||||
strings.Contains(msg, "账户已锁定") ||
|
||||
strings.Contains(msg, "操作过于频繁") ||
|
||||
strings.Contains(msg, "登录过于频繁") ||
|
||||
strings.Contains(msg, "暂时无法登录")
|
||||
}
|
||||
|
||||
func isPasswordLoginRetryableVerification(msg string) bool {
|
||||
event := browser.PasswordLoginEventFromMessage(msg)
|
||||
return event.Reason == "baxia_punish_captcha" ||
|
||||
event.Status == browser.PasswordLoginStatusVerificationRequired ||
|
||||
strings.Contains(msg, "人工验证") ||
|
||||
strings.Contains(msg, "人脸验证") ||
|
||||
strings.Contains(msg, "身份验证")
|
||||
}
|
||||
|
||||
func (a *Adapter) markPasswordError(cookieID string) {
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
cooldown.MarkPasswordError(cookieID)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("等待协议续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := xrenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.logger.Info("已异步接收协议续期迟到 Cookie", "account", cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("协议续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
|
||||
@@ -8,12 +8,14 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
@@ -53,6 +55,19 @@ type fakeBrowser struct {
|
||||
providerUpdated string
|
||||
}
|
||||
|
||||
type fakeSnapshotBrowser struct {
|
||||
fakeBrowser
|
||||
snapshotCookies string
|
||||
snapshot []cookierefresh.BrowserCookie
|
||||
snapshotErr error
|
||||
snapshotCalls int
|
||||
}
|
||||
|
||||
func (f *fakeSnapshotBrowser) TokenCaptchaCookieSnapshot(context.Context, string, bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
f.snapshotCalls++
|
||||
return f.snapshotCookies, f.snapshot, f.snapshotErr
|
||||
}
|
||||
|
||||
func (f *fakeBrowser) FetchOrderDetail(_ context.Context, _, _, _ string, _ ...bool) (*browser.OrderDetail, error) {
|
||||
return f.fetchDetail, f.fetchErr
|
||||
}
|
||||
@@ -82,6 +97,17 @@ type fakeCaptchaRequester struct {
|
||||
gotDeviceID string
|
||||
}
|
||||
|
||||
type fakeOrderDetailClient struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.calls++
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error) {
|
||||
f.calls++
|
||||
f.gotCookies = cookiesStr
|
||||
@@ -108,8 +134,11 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/hasLogin.do", "/silentHasLogin.do":
|
||||
case "/hasLogin.do":
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
|
||||
case "/silentHasLogin.do":
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
case "/setLoginSettings.do":
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
|
||||
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
|
||||
@@ -184,15 +213,16 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
a.SetTokenCaptchaRequester(req)
|
||||
a.SetNotifier(notifier)
|
||||
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha")
|
||||
const deviceID = "device-for-token-and-captcha"
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha", deviceID)
|
||||
if !ok {
|
||||
t.Fatal("token captcha recovery should succeed")
|
||||
}
|
||||
if result == nil || !strings.Contains(result.UpdatedCookies, "x5sec=ok") {
|
||||
t.Fatalf("returned cookies should contain x5sec: %+v", result)
|
||||
}
|
||||
if result.AccessToken != "fresh-access-token" {
|
||||
t.Fatalf("fresh access token was dropped: %+v", result)
|
||||
if result.AccessToken != "" {
|
||||
t.Fatalf("参考流程不得直接采用重取链接时返回的 token: %+v", result)
|
||||
}
|
||||
if fb.tokenCaptchaCalls != 1 || fb.tokenCaptchaURL != "https://old.example/captcha" {
|
||||
t.Fatalf("browser captcha call mismatch: calls=%d url=%q", fb.tokenCaptchaCalls, fb.tokenCaptchaURL)
|
||||
@@ -200,7 +230,7 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
if fb.providerURL != "https://fresh.example/captcha" || fb.providerUpdated == "" {
|
||||
t.Fatalf("provider result not passed through: url=%q updated=%q", fb.providerURL, fb.providerUpdated)
|
||||
}
|
||||
if req.calls != 1 || req.gotDeviceID == "" {
|
||||
if req.calls != 1 || req.gotDeviceID != deviceID {
|
||||
t.Fatalf("fresh captcha requester not called correctly: calls=%d device=%q", req.calls, req.gotDeviceID)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(ctx, "cid")
|
||||
@@ -224,6 +254,45 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnTokenCaptchaVerificationPersistsExactBrowserJar(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
browserSnapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
|
||||
{Name: "x5sec", Value: "fresh", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true, Expires: float64(time.Now().Add(time.Hour).Unix())},
|
||||
}
|
||||
fb := &fakeSnapshotBrowser{
|
||||
fakeBrowser: fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=fresh"},
|
||||
snapshotCookies: "unb=1; x5sec=fresh",
|
||||
snapshot: browserSnapshot,
|
||||
}
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
a.SetTokenCaptchaRequester(&fakeCaptchaRequester{})
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://passport.goofish.com/punish", "device")
|
||||
if !ok || result == nil || !result.CookieSnapshotComplete || fb.snapshotCalls != 1 {
|
||||
t.Fatalf("result=%+v ok=%v snapshot_calls=%d", result, ok, fb.snapshotCalls)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if !complete || len(saved) != 2 || detail.Value != "unb=1; x5sec=fresh" {
|
||||
t.Fatalf("滑块完整 Jar 未保存: value=%q complete=%v snapshot=%+v", detail.Value, complete, saved)
|
||||
}
|
||||
var exactX5 bool
|
||||
for _, cookie := range saved {
|
||||
if cookie.Name == "x5sec" && cookie.HTTPOnly && cookie.Secure && cookie.Expires > 0 {
|
||||
exactX5 = true
|
||||
}
|
||||
}
|
||||
if !exactX5 {
|
||||
t.Fatalf("x5sec 属性被扁平化: %+v", saved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSystemEvent_UninjectedSafe 未注入 automation 时安全返回 nil。
|
||||
func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
@@ -252,32 +321,33 @@ func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_BrowserNilReturnsError 本地缺字段且浏览器未启用时返回明确错误。
|
||||
func TestFetchOrderDetail_BrowserNilReturnsError(t *testing.T) {
|
||||
// TestFetchOrderDetail_MTopNilReturnsError 本地缺字段且 MTOP 客户端未配置时返回明确错误。
|
||||
func TestFetchOrderDetail_MTopNilReturnsError(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
a := New(store, nil, nil)
|
||||
a.SetOrderDetailClient(nil)
|
||||
_, err := a.FetchOrderDetail(context.Background(), "cid", "o-missing", "item-1", "buyer-1", "cookie")
|
||||
if err == nil {
|
||||
t.Fatal("browser=nil 且本地缺失应返回错误")
|
||||
t.Fatal("MTOP=nil 且本地缺失应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_BrowserFallback 本地缺失但有浏览器时调用浏览器抓取并保存刷新的 cookie。
|
||||
func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
|
||||
// TestFetchOrderDetail_GoMTop 本地缺失时调用 Go MTOP 并保存响应 Cookie。
|
||||
func TestFetchOrderDetail_GoMTop(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(&fakeBrowser{
|
||||
fetchDetail: &browser.OrderDetail{
|
||||
a.SetOrderDetailClient(&fakeOrderDetailClient{
|
||||
detail: &mtop.OrderDetailResult{
|
||||
Quantity: "2", SpecName: "套餐", SpecValue: "30天", Amount: "19.8",
|
||||
UpdatedCookies: "unb=1; _m_h5_tk=newtoken;",
|
||||
},
|
||||
})
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "o-fallback", "item-1", "buyer-1", "old-cookie")
|
||||
if err != nil {
|
||||
t.Fatalf("浏览器兜底应成功: %v", err)
|
||||
t.Fatalf("Go MTOP 应成功: %v", err)
|
||||
}
|
||||
if detail.SpecValue != "30天" || detail.Amount != "19.8" {
|
||||
t.Fatalf("detail=%+v", detail)
|
||||
@@ -289,17 +359,44 @@ func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := New(store, nil, nil)
|
||||
a.SetOrderDetailClient(&fakeOrderDetailClient{detail: &mtop.OrderDetailResult{
|
||||
Quantity: "1", Amount: "9.9", UpdatedCookies: "unb=1; api_only=scoped",
|
||||
}})
|
||||
if _, err := a.FetchOrderDetail(ctx, "cid", "o-jar", "item-1", "buyer-1", "old-cookie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if complete || detail.Value != "unb=1; api_only=scoped" {
|
||||
t.Fatalf("Go MTOP flat cookie not persisted: value=%q complete=%v", detail.Value, complete)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
a := New(store, nil, nil)
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
if !a.OnPasswordLoginRefresh(context.Background(), "cid") {
|
||||
t.Fatal("browser=nil 但接口续期成功时应返回 true")
|
||||
}
|
||||
if !a.OnPasswordLoginRefresh(context.Background(), "cid") {
|
||||
t.Fatal("轻量续期成功不应启动密码登录冷却")
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(context.Background(), "cid")
|
||||
if !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("接口续期 cookie 未保存: %q", saved)
|
||||
@@ -318,8 +415,8 @@ func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing
|
||||
t.Fatal("browser=nil 且接口续期失败时应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(context.Background(), "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "browser_disabled" {
|
||||
t.Fatalf("浏览器不可用应记录 browser_disabled: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || logs[0].Method != "protocol" {
|
||||
t.Fatalf("协议续期失败应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,17 +433,17 @@ func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("账号未配用户名/密码应返回 false")
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("未配置账号密码应自动停用账号,避免持续重试")
|
||||
if !store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("Go 客户端不得因未配置密码停用账号")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "no_credentials" || logs[0].FailureReason != "no_credentials" {
|
||||
t.Fatalf("无凭据应记录 no_credentials 日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserRenewSuccess 无账密时旧 Cookie 仍可快速续期,应保存新 Cookie 并跳过密码登录。
|
||||
func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
|
||||
// TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew 协议失败后不得调用浏览器续期。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -360,30 +457,23 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("快速续期成功应返回 true")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
if fb.renewCalls != 1 {
|
||||
t.Fatalf("CookieRenew 应调用一次,got %d", fb.renewCalls)
|
||||
if fb.renewCalls != 0 {
|
||||
t.Fatalf("不得调用浏览器 CookieRenew,got %d", fb.renewCalls)
|
||||
}
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if !strings.Contains(saved, "_m_h5_tk=renewed") || !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("快速续期 cookie 未保存: %q", saved)
|
||||
}
|
||||
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
|
||||
t.Fatalf("Cookie 更新后应清除旧 token,got %v", err)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("快速续期应记录登录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_Success 配好凭据后浏览器登录成功,cookie 被保存。
|
||||
func TestOnPasswordLoginRefresh_Success(t *testing.T) {
|
||||
// TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin 配好密码也不得启动 Chromium 登录。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -396,26 +486,22 @@ func TestOnPasswordLoginRefresh_Success(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("登录成功应返回 true")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
if fb.loginCalls != 1 {
|
||||
t.Fatalf("PasswordLogin 应调用一次,got %d", fb.loginCalls)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if saved == "" {
|
||||
t.Fatal("刷新的 cookie 应已保存")
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用 Chromium PasswordLogin,got %d", fb.loginCalls)
|
||||
}
|
||||
d, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetDetails: %v", err)
|
||||
}
|
||||
if d.LoginMethod != "password" || d.LastLoginAt == 0 {
|
||||
t.Fatalf("密码登录成功后应标记登录审计字段: %+v", d)
|
||||
if d.LoginMethod == "password" {
|
||||
t.Fatalf("不得标记密码登录: %+v", d)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("密码登录成功应记录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,9 +521,12 @@ func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("登录失败应返回 false")
|
||||
}
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("验证失败后的账密错误冷却期应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "failed" || logs[0].FailureReason != "verification_required" {
|
||||
t.Fatalf("密码登录失败应记录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,8 +546,8 @@ func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
|
||||
t.Fatal("风控失败应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
|
||||
t.Fatalf("baxia 风控应记录专用 failure_reason: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
if !store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("baxia 风控只应冷却,不应停用账号")
|
||||
@@ -480,8 +569,8 @@ func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("冻结账号登录失败应返回 false")
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("冻结账号登录错误应停用账号")
|
||||
if !store.Cookies.GetStatus(ctx, "cid") || fb.loginCalls != 0 {
|
||||
t.Fatal("未执行密码登录时不得按浏览器页面错误停用账号")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,18 +603,18 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("首次应成功")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
// 第二次在冷却期内,应被拒绝且不调用浏览器。
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("冷却期内应返回 false")
|
||||
}
|
||||
if fb.loginCalls != 1 {
|
||||
t.Fatalf("冷却期内不应调用浏览器,got calls=%d", fb.loginCalls)
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("任何一次都不应调用浏览器,got calls=%d", fb.loginCalls)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "login_cooldown" {
|
||||
t.Fatalf("冷却拒绝应记录 skipped_cooldown 日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("协议失败应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
const (
|
||||
remoteCaptchaBrowserTimeout = 20
|
||||
remoteCaptchaResponseLimit = 1 << 20
|
||||
)
|
||||
|
||||
type remoteCaptchaConfig struct {
|
||||
URL string
|
||||
Secret string
|
||||
PassCookies bool
|
||||
}
|
||||
|
||||
type remoteCaptchaStatus uint8
|
||||
|
||||
const (
|
||||
remoteCaptchaFallback remoteCaptchaStatus = iota
|
||||
remoteCaptchaOK
|
||||
remoteCaptchaFailed
|
||||
remoteCaptchaURLExpired
|
||||
)
|
||||
|
||||
type remoteCaptchaResult struct {
|
||||
status remoteCaptchaStatus
|
||||
cookies map[string]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context) *remoteCaptchaConfig {
|
||||
if a.store == nil || a.store.Settings == nil {
|
||||
return nil
|
||||
}
|
||||
urlValue, err := a.store.Settings.Get(ctx, "captcha.remote_service_url")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块地址失败,回退本机逻辑", "err", err)
|
||||
return nil
|
||||
}
|
||||
secret, err := a.store.Settings.Get(ctx, "captcha.remote_secret_key")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块密钥失败,回退本机逻辑", "err", err)
|
||||
return nil
|
||||
}
|
||||
urlValue, secret = strings.TrimSpace(urlValue), strings.TrimSpace(secret)
|
||||
if urlValue == "" || secret == "" {
|
||||
return nil
|
||||
}
|
||||
passCookies, err := a.store.Settings.Get(ctx, "captcha.remote_pass_cookies")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块 Cookie 开关失败,按关闭处理", "err", err)
|
||||
}
|
||||
return &remoteCaptchaConfig{
|
||||
URL: urlValue,
|
||||
Secret: secret,
|
||||
PassCookies: strings.EqualFold(strings.TrimSpace(passCookies), "true"),
|
||||
}
|
||||
}
|
||||
|
||||
func newRemoteCaptchaHTTPClient() *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: dialer.DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 20,
|
||||
MaxIdleConnsPerHost: 4,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
TLSHandshakeTimeout: 8 * time.Second,
|
||||
ResponseHeaderTimeout: 90 * time.Second,
|
||||
},
|
||||
Timeout: 90 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptchaConfig, accountID, verificationURL, cookies, deviceID string) remoteCaptchaResult {
|
||||
payload := map[string]any{
|
||||
"secret_key": cfg.Secret,
|
||||
"account_id": accountID,
|
||||
"url": verificationURL,
|
||||
"browser_timeout": remoteCaptchaBrowserTimeout,
|
||||
}
|
||||
if cfg.PassCookies {
|
||||
payload["cookies"] = cookies
|
||||
payload["device_id"] = deviceID
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: err}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.URL, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: err}
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFallback, err: err}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, remoteCaptchaResponseLimit+1))
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFallback, err: err}
|
||||
}
|
||||
if len(body) > remoteCaptchaResponseLimit {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("远程响应超过 %d 字节", remoteCaptchaResponseLimit)}
|
||||
}
|
||||
var decoded struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Cookies map[string]string `json:"cookies"`
|
||||
URLExpired bool `json:"url_expired"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("解析远程响应: %w", err)}
|
||||
}
|
||||
if decoded.Success && hasX5Cookies(decoded.Data.Cookies) {
|
||||
return remoteCaptchaResult{status: remoteCaptchaOK, cookies: decoded.Data.Cookies}
|
||||
}
|
||||
if decoded.Data.URLExpired {
|
||||
return remoteCaptchaResult{status: remoteCaptchaURLExpired}
|
||||
}
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("远程过滑块未通过(HTTP %d)", resp.StatusCode)}
|
||||
}
|
||||
|
||||
func solveRemoteCaptcha(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
cfg remoteCaptchaConfig,
|
||||
accountID, verificationURL, cookieStr, deviceID string,
|
||||
provider func(context.Context, string) (string, bool, string, error),
|
||||
) (cookies string, handled bool, err error) {
|
||||
currentCookies := cookieStr
|
||||
currentURL := verificationURL
|
||||
for refreshCount := 0; ; {
|
||||
result := callRemoteCaptcha(ctx, client, cfg, accountID, currentURL, currentCookies, deviceID)
|
||||
switch result.status {
|
||||
case remoteCaptchaFallback:
|
||||
return "", false, result.err
|
||||
case remoteCaptchaOK:
|
||||
return mergeX5Cookies(currentCookies, result.cookies), true, nil
|
||||
case remoteCaptchaFailed:
|
||||
return "", true, result.err
|
||||
case remoteCaptchaURLExpired:
|
||||
if provider == nil || refreshCount >= 2 {
|
||||
return "", true, fmt.Errorf("远程反馈验证链接已过期且无法重取")
|
||||
}
|
||||
refreshCount++
|
||||
freshURL, tokenOK, updatedCookies, providerErr := provider(ctx, currentCookies)
|
||||
if providerErr != nil {
|
||||
return "", true, fmt.Errorf("远程验证链接过期后重取失败: %w", providerErr)
|
||||
}
|
||||
if strings.TrimSpace(updatedCookies) != "" {
|
||||
currentCookies = updatedCookies
|
||||
}
|
||||
if tokenOK {
|
||||
return currentCookies, true, nil
|
||||
}
|
||||
if strings.TrimSpace(freshURL) == "" {
|
||||
return "", true, fmt.Errorf("远程验证链接过期后未获取到新链接")
|
||||
}
|
||||
currentURL = freshURL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func hasX5Cookies(cookies map[string]string) bool {
|
||||
for name, value := range cookies {
|
||||
lower := strings.ToLower(strings.TrimSpace(name))
|
||||
if strings.TrimSpace(value) != "" && (strings.HasPrefix(lower, "x5") || strings.Contains(lower, "x5sec")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mergeX5Cookies(original string, incoming map[string]string) string {
|
||||
merged := cookierefresh.ParseCookieString(original)
|
||||
for name, value := range incoming {
|
||||
lower := strings.ToLower(strings.TrimSpace(name))
|
||||
if strings.HasPrefix(lower, "x5") || strings.Contains(lower, "x5sec") {
|
||||
merged[name] = value
|
||||
}
|
||||
}
|
||||
return cookierefresh.MarshalCookieString(merged)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRemoteCaptchaSuccessWorksWithoutLocalBrowser(t *testing.T) {
|
||||
var payload map[string]any
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Errorf("decode payload: %v", err)
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"success":true,"data":{"cookies":{"x5sec":"fresh","other":"must-not-merge"}}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if err := store.Settings.SetMany(ctx, map[string]string{
|
||||
"captcha.remote_service_url": remote.URL,
|
||||
"captcha.remote_secret_key": "remote-secret",
|
||||
"captcha.remote_pass_cookies": "false",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
a := New(store, nil, nil)
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; old=keep", "https://punish.example", "device-private")
|
||||
if !ok || result == nil || !strings.Contains(result.UpdatedCookies, "x5sec=fresh") {
|
||||
t.Fatalf("remote result=%+v ok=%v", result, ok)
|
||||
}
|
||||
if strings.Contains(result.UpdatedCookies, "must-not-merge") {
|
||||
t.Fatalf("非 x5 Cookie 不应从远程结果合入: %q", result.UpdatedCookies)
|
||||
}
|
||||
if payload["secret_key"] != "remote-secret" || payload["account_id"] != "cid" || payload["browser_timeout"] != float64(20) {
|
||||
t.Fatalf("remote payload=%#v", payload)
|
||||
}
|
||||
if _, exists := payload["cookies"]; exists {
|
||||
t.Fatalf("关闭传递 Cookie 时不应发送账号 Cookie: %#v", payload)
|
||||
}
|
||||
if _, exists := payload["device_id"]; exists {
|
||||
t.Fatalf("关闭传递 Cookie 时不应发送设备 ID: %#v", payload)
|
||||
}
|
||||
var status, engineName string
|
||||
if err := store.DB.QueryRowContext(ctx,
|
||||
`SELECT processing_status,captcha_engine FROM risk_control_logs WHERE cookie_id='cid' ORDER BY id DESC LIMIT 1`).
|
||||
Scan(&status, &engineName); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "success" || engineName != "remote" {
|
||||
t.Fatalf("risk log status=%q engine=%q", status, engineName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost(t *testing.T) {
|
||||
var calls int
|
||||
var gotURLs []string
|
||||
var gotCookies []string
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
var payload map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&payload)
|
||||
gotURLs = append(gotURLs, payload["url"].(string))
|
||||
gotCookies = append(gotCookies, payload["cookies"].(string))
|
||||
if calls == 1 {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":true}}`)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"success":true,"data":{"cookies":{"x5sec":"new-x5"}}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
providerCalls := 0
|
||||
provider := func(_ context.Context, current string) (string, bool, string, error) {
|
||||
providerCalls++
|
||||
if current != "unb=1" {
|
||||
t.Fatalf("provider current=%q", current)
|
||||
}
|
||||
return "https://fresh.example", false, "unb=1; _m_h5_tk=fresh", nil
|
||||
}
|
||||
cookies, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret", PassCookies: true,
|
||||
}, "cid", "https://expired.example", "unb=1", "device-1", provider)
|
||||
if err != nil || !handled || !strings.Contains(cookies, "x5sec=new-x5") {
|
||||
t.Fatalf("cookies=%q handled=%v err=%v", cookies, handled, err)
|
||||
}
|
||||
if calls != 2 || providerCalls != 1 || gotURLs[1] != "https://fresh.example" {
|
||||
t.Fatalf("calls=%d provider=%d urls=%v", calls, providerCalls, gotURLs)
|
||||
}
|
||||
if gotCookies[0] != "unb=1" || !strings.Contains(gotCookies[1], "_m_h5_tk=fresh") {
|
||||
t.Fatalf("remote cookies=%v", gotCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCaptchaTokenAlreadyUsableReturnsUpdatedCookies(t *testing.T) {
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":true}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return "", true, "unb=1; _m_h5_tk=renewed", nil
|
||||
}
|
||||
cookies, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret",
|
||||
}, "cid", "https://expired.example", "unb=1", "device", provider)
|
||||
if err != nil || !handled || !strings.Contains(cookies, "_m_h5_tk=renewed") {
|
||||
t.Fatalf("cookies=%q handled=%v err=%v", cookies, handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCaptchaExplicitFailureDoesNotFallbackToBrowser(t *testing.T) {
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":false}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_ = store.Settings.SetMany(ctx, map[string]string{
|
||||
"captcha.remote_service_url": remote.URL, "captcha.remote_secret_key": "secret",
|
||||
})
|
||||
fb := &fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=local"}
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
if result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://punish.example", "device"); ok || result != nil {
|
||||
t.Fatalf("明确远程失败应直接失败: result=%+v ok=%v", result, ok)
|
||||
}
|
||||
if fb.tokenCaptchaCalls != 0 {
|
||||
t.Fatalf("明确远程失败不应回退本机,browser calls=%d", fb.tokenCaptchaCalls)
|
||||
}
|
||||
}
|
||||
|
||||
type failingRoundTripper struct{}
|
||||
|
||||
func (failingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("network unavailable")
|
||||
}
|
||||
|
||||
func TestRemoteCaptchaNetworkErrorRequestsLocalFallback(t *testing.T) {
|
||||
client := &http.Client{Transport: failingRoundTripper{}}
|
||||
_, handled, err := solveRemoteCaptcha(context.Background(), client, remoteCaptchaConfig{
|
||||
URL: "https://remote.example", Secret: "secret",
|
||||
}, "cid", "https://punish.example", "unb=1", "device", nil)
|
||||
if handled || err == nil || !strings.Contains(err.Error(), "network unavailable") {
|
||||
t.Fatalf("handled=%v err=%v", handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCaptchaProviderErrorIsHandledFailure(t *testing.T) {
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":true}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return "", false, "", errors.New("token request failed")
|
||||
}
|
||||
_, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret",
|
||||
}, "cid", "https://expired.example", "unb=1", "device", provider)
|
||||
if !handled || err == nil || !strings.Contains(err.Error(), "token request failed") {
|
||||
t.Fatalf("handled=%v err=%v", handled, err)
|
||||
}
|
||||
}
|
||||
+492
-138
@@ -12,9 +12,31 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
var (
|
||||
errAutomationDeferred = errors.New("自动化动作已持久化等待执行")
|
||||
errAutomationNeedsReview = errors.New("自动化动作结果需要人工核对")
|
||||
)
|
||||
|
||||
type uncertainActionError struct{ err error }
|
||||
|
||||
func (e *uncertainActionError) Error() string { return e.err.Error() }
|
||||
func (e *uncertainActionError) Unwrap() error { return e.err }
|
||||
|
||||
func uncertainAction(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var existing *uncertainActionError
|
||||
if errors.As(err, &existing) {
|
||||
return err
|
||||
}
|
||||
return &uncertainActionError{err: err}
|
||||
}
|
||||
|
||||
// SenderProvider 根据账号 ID 提供当前在线账号的发送能力。
|
||||
// 计划任务和 WS 事件都复用这个抽象,避免自动化中心直接依赖 account.Manager。
|
||||
type SenderProvider interface {
|
||||
@@ -80,28 +102,112 @@ func (c *Center) SetCookieSource(fn func(context.Context, string) (string, error
|
||||
|
||||
// HandleTask 处理一条自动化任务。无匹配规则时安全忽略。
|
||||
func (c *Center) HandleTask(ctx context.Context, task Task) error {
|
||||
_, err := c.handleTask(ctx, task)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
if c == nil || c.store == nil || c.store.Automation == nil {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
task.TriggerType = strings.TrimSpace(task.TriggerType)
|
||||
if task.TriggerType == "" || task.AccountID == "" {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
c.markEventFacts(ctx, task)
|
||||
rules, err := c.store.Automation.Match(ctx, task.AccountID, task.ItemID, task.TriggerType)
|
||||
paused, until, err := c.store.Cookies.IsPaused(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if paused {
|
||||
if err := c.deferTask(ctx, task, until); err != nil {
|
||||
return false, err
|
||||
}
|
||||
c.logger.Info("账号已暂停,自动化事件已持久化等待恢复", "account", task.AccountID, "trigger", task.TriggerType, "due_at", until)
|
||||
return true, nil
|
||||
}
|
||||
enabled, err := c.store.Cookies.Status(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !enabled {
|
||||
c.logger.Info("账号已停用,记录事件事实但不执行自动化", "account", task.AccountID, "trigger", task.TriggerType)
|
||||
return false, nil
|
||||
}
|
||||
var rules []db.AutomationRule
|
||||
if resumeRunID := taskAutomationRunID(task); resumeRunID > 0 {
|
||||
run, runErr := c.store.Automation.GetRun(ctx, resumeRunID)
|
||||
if runErr != nil {
|
||||
return false, runErr
|
||||
}
|
||||
if run.Status != "running" {
|
||||
return false, nil
|
||||
}
|
||||
rule, ruleErr := c.store.Automation.Get(ctx, run.RuleID)
|
||||
if ruleErr != nil {
|
||||
return false, ruleErr
|
||||
}
|
||||
rules = []db.AutomationRule{*rule}
|
||||
} else {
|
||||
rules, err = c.store.Automation.Match(ctx, task.AccountID, task.ItemID, task.TriggerType)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
c.logger.Info("无匹配自动化规则,忽略事件", "trigger", task.TriggerType, "order_id", task.OrderID, "item_id", task.ItemID)
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
var firstErr error
|
||||
for _, rule := range rules {
|
||||
if err := c.executeRule(ctx, task, rule); err != nil {
|
||||
if errors.Is(err, errAutomationDeferred) {
|
||||
return true, nil
|
||||
}
|
||||
c.logger.Error("自动化规则执行失败", "rule_id", rule.ID, "trigger", task.TriggerType, "err", err)
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return false, firstErr
|
||||
}
|
||||
|
||||
func taskAutomationRunID(task Task) int64 {
|
||||
if task.Raw == nil {
|
||||
return 0
|
||||
}
|
||||
value := fmt.Sprint(task.Raw["automation_run_id"])
|
||||
id, _ := strconv.ParseInt(value, 10, 64)
|
||||
return id
|
||||
}
|
||||
|
||||
func taskDelayCursor(task Task) int {
|
||||
if task.Raw == nil {
|
||||
return -1
|
||||
}
|
||||
value := fmt.Sprint(task.Raw["automation_delay_cursor"])
|
||||
cursor, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
return cursor
|
||||
}
|
||||
|
||||
func (c *Center) deferTask(ctx context.Context, task Task, dueAt int64) error {
|
||||
key := buildTriggerKey(task)
|
||||
if key == "" {
|
||||
return fmt.Errorf("暂停期间的自动化事件缺少可持久化防重键")
|
||||
}
|
||||
task.CookieStr = ""
|
||||
raw, err := json.Marshal(task)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.store.Automation.DeferTask(ctx, db.DeferredAutomationTask{
|
||||
TaskKey: task.AccountID + ":" + key, CookieID: task.AccountID,
|
||||
TriggerType: task.TriggerType, TaskJSON: string(raw), DueAt: dueAt,
|
||||
})
|
||||
}
|
||||
|
||||
// ManualFullDelivery 对已存在订单执行完整发货,和付款系统事件共用同一套
|
||||
@@ -113,6 +219,20 @@ func (c *Center) ManualFullDelivery(ctx context.Context, order *db.Order) (int,
|
||||
if strings.TrimSpace(order.OrderID) == "" {
|
||||
return 0, fmt.Errorf("订单缺少订单ID")
|
||||
}
|
||||
paused, until, err := c.store.Cookies.IsPaused(ctx, order.CookieID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("读取账号暂停状态: %w", err)
|
||||
}
|
||||
if paused {
|
||||
return 0, fmt.Errorf("账号暂停处理中,恢复时间 %d", until)
|
||||
}
|
||||
enabled, err := c.store.Cookies.Status(ctx, order.CookieID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("读取账号启用状态: %w", err)
|
||||
}
|
||||
if !enabled {
|
||||
return 0, fmt.Errorf("账号已停用,无法执行完整发货")
|
||||
}
|
||||
if strings.TrimSpace(order.CookieID) == "" {
|
||||
return 0, fmt.Errorf("订单缺少账号ID")
|
||||
}
|
||||
@@ -123,21 +243,22 @@ func (c *Center) ManualFullDelivery(ctx context.Context, order *db.Order) (int,
|
||||
return 0, fmt.Errorf("订单缺少 chat_id 或 buyer_id,无法发送卡券")
|
||||
}
|
||||
task := Task{
|
||||
Source: "manual",
|
||||
AccountID: order.CookieID,
|
||||
TriggerType: TriggerOrderPaid,
|
||||
ChatID: order.ChatID,
|
||||
OrderID: order.OrderID,
|
||||
ItemID: order.ItemID,
|
||||
BuyerID: order.BuyerID,
|
||||
SpecName: order.SpecName,
|
||||
SpecValue: order.SpecValue,
|
||||
Quantity: order.Quantity,
|
||||
Amount: order.Amount,
|
||||
OrderStatus: order.OrderStatus,
|
||||
Raw: map[string]any{"manual": true},
|
||||
Source: "manual",
|
||||
AccountID: order.CookieID,
|
||||
TriggerType: TriggerOrderPaid,
|
||||
ChatID: order.ChatID,
|
||||
OrderID: order.OrderID,
|
||||
ItemID: order.ItemID,
|
||||
BuyerID: order.BuyerID,
|
||||
SpecName: order.SpecName,
|
||||
SpecValue: order.SpecValue,
|
||||
Quantity: order.Quantity,
|
||||
Amount: order.Amount,
|
||||
OrderStatus: order.OrderStatus,
|
||||
ForceConfirmShipment: true,
|
||||
Raw: map[string]any{"manual": true},
|
||||
}
|
||||
task, err := c.prepareTask(ctx, task)
|
||||
task, err = c.prepareTask(ctx, task)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -153,8 +274,50 @@ func (c *Center) ManualFullDelivery(ctx context.Context, order *db.Order) (int,
|
||||
if !hasMatchingSendCard(task, rule.Actions) {
|
||||
continue
|
||||
}
|
||||
n, err := c.executePaidDeliveryActions(ctx, task, rule.Actions)
|
||||
sent += n
|
||||
task.ActionPlan = runnableActions(task, immediateManualActions(rule.Actions))
|
||||
rawTask := task
|
||||
rawTask.CookieStr = ""
|
||||
rawJSON, _ := json.Marshal(rawTask)
|
||||
runID, started, startErr := c.store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||
RuleID: rule.ID,
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
OrderID: task.OrderID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
TriggerType: TriggerOrderPaid,
|
||||
TriggerKey: buildTriggerKey(task),
|
||||
RawEventJSON: string(rawJSON),
|
||||
LeaseExpiresAt: time.Now().UTC().Add(5 * time.Minute).Unix(),
|
||||
})
|
||||
if startErr != nil {
|
||||
return 0, startErr
|
||||
}
|
||||
if !started {
|
||||
return 0, fmt.Errorf("该订单已自动或手动执行过完整发货;如仅需补记状态,请选择仅修改发货状态")
|
||||
}
|
||||
run, getErr := c.store.Automation.GetRun(ctx, runID)
|
||||
if getErr != nil {
|
||||
return 0, getErr
|
||||
}
|
||||
n, deferred, err := c.executeRunActions(ctx, task, rule.ID, run, task.ActionPlan, true)
|
||||
if deferred {
|
||||
return n, errors.New("手动完整发货不应进入延迟队列")
|
||||
}
|
||||
sent = n
|
||||
if errors.Is(err, errAutomationNeedsReview) {
|
||||
return sent, err
|
||||
}
|
||||
status, errMsg := "success", ""
|
||||
if err != nil {
|
||||
status, errMsg = "failed", err.Error()
|
||||
}
|
||||
finishCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
finishErr := c.store.Automation.FinishRun(finishCtx, runID, run.AttemptCount, status, sent, errMsg)
|
||||
cancel()
|
||||
if finishErr != nil {
|
||||
return sent, fmt.Errorf("保存完整发货执行结果: %w", finishErr)
|
||||
}
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
@@ -168,6 +331,23 @@ func (c *Center) ManualFullDelivery(ctx context.Context, order *db.Order) (int,
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func immediateManualActions(actions []db.AutomationAction) []db.AutomationAction {
|
||||
out := make([]db.AutomationAction, len(actions))
|
||||
copy(out, actions)
|
||||
for i := range out {
|
||||
out[i].DelaySeconds = 0
|
||||
if out[i].ActionType != ActionSendCard {
|
||||
continue
|
||||
}
|
||||
cfg := map[string]any{}
|
||||
_ = json.Unmarshal([]byte(out[i].ConfigJSON), &cfg)
|
||||
cfg["delay_override"] = true
|
||||
raw, _ := json.Marshal(cfg)
|
||||
out[i].ConfigJSON = string(raw)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationRule) error {
|
||||
var err error
|
||||
task, err = c.prepareTask(ctx, task)
|
||||
@@ -178,49 +358,190 @@ func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationR
|
||||
if triggerKey == "" {
|
||||
return nil
|
||||
}
|
||||
rawJSON, _ := json.Marshal(task.Raw)
|
||||
runID, started, err := c.store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||
RuleID: rule.ID,
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
OrderID: task.OrderID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
TriggerType: task.TriggerType,
|
||||
TriggerKey: triggerKey,
|
||||
RawEventJSON: string(rawJSON),
|
||||
})
|
||||
if err != nil || !started {
|
||||
return err
|
||||
if len(task.ActionPlan) == 0 {
|
||||
task.ActionPlan = runnableActions(task, rule.Actions)
|
||||
}
|
||||
retryTask := task
|
||||
retryTask.CookieStr = ""
|
||||
rawJSON, _ := json.Marshal(retryTask)
|
||||
var run *db.AutomationRun
|
||||
if resumeID := taskAutomationRunID(task); resumeID > 0 {
|
||||
run, err = c.store.Automation.GetRun(ctx, resumeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if run.Status != "running" || run.RuleID != rule.ID {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
var runID int64
|
||||
var started bool
|
||||
runID, started, err = c.store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||
RuleID: rule.ID, CookieID: task.AccountID, ItemID: task.ItemID, OrderID: task.OrderID,
|
||||
BuyerID: task.BuyerID, ChatID: task.ChatID, TriggerType: task.TriggerType,
|
||||
TriggerKey: triggerKey, RawEventJSON: string(rawJSON),
|
||||
LeaseExpiresAt: time.Now().UTC().Add(5 * time.Minute).Unix(),
|
||||
})
|
||||
if err != nil || !started {
|
||||
return err
|
||||
}
|
||||
run, err = c.store.Automation.GetRun(ctx, runID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
status := "success"
|
||||
errMsg := ""
|
||||
sent := 0
|
||||
sent := run.SentCount
|
||||
finish := true
|
||||
defer func() {
|
||||
_ = c.store.Automation.FinishRun(context.Background(), runID, status, sent, errMsg)
|
||||
if !finish {
|
||||
return
|
||||
}
|
||||
finishCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
if finishErr := c.store.Automation.FinishRun(finishCtx, run.ID, run.AttemptCount, status, sent, errMsg); finishErr != nil {
|
||||
c.logger.Error("保存自动化执行结果失败", "run_id", run.ID, "err", finishErr)
|
||||
}
|
||||
cancel()
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, status, sent, errMsg)
|
||||
}
|
||||
}()
|
||||
if task.TriggerType == TriggerOrderPaid && !hasMatchingSendCard(task, rule.Actions) {
|
||||
actions := task.ActionPlan
|
||||
if task.TriggerType == TriggerOrderPaid && !hasMatchingSendCard(task, actions) {
|
||||
status, errMsg = "failed", "未匹配到订单规格对应的卡密动作"
|
||||
return errors.New(errMsg)
|
||||
}
|
||||
if task.TriggerType == TriggerOrderPaid {
|
||||
sent, err = c.executePaidDeliveryActions(ctx, task, rule.Actions)
|
||||
} else {
|
||||
sent, err = c.executeRuleActions(ctx, task, rule.Actions)
|
||||
var deferred bool
|
||||
sent, deferred, err = c.executeRunActions(ctx, task, rule.ID, run, actions, false)
|
||||
if deferred {
|
||||
finish = false
|
||||
return errAutomationDeferred
|
||||
}
|
||||
if errors.Is(err, errAutomationNeedsReview) {
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, "needs_review", sent, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
if sent > 0 {
|
||||
reason := "运行已完成部分动作,后续动作失败,已禁止从头自动重放: " + err.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, "needs_review", sent, reason)
|
||||
}
|
||||
return fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
|
||||
}
|
||||
status, errMsg = "failed", err.Error()
|
||||
return err
|
||||
}
|
||||
if task.TriggerType == TriggerReviewMissingTimeout && task.OrderID != "" {
|
||||
_ = c.store.Automation.IncrementReviewRequest(ctx, task.OrderID)
|
||||
if incrementErr := c.store.Automation.IncrementReviewRequest(ctx, task.OrderID); incrementErr != nil {
|
||||
reason := "求评价消息已发送,但保存提醒次数失败,已停止自动重放: " + incrementErr.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, "needs_review", sent, reason)
|
||||
}
|
||||
return fmt.Errorf("%w: %v", errAutomationNeedsReview, incrementErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runnableActions(task Task, actions []db.AutomationAction) []db.AutomationAction {
|
||||
out := make([]db.AutomationAction, 0, len(actions))
|
||||
if task.TriggerType == TriggerOrderPaid {
|
||||
for _, action := range actions {
|
||||
if action.Enabled && action.ActionType == ActionSendCard && actionMatchesOrderSpec(task, action) {
|
||||
out = append(out, action)
|
||||
}
|
||||
}
|
||||
for _, action := range actions {
|
||||
if action.Enabled && action.ActionType == ActionConfirmShipment {
|
||||
out = append(out, action)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
for _, action := range actions {
|
||||
if action.Enabled {
|
||||
out = append(out, action)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64, run *db.AutomationRun, actions []db.AutomationAction, skipDelays bool) (int, bool, error) {
|
||||
sent := run.SentCount
|
||||
for cursor := run.ActionCursor; cursor < len(actions); cursor++ {
|
||||
action := actions[cursor]
|
||||
if !skipDelays {
|
||||
delaySeconds, err := c.actionDelaySeconds(ctx, action)
|
||||
if err != nil {
|
||||
return sent, false, err
|
||||
}
|
||||
if delaySeconds > 0 && taskDelayCursor(task) != cursor {
|
||||
if task.Raw == nil {
|
||||
task.Raw = map[string]any{}
|
||||
}
|
||||
task.Raw["automation_run_id"] = run.ID
|
||||
task.Raw["automation_rule_id"] = ruleID
|
||||
task.Raw["automation_delay_cursor"] = cursor
|
||||
dueAt := time.Now().UTC().Add(time.Duration(delaySeconds) * time.Second)
|
||||
if err := c.store.Automation.RenewRunLease(ctx, run.ID, run.AttemptCount, dueAt.Add(5*time.Minute).Unix()); err != nil {
|
||||
return sent, false, err
|
||||
}
|
||||
if err := c.deferTask(ctx, task, dueAt.Unix()); err != nil {
|
||||
return sent, false, err
|
||||
}
|
||||
return sent, true, nil
|
||||
}
|
||||
}
|
||||
started, err := c.store.Automation.StartRunAction(ctx, run.ID, run.AttemptCount, cursor, time.Now().UTC().Add(5*time.Minute).Unix())
|
||||
if err != nil || !started {
|
||||
if err == nil {
|
||||
err = errors.New("自动化动作已被其他 worker 领取")
|
||||
}
|
||||
return sent, false, err
|
||||
}
|
||||
n, actionErr := c.executeActionNow(ctx, task, action)
|
||||
if actionErr != nil {
|
||||
var uncertain *uncertainActionError
|
||||
if n > 0 || errors.As(actionErr, &uncertain) {
|
||||
reason := "外部动作可能已部分或全部执行,已禁止自动重放,请人工核对: " + actionErr.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent+n, reason)
|
||||
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, actionErr)
|
||||
}
|
||||
_ = c.store.Automation.AbortRunAction(ctx, run.ID, run.AttemptCount, cursor)
|
||||
return sent, false, actionErr
|
||||
}
|
||||
if err := c.store.Automation.AdvanceRunAction(ctx, run.ID, run.AttemptCount, cursor, n); err != nil {
|
||||
_ = c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, "动作已执行但检查点保存失败,请人工核对,禁止自动重放: "+err.Error())
|
||||
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
|
||||
}
|
||||
sent += n
|
||||
if task.Raw != nil {
|
||||
delete(task.Raw, "automation_delay_cursor")
|
||||
}
|
||||
}
|
||||
return sent, false, nil
|
||||
}
|
||||
|
||||
func (c *Center) executeActionNow(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
allowed, err := c.accountAutomationAllowed(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !allowed {
|
||||
return 0, fmt.Errorf("账号已暂停或停用,取消自动化动作")
|
||||
}
|
||||
return c.executeAction(ctx, task, action)
|
||||
}
|
||||
|
||||
// notifyResult 根据规则执行结果发送通知。成功且实际发出了内容才通知,
|
||||
// 避免无匹配动作的空跑刷屏;失败时发失败通知。
|
||||
func (c *Center) notifyResult(task Task, status string, sent int, errMsg string) {
|
||||
@@ -244,44 +565,12 @@ func (c *Center) notifyResult(task Task, status string, sent int, errMsg string)
|
||||
c.notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, msg, task.ChatID)
|
||||
}
|
||||
|
||||
func (c *Center) executeRuleActions(ctx context.Context, task Task, actions []db.AutomationAction) (int, error) {
|
||||
sent := 0
|
||||
for _, action := range actions {
|
||||
n, err := c.executeActionWithDelay(ctx, task, action)
|
||||
sent += n
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
func (c *Center) notifyRunNeedsReview(run db.AutomationRun, reason string) {
|
||||
if c == nil || c.notifier == nil {
|
||||
return
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (c *Center) executePaidDeliveryActions(ctx context.Context, task Task, actions []db.AutomationAction) (int, error) {
|
||||
// 同一商品或同一规格允许配置多条发货内容:先按顺序执行全部匹配的
|
||||
// send_card 动作,任意一条失败都停止,只有全部成功后才确认发货。
|
||||
sent := 0
|
||||
for _, action := range actions {
|
||||
if action.ActionType != ActionSendCard || !actionMatchesOrderSpec(task, action) {
|
||||
continue
|
||||
}
|
||||
n, err := c.executeActionWithDelay(ctx, task, action)
|
||||
sent += n
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
}
|
||||
if sent == 0 {
|
||||
return 0, errors.New("未匹配到订单规格对应的卡密动作")
|
||||
}
|
||||
for _, action := range actions {
|
||||
if action.ActionType != ActionConfirmShipment {
|
||||
continue
|
||||
}
|
||||
if _, err := c.executeActionWithDelay(ctx, task, action); err != nil {
|
||||
return sent, err
|
||||
}
|
||||
}
|
||||
return sent, nil
|
||||
task := Task{AccountID: run.CookieID, BuyerID: run.BuyerID, ItemID: run.ItemID, ChatID: run.ChatID, OrderID: run.OrderID, TriggerType: run.TriggerType}
|
||||
c.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason)
|
||||
}
|
||||
|
||||
func hasMatchingSendCard(task Task, actions []db.AutomationAction) bool {
|
||||
@@ -293,22 +582,6 @@ func hasMatchingSendCard(task Task, actions []db.AutomationAction) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Center) executeActionWithDelay(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
if !action.Enabled {
|
||||
return 0, nil
|
||||
}
|
||||
delaySeconds, err := c.actionDelaySeconds(ctx, action)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if delaySeconds > 0 {
|
||||
if err := sleepCtx(ctx, time.Duration(delaySeconds)*time.Second); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return c.executeAction(ctx, task, action)
|
||||
}
|
||||
|
||||
// actionDelaySeconds 统一卡密默认延时和动作覆盖语义。旧动作没有
|
||||
// delay_override 字段时自动使用卡密上的默认延时。
|
||||
func (c *Center) actionDelaySeconds(ctx context.Context, action db.AutomationAction) (int, error) {
|
||||
@@ -319,13 +592,16 @@ func (c *Center) actionDelaySeconds(ctx context.Context, action db.AutomationAct
|
||||
DelayOverride bool `json:"delay_override"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(action.ConfigJSON), &cfg)
|
||||
if cfg.DelayOverride {
|
||||
return action.DelaySeconds, nil
|
||||
}
|
||||
card, err := c.store.Cards.Get(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !card.Enabled {
|
||||
return 0, fmt.Errorf("卡密组 %d 已停用", card.ID)
|
||||
}
|
||||
if cfg.DelayOverride {
|
||||
return action.DelaySeconds, nil
|
||||
}
|
||||
return card.DelaySeconds, nil
|
||||
}
|
||||
|
||||
@@ -437,7 +713,10 @@ func (c *Center) executeAction(ctx context.Context, task Task, action db.Automat
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return 0, nil
|
||||
}
|
||||
return 1, c.sendText(ctx, task, text)
|
||||
if err := c.sendText(ctx, task, text); err != nil {
|
||||
return 0, uncertainAction(err)
|
||||
}
|
||||
return 1, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("未知自动化动作: %s", action.ActionType)
|
||||
}
|
||||
@@ -448,41 +727,107 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
return fmt.Errorf("确认发货缺少订单ID")
|
||||
}
|
||||
enabled, err := c.store.Cookies.GetAutoConfirm(ctx, task.AccountID)
|
||||
if err == nil && !enabled {
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取自动确认发货设置: %w", err)
|
||||
}
|
||||
if !enabled && !task.ForceConfirmShipment {
|
||||
return nil
|
||||
}
|
||||
cookieStr := task.CookieStr
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
cookieStr, err = c.cookieValue(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}
|
||||
ok, ret, updated, err := c.mtop.ConsignContext(ctx, cookieStr, task.OrderID)
|
||||
}()
|
||||
detail, err := c.store.Cookies.GetDetails(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if updated != "" && updated != cookieStr {
|
||||
_ = c.store.Cookies.Save(ctx, task.AccountID, updated, 0)
|
||||
if c.senders != nil {
|
||||
if sender, running := c.senders.Sender(task.AccountID); running {
|
||||
sender.UpdateCookie(updated)
|
||||
}
|
||||
if detail == nil {
|
||||
return db.ErrNotFound
|
||||
}
|
||||
_, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if strings.TrimSpace(detail.Value) == "" && !completeSnapshot {
|
||||
return fmt.Errorf("账号 %s Cookie 为空", task.AccountID)
|
||||
}
|
||||
cookieStr := detail.Value
|
||||
var mtopCtx context.Context
|
||||
var cookieSession *mtop.CookieSession
|
||||
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
|
||||
mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
ok, ret, updated, callErr := c.mtop.ConsignContext(mtopCtx, cookieStr, task.OrderID)
|
||||
var persistenceErrs []error
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
// 完整 Jar 已接管时,即使响应没有 Cookie 变化,也不能因扁平字符串
|
||||
// 格式差异回退覆盖并清除 Jar。
|
||||
sessionHandled := snapshot != nil
|
||||
if changed {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
|
||||
}
|
||||
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr))
|
||||
} else if value != cookieStr {
|
||||
runtimeCookie = value
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr {
|
||||
// 注入 mock 或没有权威快照的历史账号保留扁平
|
||||
// Cookie 兼容路径;扁平结果无法维护旧 Jar 的作用域,
|
||||
// 因此不得继续保留可能已过期的 snapshot。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
|
||||
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
|
||||
} else {
|
||||
runtimeCookie = updated
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if runtimeCookieChanged && c.senders != nil {
|
||||
if sender, running := c.senders.Sender(task.AccountID); running {
|
||||
sender.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
}
|
||||
if callErr != nil {
|
||||
if len(persistenceErrs) > 0 {
|
||||
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return uncertainAction(callErr)
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
|
||||
failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(failure, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return failure
|
||||
}
|
||||
sysShip := true
|
||||
_ = c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
if upsertErr := c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
OrderStatus: "shipped",
|
||||
SystemShipped: &sysShip,
|
||||
})
|
||||
_ = c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at")
|
||||
}); upsertErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr))
|
||||
}
|
||||
if eventErr := c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr))
|
||||
}
|
||||
if len(persistenceErrs) > 0 {
|
||||
return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -498,6 +843,9 @@ func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAc
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !card.Enabled {
|
||||
return 0, fmt.Errorf("卡密组 %d 已停用", card.ID)
|
||||
}
|
||||
if card.Type == "data" {
|
||||
return c.sendDataCard(ctx, task, card, count)
|
||||
}
|
||||
@@ -509,14 +857,17 @@ func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAc
|
||||
}
|
||||
if imageURL != "" {
|
||||
if err := c.sendImage(ctx, task, imageURL, card.ID); err != nil {
|
||||
return sent, err
|
||||
return sent, uncertainAction(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
return sent, err
|
||||
return sent, uncertainAction(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" {
|
||||
return sent, fmt.Errorf("卡密组 %d 没有可发送内容", card.ID)
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
@@ -527,23 +878,34 @@ func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull,
|
||||
defer unlock()
|
||||
sent := 0
|
||||
for i := 0; i < count; i++ {
|
||||
content, snapshot, err := c.store.Cards.FirstBatchData(ctx, card.ID)
|
||||
content, err := c.store.Cards.ConsumeBatchData(ctx, card.ID)
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
return sent, err
|
||||
// 发送接口报错时无法判断远端是否已经收到。恢复库存会让同一卡密
|
||||
// 再次被消费,因此保守地保留已消费状态并交给人工核对。
|
||||
return sent, uncertainAction(err)
|
||||
}
|
||||
}
|
||||
if err := c.store.Cards.CommitFirstBatchData(ctx, card.ID, snapshot); err != nil {
|
||||
return sent, err
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) (bool, error) {
|
||||
paused, _, err := c.store.Cookies.IsPaused(ctx, accountID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("读取账号暂停状态: %w", err)
|
||||
}
|
||||
enabled, err := c.store.Cookies.Status(ctx, accountID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("读取账号启用状态: %w", err)
|
||||
}
|
||||
return !paused && enabled, nil
|
||||
}
|
||||
|
||||
func (c *Center) lockCard(cardID int64) func() {
|
||||
raw, _ := c.cardLocks.LoadOrStore(cardID, &sync.Mutex{})
|
||||
mu := raw.(*sync.Mutex)
|
||||
@@ -557,7 +919,7 @@ func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool {
|
||||
SpecValue string `json:"spec_value"`
|
||||
}
|
||||
if json.Unmarshal([]byte(action.ConfigJSON), &cfg) != nil {
|
||||
return true
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(cfg.SpecName) == "" && strings.TrimSpace(cfg.SpecValue) == "" {
|
||||
return true
|
||||
@@ -593,6 +955,9 @@ func parsePositiveInt(raw string) int {
|
||||
func (c *Center) cardContent(ctx context.Context, card *db.CardFull) (text, imageURL string, err error) {
|
||||
switch card.Type {
|
||||
case "text":
|
||||
if strings.TrimSpace(card.TextContent) == "" {
|
||||
return "", "", fmt.Errorf("文本卡密组缺少内容")
|
||||
}
|
||||
return card.TextContent, "", nil
|
||||
case "data":
|
||||
return "", "", fmt.Errorf("data 卡密必须通过 sendDataCard 发送")
|
||||
@@ -706,14 +1071,3 @@ func renderTemplate(tpl string, task Task) string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package automation
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
@@ -85,11 +87,11 @@ func TestCenterConfirmShipment_MockMTopConsigError(t *testing.T) {
|
||||
if order.SystemShipped {
|
||||
t.Fatal("consign 失败不应写 system_shipped=1")
|
||||
}
|
||||
// automation_runs 应记录失败状态 + 错误信息。
|
||||
// 网络错误无法确认远端是否已经发货,必须进入人工核对而不是自动重试。
|
||||
var runStatus, runErr string
|
||||
store.DB.QueryRowContext(ctx, `SELECT status, error_message FROM automation_runs WHERE order_id='order-mock'`).Scan(&runStatus, &runErr)
|
||||
if runStatus != "failed" {
|
||||
t.Fatalf("run status=%q want failed", runStatus)
|
||||
if runStatus != "needs_review" {
|
||||
t.Fatalf("run status=%q want needs_review", runStatus)
|
||||
}
|
||||
if runErr == "" {
|
||||
t.Fatal("失败 run 应记录错误信息")
|
||||
@@ -109,3 +111,114 @@ func TestCenterConfirmShipment_MockMTopConsigError(t *testing.T) {
|
||||
t.Fatalf("ok=false 应记 failed,got %q", runStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if err := store.Orders.Upsert(ctx, "persist-failure", db.OrderUpsertOpts{CookieID: "cid", ItemID: "item-1", BuyerID: "buyer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_shipped_state
|
||||
BEFORE UPDATE OF system_shipped ON orders
|
||||
WHEN NEW.system_shipped=1
|
||||
BEGIN SELECT RAISE(FAIL, 'forced shipment persistence failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mtopMock := &fakeMTop{consignOk: true, consignUpdated: "unb=123; _m_h5_tk=updated_1;"}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetMTop(mtopMock)
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "persist-failure", ItemID: "item-1", BuyerID: "buyer", ChatID: "chat",
|
||||
})
|
||||
var uncertain *uncertainActionError
|
||||
if !errors.As(err, &uncertain) {
|
||||
t.Fatalf("known remote success with local failure must be quarantined, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "闲鱼已确认发货") || !strings.Contains(err.Error(), "本地状态保存失败") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
order, getErr := store.Orders.Get(ctx, "persist-failure")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if order.SystemShipped {
|
||||
t.Fatal("failed local write must not be reported as persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentKeepsAuthoritativeSnapshotWhenSessionUnchanged(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
initial := "unb=123; _m_h5_tk=old_1;"
|
||||
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, metadata, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := "unb=123; _m_h5_tk=mock_new_2;"
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
|
||||
t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
|
||||
}
|
||||
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if detail.Value != initial {
|
||||
t.Fatalf("完整 Jar 未变化时不得被扁平/mock 返回覆盖: %q", detail.Value)
|
||||
}
|
||||
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); !ok || len(snapshot) != 2 {
|
||||
t.Fatalf("完整 Jar 未变化时必须继续保留: ok=%v snapshot=%+v metadata=%s", ok, snapshot, detail.MetadataJSON)
|
||||
}
|
||||
if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
|
||||
t.Fatalf("保留 snapshot 时丢失其他 metadata: %s", detail.MetadataJSON)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 0 {
|
||||
t.Fatalf("被忽略的扁平/mock 返回不得同步运行实例: %+v", sender.cookieUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
initial := "unb=123; _m_h5_tk=old_1;"
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, `{"preserved":true}`, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := "unb=123; _m_h5_tk=mock_new_2;"
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
|
||||
t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
|
||||
}
|
||||
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if detail.Value != updated {
|
||||
t.Fatalf("无完整 Jar 时未保留扁平/mock 写回路径: %q", detail.Value)
|
||||
}
|
||||
if _, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
|
||||
t.Fatalf("扁平 mock 结果不得伪装成权威 Jar: %s", detail.MetadataJSON)
|
||||
}
|
||||
if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
|
||||
t.Fatalf("扁平写回时丢失其他 metadata: %s", detail.MetadataJSON)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != updated {
|
||||
t.Fatalf("扁平/mock 更新未同步运行实例: %+v", sender.cookieUpdates)
|
||||
}
|
||||
}
|
||||
@@ -2,36 +2,88 @@ package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
type automationRoundTripperFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f automationRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
type testSenderProvider struct{ sender *testSender }
|
||||
|
||||
func (p testSenderProvider) Sender(string) (MessageSender, bool) { return p.sender, true }
|
||||
|
||||
type testSender struct {
|
||||
texts []string
|
||||
events *[]string
|
||||
texts []string
|
||||
cookieUpdates []string
|
||||
onCookieUpdate func(string)
|
||||
events *[]string
|
||||
err error
|
||||
failAfter int
|
||||
}
|
||||
|
||||
func (s *testSender) SendText(_ context.Context, _, _, text string) error {
|
||||
if s.err != nil && (s.failAfter == 0 || len(s.texts) >= s.failAfter) {
|
||||
return s.err
|
||||
}
|
||||
s.texts = append(s.texts, text)
|
||||
if s.events != nil {
|
||||
*s.events = append(*s.events, "send:"+text)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPartialAutomationRunIsQuarantined(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "partial", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendText, MessageTemplate: "first", Enabled: true, SortOrder: 1},
|
||||
{ActionType: "unknown", Enabled: true, SortOrder: 2},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "partial-order", ChatID: "chat", BuyerID: "buyer"}); err == nil {
|
||||
t.Fatal("partial execution should return an error")
|
||||
}
|
||||
var status string
|
||||
var sent int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status,sent_count FROM automation_runs WHERE order_id='partial-order'`).Scan(&status, &sent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "needs_review" || sent != 1 || len(sender.texts) != 1 {
|
||||
t.Fatalf("status=%s sent=%d texts=%v", status, sent, sender.texts)
|
||||
}
|
||||
}
|
||||
func (s *testSender) SendImage(context.Context, string, string, string, int64) error { return nil }
|
||||
func (s *testSender) UpdateCookie(string) {}
|
||||
func (s *testSender) UpdateCookie(cookieStr string) {
|
||||
s.cookieUpdates = append(s.cookieUpdates, cookieStr)
|
||||
if s.onCookieUpdate != nil {
|
||||
s.onCookieUpdate(cookieStr)
|
||||
}
|
||||
}
|
||||
|
||||
type testFetcher struct{ detail *OrderDetail }
|
||||
|
||||
@@ -83,6 +135,289 @@ func TestActionDelayUsesCardDefaultUnlessOverridden(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestActionDelayRejectsDisabledCardAndEmptyTextCard(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
disabledID, err := store.Cards.Create(ctx, &db.CardFull{Name: "disabled", Type: "text", TextContent: "x", Enabled: false, UserID: admin.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
center := New(store, nil, nil)
|
||||
if _, err := center.actionDelaySeconds(ctx, db.AutomationAction{ActionType: ActionSendCard, CardID: disabledID}); err == nil {
|
||||
t.Fatal("disabled card must not be executed")
|
||||
}
|
||||
if _, _, err := center.cardContent(ctx, &db.CardFull{ID: 99, Type: "text", Enabled: true}); err == nil {
|
||||
t.Fatal("empty text card must not produce a successful send")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendDataCardKeepsConsumedInventoryWhenDeliveryResultIsUncertain(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
cardID, err := store.Cards.Create(ctx, &db.CardFull{
|
||||
Name: "data", Type: "data", DataContent: "secret-1\nsecret-2", Enabled: true, UserID: admin.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{err: errors.New("temporary send failure")}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
_, err = center.sendCard(ctx, Task{AccountID: "cid", ChatID: "chat", BuyerID: "buyer"}, db.AutomationAction{
|
||||
ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, ConfigJSON: `{}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("send failure must be returned")
|
||||
}
|
||||
reserved, err := store.Cards.ConsumeBatchData(ctx, cardID)
|
||||
if err != nil || reserved != "secret-2" {
|
||||
t.Fatalf("uncertain send must not expose the same secret again: got=%q err=%v", reserved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCenterSkipsPausedAccountTasks(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "paused", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "must-not-send", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Cookies.SetPause(ctx, "cid", 10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "paused-order", ChatID: "chat", BuyerID: "buyer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sender.texts) != 0 {
|
||||
t.Fatalf("paused account sent messages: %v", sender.texts)
|
||||
}
|
||||
if _, err := store.Orders.Get(ctx, "paused-order"); err != nil {
|
||||
t.Fatalf("paused event facts must be persisted, got %v", err)
|
||||
}
|
||||
if _, err := center.ManualFullDelivery(ctx, &db.Order{OrderID: "manual", CookieID: "cid"}); err == nil {
|
||||
t.Fatal("manual full delivery must reject a paused account")
|
||||
}
|
||||
if _, err := store.Cookies.SetPause(ctx, "cid", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
(&Scheduler{center: center}).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "must-not-send" {
|
||||
t.Fatalf("deferred event was not replayed exactly once: %v", sender.texts)
|
||||
}
|
||||
(&Scheduler{center: center}).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 1 {
|
||||
t.Fatalf("deferred event replay was not idempotent: %v", sender.texts)
|
||||
}
|
||||
if err := store.Cookies.SetStatus(ctx, "cid", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "disabled-order", ChatID: "chat"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sender.texts) != 1 {
|
||||
t.Fatalf("disabled account sent messages: %v", sender.texts)
|
||||
}
|
||||
if _, err := center.ManualFullDelivery(ctx, &db.Order{OrderID: "disabled-manual", CookieID: "cid"}); err == nil {
|
||||
t.Fatal("manual full delivery must reject a disabled account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelayedAutomationIsPersistedAndReplayedWithoutSleeping(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "delayed", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "delayed-message", DelaySeconds: 30, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
start := time.Now()
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "delay-order", ChatID: "chat", BuyerID: "buyer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) > time.Second || len(sender.texts) != 0 {
|
||||
t.Fatalf("delayed task blocked or sent immediately: elapsed=%s texts=%v", time.Since(start), sender.texts)
|
||||
}
|
||||
var pending int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_pending_tasks WHERE status='pending'`).Scan(&pending); err != nil || pending != 1 {
|
||||
t.Fatalf("pending=%d err=%v", pending, err)
|
||||
}
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`)
|
||||
(&Scheduler{center: center}).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "delayed-message" {
|
||||
t.Fatalf("replayed texts=%v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleActionDelaysPreserveSequentialSemantics(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "sequential", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendText, MessageTemplate: "first", DelaySeconds: 0, Enabled: true, SortOrder: 1},
|
||||
{ActionType: ActionSendText, MessageTemplate: "second", DelaySeconds: 30, Enabled: true, SortOrder: 2},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "seq-order", ChatID: "chat", BuyerID: "buyer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "first" {
|
||||
t.Fatalf("first action was not immediate: %v", sender.texts)
|
||||
}
|
||||
var cursor int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT action_cursor FROM automation_runs WHERE order_id='seq-order'`).Scan(&cursor); err != nil || cursor != 1 {
|
||||
t.Fatalf("cursor=%d err=%v", cursor, err)
|
||||
}
|
||||
if err := store.Automation.Update(ctx, admin.ID, ruleID, db.AutomationRuleInput{
|
||||
CookieID: "cid", Name: "changed", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendText, MessageTemplate: "inserted", Enabled: true, SortOrder: 1},
|
||||
{ActionType: ActionSendText, MessageTemplate: "changed-second", Enabled: true, SortOrder: 2},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`)
|
||||
(&Scheduler{center: center}).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 2 || sender.texts[1] != "second" {
|
||||
t.Fatalf("second action was not replayed: %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredRunDuringExternalActionIsQuarantined(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
ruleID, _ := store.Automation.Create(ctx, db.AutomationRuleInput{UserID: admin.ID, CookieID: "cid", Name: "crash", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "must-not-repeat", Enabled: true}}})
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "crash-order", ChatID: "chat", BuyerID: "buyer"}
|
||||
raw, _ := json.Marshal(task)
|
||||
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{RuleID: ruleID, CookieID: "cid", OrderID: "crash-order",
|
||||
TriggerType: TriggerBuyerReviewed, TriggerKey: buildTriggerKey(task), RawEventJSON: string(raw), LeaseExpiresAt: time.Now().Add(time.Minute).Unix()})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start=%v err=%v", started, err)
|
||||
}
|
||||
if ok, err := store.Automation.StartRunAction(ctx, runID, 1, 0, time.Now().Add(-time.Minute).Unix()); err != nil || !ok {
|
||||
t.Fatalf("start action=%v err=%v", ok, err)
|
||||
}
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID)
|
||||
sender := &testSender{}
|
||||
(&Scheduler{center: New(store, testSenderProvider{sender: sender}, nil)}).runRecoveryTasks(ctx)
|
||||
run, _ := store.Automation.GetRun(ctx, runID)
|
||||
if run.Status != "needs_review" || len(sender.texts) != 0 {
|
||||
t.Fatalf("run=%+v texts=%v", run, sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidDeferredTaskMovesToDeadLetter(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO automation_pending_tasks
|
||||
(task_key,cookie_id,trigger_type,task_json,due_at,status,attempt_count,lease_expires_at,error_message)
|
||||
VALUES ('cid:bad','cid',?,'{"broken',0,'pending',0,0,'')`, TriggerBuyerReviewed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scheduler := &Scheduler{center: New(store, testSenderProvider{sender: &testSender{}}, nil)}
|
||||
for i := 0; i < 5; i++ {
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`)
|
||||
scheduler.runDeferredTasks(ctx)
|
||||
}
|
||||
var status string
|
||||
var attempts int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status,attempt_count FROM automation_pending_tasks WHERE task_key='cid:bad'`).Scan(&status, &attempts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "dead_letter" || attempts != 5 {
|
||||
t.Fatalf("status=%s attempts=%d", status, attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownExternalAutomationRunCannotBeRetried(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "retry", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "retry-message", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{err: errors.New("temporary")}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "retry-order", ChatID: "chat", BuyerID: "buyer"}); err == nil {
|
||||
t.Fatal("first execution should fail")
|
||||
}
|
||||
var runID int64
|
||||
var initialStatus string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT id,status FROM automation_runs WHERE order_id='retry-order'`).Scan(&runID, &initialStatus); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initialStatus != "needs_review" {
|
||||
t.Fatalf("ambiguous failure status=%s", initialStatus)
|
||||
}
|
||||
if err := store.Automation.ResolveRunIssue(ctx, admin.ID, runID, "retry"); err == nil {
|
||||
t.Fatal("unknown external send result must reject retry")
|
||||
}
|
||||
var status string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id='retry-order'`).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "needs_review" {
|
||||
t.Fatalf("status=%s want needs_review", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedDeferredTaskRemainsPending(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "deferred-fail", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "x", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "deferred-fail", ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"delays_elapsed": true}}
|
||||
raw, _ := json.Marshal(task)
|
||||
if err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{TaskKey: "cid:buyer_reviewed:deferred-fail", CookieID: "cid", TriggerType: TriggerBuyerReviewed, TaskJSON: string(raw), DueAt: 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
center := New(store, testSenderProvider{sender: &testSender{err: errors.New("temporary")}}, nil)
|
||||
(&Scheduler{center: center}).runDeferredTasks(ctx)
|
||||
var status string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status FROM automation_pending_tasks WHERE task_key='cid:buyer_reviewed:deferred-fail'`).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "pending" {
|
||||
t.Fatalf("status=%s", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
@@ -268,8 +603,8 @@ func TestCenterOrderPaidDoesNotConfirmWhenNoCardSpecMatches(t *testing.T) {
|
||||
Source: "ws", AccountID: "cid", CookieStr: "unb=123; _m_h5_tk=tk_1;", TriggerType: TriggerOrderPaid,
|
||||
ChatID: "chat-1", OrderID: "order-no-match", ItemID: "item-1", BuyerID: "buyer-1", Raw: map[string]any{"message_id": "m2"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("HandleTask should swallow rule execution errors: %v", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "未匹配") {
|
||||
t.Fatalf("HandleTask should return rule execution errors: %v", err)
|
||||
}
|
||||
if len(sender.texts) != 0 {
|
||||
t.Fatalf("规格不匹配时不应发送卡密: %v", sender.texts)
|
||||
@@ -334,6 +669,191 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
initialValue := "flat_leak=must-not-send; unb=123; _m_h5_tk=flat_old_1"
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "snapshot_old_1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "document_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
|
||||
{Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
|
||||
}
|
||||
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":"yes"}`, snapshot)
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var requestCookie string
|
||||
client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
requestCookie = req.Header.Get("Cookie")
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Set-Cookie": []string{
|
||||
"_m_h5_tk=snapshot_new_2; Domain=.goofish.com; Path=/; Secure",
|
||||
"consign_scope=new; Path=/h5; Secure; HttpOnly",
|
||||
}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
lockReleasedBeforeRuntimeUpdate := false
|
||||
sender := &testSender{onCookieUpdate: func(string) {
|
||||
acquired := make(chan struct{})
|
||||
go func() {
|
||||
unlock := store.LockAccountCredentials("cid")
|
||||
unlock()
|
||||
close(acquired)
|
||||
}()
|
||||
select {
|
||||
case <-acquired:
|
||||
lockReleasedBeforeRuntimeUpdate = true
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
}}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "session-parse-error", ForceConfirmShipment: true,
|
||||
})
|
||||
var uncertain *uncertainActionError
|
||||
if !errors.As(err, &uncertain) {
|
||||
t.Fatalf("远程响应解析失败应进入人工核对: %v", err)
|
||||
}
|
||||
for _, want := range []string{"unb=123", "_m_h5_tk=snapshot_old_1", "api_only=api"} {
|
||||
if !strings.Contains(requestCookie, want) {
|
||||
t.Fatalf("发货请求 Cookie %q 未使用加锁后重读的权威 Jar,缺少 %q", requestCookie, want)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"flat_leak=", "document_only="} {
|
||||
if strings.Contains(requestCookie, unwanted) {
|
||||
t.Fatalf("发货请求 Cookie %q 泄漏了错误作用域 %q", requestCookie, unwanted)
|
||||
}
|
||||
}
|
||||
|
||||
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if !strings.Contains(detail.Value, "_m_h5_tk=snapshot_new_2") || strings.Contains(detail.Value, "flat_leak=") {
|
||||
t.Fatalf("正文解析失败后未优先持久化响应 Cookie Jar: %q", detail.Value)
|
||||
}
|
||||
if !strings.Contains(detail.MetadataJSON, `"preserved":"yes"`) {
|
||||
t.Fatalf("持久化 Jar 时丢失原 metadata: %s", detail.MetadataJSON)
|
||||
}
|
||||
gotSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if !ok {
|
||||
t.Fatalf("响应后权威 snapshot 丢失: %s", detail.MetadataJSON)
|
||||
}
|
||||
values := make(map[string]string, len(gotSnapshot))
|
||||
for _, cookie := range gotSnapshot {
|
||||
values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path] = cookie.Value
|
||||
}
|
||||
if values["_m_h5_tk|.goofish.com|/"] != "snapshot_new_2" ||
|
||||
values["consign_scope|h5api.m.goofish.com|/h5"] != "new" ||
|
||||
values["document_only|www.goofish.com|/im"] != "doc" {
|
||||
t.Fatalf("响应后 snapshot 作用域不完整: %+v", gotSnapshot)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 1 || !strings.Contains(sender.cookieUpdates[0], "_m_h5_tk=snapshot_new_2") {
|
||||
t.Fatalf("运行实例未同步已持久化的 Cookie: %+v", sender.cookieUpdates)
|
||||
}
|
||||
if !lockReleasedBeforeRuntimeUpdate {
|
||||
t.Fatal("运行实例 Cookie 必须在账号凭证锁外更新")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentPropagatesAuthoritativeEmptySession(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
initialValue := "unb=123; _m_h5_tk=old_1"
|
||||
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Set-Cookie": []string{
|
||||
"unb=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
|
||||
"_m_h5_tk=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
|
||||
}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "authoritative-empty-session", ForceConfirmShipment: true,
|
||||
})
|
||||
var uncertain *uncertainActionError
|
||||
if !errors.As(err, &uncertain) {
|
||||
t.Fatalf("删除凭证后的解析失败应进入人工核对: %v", err)
|
||||
}
|
||||
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if detail.Value != "" {
|
||||
t.Fatalf("权威空 Jar 未持久化: %q", detail.Value)
|
||||
}
|
||||
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if !ok || snapshot == nil || len(snapshot) != 0 {
|
||||
t.Fatalf("权威空 snapshot 语义丢失: ok=%v snapshot=%#v metadata=%s", ok, snapshot, detail.MetadataJSON)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != "" {
|
||||
t.Fatalf("权威空 Jar 未在锁外通知运行实例: %#v", sender.cookieUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualFullDeliveryIsImmediateIdempotentAndForcesConfirmation(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE cookies SET auto_confirm=0 WHERE id='cid'`)
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('cid','manual-item','会员')`)
|
||||
cardID, err := store.Cards.Create(ctx, &db.CardFull{
|
||||
Name: "manual-card", Type: "text", TextContent: "MANUAL-CARD", Enabled: true, DelaySeconds: 86400, UserID: admin.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "manual-item", Name: "manual", TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, ConfigJSON: `{}`, Enabled: true, SortOrder: 1},
|
||||
{ActionType: ActionConfirmShipment, Enabled: true, SortOrder: 2},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
mtopMock := &fakeMTop{consignOk: true}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(mtopMock)
|
||||
center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", OrderStatus: "pending_ship"}})
|
||||
order := &db.Order{OrderID: "manual-order", CookieID: "cid", ItemID: "manual-item", BuyerID: "buyer", ChatID: "chat"}
|
||||
|
||||
sent, err := center.ManualFullDelivery(ctx, order)
|
||||
if err != nil || sent != 1 || len(sender.texts) != 1 || mtopMock.consignCalls != 1 {
|
||||
t.Fatalf("first manual delivery sent=%d texts=%v consign=%d err=%v", sent, sender.texts, mtopMock.consignCalls, err)
|
||||
}
|
||||
if _, err := center.ManualFullDelivery(ctx, order); err == nil || !strings.Contains(err.Error(), "执行过") {
|
||||
t.Fatalf("duplicate manual delivery should be rejected: %v", err)
|
||||
}
|
||||
if len(sender.texts) != 1 || mtopMock.consignCalls != 1 {
|
||||
t.Fatalf("duplicate request caused side effects: texts=%v consign=%d", sender.texts, mtopMock.consignCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// recordingNotifier 记录所有 NotifyDelivery 调用,用于断言 automation.Center 接线。
|
||||
type recordingNotifier struct {
|
||||
mu sync.Mutex
|
||||
@@ -474,6 +994,13 @@ func TestDueReviewRequestOrdersHandlesNullSpecColumns(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "review", TriggerType: TriggerReviewMissingTimeout, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "review", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 插入一条已发货、未评价、spec_name/spec_value 为 NULL 的订单(旧库常见形态)。
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO orders
|
||||
@@ -493,3 +1020,54 @@ func TestDueReviewRequestOrdersHandlesNullSpecColumns(t *testing.T) {
|
||||
t.Fatalf("NULL 列应归一为空串,got spec=%q/%q", orders[0].SpecName, orders[0].SpecValue)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewRequestCounterFailureMovesCompletedActionToNeedsReview(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "review-counter", TriggerType: TriggerReviewMissingTimeout, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "请评价", Enabled: true}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Orders.Upsert(ctx, "review-counter-order", db.OrderUpsertOpts{CookieID: "cid", ChatID: "chat", BuyerID: "buyer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_review_counter
|
||||
BEFORE UPDATE OF review_request_count ON orders
|
||||
WHEN NEW.review_request_count>OLD.review_request_count
|
||||
BEGIN SELECT RAISE(FAIL, 'forced review counter failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rule, err := store.Automation.Get(ctx, ruleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
err = center.executeRule(ctx, Task{
|
||||
Source: "scheduler", AccountID: "cid", TriggerType: TriggerReviewMissingTimeout,
|
||||
OrderID: "review-counter-order", ChatID: "chat", BuyerID: "buyer",
|
||||
Raw: map[string]any{"attempt": 1},
|
||||
}, *rule)
|
||||
if !errors.Is(err, errAutomationNeedsReview) {
|
||||
t.Fatalf("counter failure should require review, got %v", err)
|
||||
}
|
||||
if len(sender.texts) != 1 {
|
||||
t.Fatalf("message action should execute exactly once, got %v", sender.texts)
|
||||
}
|
||||
order, err := store.Orders.Get(ctx, "review-counter-order")
|
||||
if err != nil || order.ReviewRequestCount != 0 {
|
||||
t.Fatalf("counter=%d err=%v", order.ReviewRequestCount, err)
|
||||
}
|
||||
var status, message string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status,error_message FROM automation_runs WHERE order_id=?`, "review-counter-order").Scan(&status, &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "needs_review" || !strings.Contains(message, "保存提醒次数失败") {
|
||||
t.Fatalf("status=%q message=%q", status, message)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,7 +42,12 @@ type Task struct {
|
||||
OrderStatus string
|
||||
Text string
|
||||
UpdateKey string
|
||||
Raw map[string]any
|
||||
// ForceConfirmShipment 仅供明确的人工“完整发货”使用;自动事件仍遵循账号自动确认开关。
|
||||
ForceConfirmShipment bool
|
||||
// ActionPlan 是运行创建时冻结的动作计划。延迟恢复和失败重试必须使用该快照,
|
||||
// 不能把数字游标应用到管理员后来修改过的规则上。
|
||||
ActionPlan []db.AutomationAction
|
||||
Raw map[string]any
|
||||
}
|
||||
|
||||
// OrderDetail 是自动化中心执行交易类任务前需要补齐的订单事实。
|
||||
|
||||
@@ -3,6 +3,7 @@ package automation
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -43,60 +44,150 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *Scheduler) scan(ctx context.Context) {
|
||||
orders, err := s.center.store.Automation.DueReviewRequestOrders(ctx, 200)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描求评价计划任务失败", "err", err)
|
||||
return
|
||||
}
|
||||
for _, order := range orders {
|
||||
rules, err := s.center.store.Automation.Match(ctx, order.CookieID, order.ItemID, TriggerReviewMissingTimeout)
|
||||
if err != nil || len(rules) == 0 {
|
||||
continue
|
||||
s.runDeferredTasks(ctx)
|
||||
s.runRecoveryTasks(ctx)
|
||||
// 逐页执行,避免把所有到期订单一次性装入内存。稳定 ID 游标确保本轮有界。
|
||||
afterOrderID := ""
|
||||
for {
|
||||
orders, err := s.center.store.Automation.DueReviewRequestOrdersAfter(ctx, afterOrderID, 200)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描求评价计划任务失败", "err", err)
|
||||
return
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if !reviewRequestRuleDue(order, rule) {
|
||||
for _, order := range orders {
|
||||
allowed, allowErr := s.center.accountAutomationAllowed(ctx, order.CookieID)
|
||||
if allowErr != nil {
|
||||
s.center.logger.Warn("检查求评价账号状态失败", "account", order.CookieID, "err", allowErr)
|
||||
continue
|
||||
}
|
||||
task := Task{
|
||||
Source: "scheduler",
|
||||
AccountID: order.CookieID,
|
||||
TriggerType: TriggerReviewMissingTimeout,
|
||||
ChatID: order.ChatID,
|
||||
OrderID: order.OrderID,
|
||||
ItemID: order.ItemID,
|
||||
BuyerID: order.BuyerID,
|
||||
Text: "发货后一段时间未评价",
|
||||
Raw: map[string]any{
|
||||
"source": "scheduler",
|
||||
"rule_id": rule.ID,
|
||||
"order_id": order.OrderID,
|
||||
"attempt": order.ReviewRequestCount + 1,
|
||||
},
|
||||
if !allowed {
|
||||
continue
|
||||
}
|
||||
_ = s.center.executeRule(ctx, task, rule)
|
||||
rules, err := s.center.store.Automation.Match(ctx, order.CookieID, order.ItemID, TriggerReviewMissingTimeout)
|
||||
if err != nil || len(rules) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if !reviewRequestRuleDue(order, rule) {
|
||||
continue
|
||||
}
|
||||
task := Task{Source: "scheduler", AccountID: order.CookieID, TriggerType: TriggerReviewMissingTimeout,
|
||||
ChatID: order.ChatID, OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID,
|
||||
Text: "发货后一段时间未评价", Raw: map[string]any{"source": "scheduler", "rule_id": rule.ID,
|
||||
"order_id": order.OrderID, "attempt": order.ReviewRequestCount + 1}}
|
||||
_ = s.center.executeRule(ctx, task, rule)
|
||||
}
|
||||
}
|
||||
if len(orders) < 200 {
|
||||
break
|
||||
}
|
||||
afterOrderID = orders[len(orders)-1].OrderID
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
runs, err := s.center.store.Automation.DueRecoveryRuns(ctx, 100)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描失败自动化运行失败", "err", err)
|
||||
return
|
||||
}
|
||||
for _, run := range runs {
|
||||
if run.ActionStarted {
|
||||
reason := "进程在外部动作执行期间中断,发送结果未知,已禁止自动重放"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
continue
|
||||
}
|
||||
var task Task
|
||||
if err := json.Unmarshal([]byte(run.RawEventJSON), &task); err != nil || task.AccountID == "" {
|
||||
reason := "历史运行数据无法安全解析,已移入人工检查"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
continue
|
||||
}
|
||||
allowed, err := s.center.accountAutomationAllowed(ctx, task.AccountID)
|
||||
if err != nil || !allowed {
|
||||
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
continue
|
||||
}
|
||||
rule, err := s.center.store.Automation.Get(ctx, run.RuleID)
|
||||
if err != nil || !rule.Enabled {
|
||||
reason := "自动化规则不存在或已停用,无法恢复"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
continue
|
||||
}
|
||||
claimed, claimErr := s.center.store.Automation.ClaimRecoveryRun(ctx, run.ID, time.Now().UTC().Add(5*time.Minute).Unix())
|
||||
if claimErr != nil || !claimed {
|
||||
continue
|
||||
}
|
||||
if task.Raw == nil {
|
||||
task.Raw = map[string]any{}
|
||||
}
|
||||
task.Raw["automation_run_id"] = run.ID
|
||||
task.Raw["automation_rule_id"] = run.RuleID
|
||||
if err := s.center.executeRule(ctx, task, *rule); err != nil && !errors.Is(err, errAutomationDeferred) {
|
||||
s.center.logger.Warn("重试自动化运行失败", "run_id", run.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
tasks, err := s.center.store.Automation.ClaimDueDeferredTasks(ctx, 100)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描暂停期间自动化事件失败", "err", err)
|
||||
return
|
||||
}
|
||||
for _, pending := range tasks {
|
||||
var task Task
|
||||
if err := json.Unmarshal([]byte(pending.TaskJSON), &task); err != nil {
|
||||
_ = s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, false, "解析任务失败: "+err.Error())
|
||||
continue
|
||||
}
|
||||
deferredAgain, runErr := s.center.handleTask(ctx, task)
|
||||
if deferredAgain {
|
||||
// handleTask 已按新的 paused_until 重置同一任务;当前 claim 不再删除。
|
||||
continue
|
||||
}
|
||||
if err := s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, runErr == nil, errorString(runErr)); err != nil {
|
||||
s.center.logger.Warn("保存暂停事件重放结果失败", "task_id", pending.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func errorString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func reviewRequestRuleDue(order db.Order, rule db.AutomationRule) bool {
|
||||
cfg := parseReviewRuleConfig(rule.ConfigJSON)
|
||||
if cfg.MaxAttempts > 0 && order.ReviewRequestCount >= cfg.MaxAttempts {
|
||||
return false
|
||||
}
|
||||
base := parseDBTime(firstNonEmpty(order.ShippedAt, order.UpdatedAt, order.CreatedAt))
|
||||
baseRaw := firstNonEmpty(order.ShippedAt, order.UpdatedAt, order.CreatedAt)
|
||||
waitHours := cfg.AfterShippedHours
|
||||
if order.ReviewRequestCount > 0 && strings.TrimSpace(order.LastReviewRequestAt) != "" {
|
||||
baseRaw = order.LastReviewRequestAt
|
||||
waitHours = cfg.RepeatIntervalHours
|
||||
}
|
||||
base := parseDBTime(baseRaw)
|
||||
if base.IsZero() {
|
||||
return false
|
||||
}
|
||||
return time.Since(base) >= time.Duration(cfg.AfterShippedHours)*time.Hour
|
||||
return time.Since(base) >= time.Duration(waitHours)*time.Hour
|
||||
}
|
||||
|
||||
type reviewRuleConfig struct {
|
||||
AfterShippedHours int
|
||||
MaxAttempts int
|
||||
AfterShippedHours int
|
||||
RepeatIntervalHours int
|
||||
MaxAttempts int
|
||||
}
|
||||
|
||||
func parseReviewRuleConfig(raw string) reviewRuleConfig {
|
||||
cfg := reviewRuleConfig{AfterShippedHours: 72, MaxAttempts: 1}
|
||||
cfg := reviewRuleConfig{AfterShippedHours: 72, RepeatIntervalHours: 24, MaxAttempts: 1}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return cfg
|
||||
}
|
||||
@@ -107,6 +198,12 @@ func parseReviewRuleConfig(raw string) reviewRuleConfig {
|
||||
if v := intFromAny(m["after_shipped_hours"]); v > 0 {
|
||||
cfg.AfterShippedHours = v
|
||||
}
|
||||
if v := intFromAny(m["first_delay_hours"]); v > 0 {
|
||||
cfg.AfterShippedHours = v
|
||||
}
|
||||
if v := intFromAny(m["repeat_interval_hours"]); v > 0 {
|
||||
cfg.RepeatIntervalHours = v
|
||||
}
|
||||
if v := intFromAny(m["max_attempts"]); v > 0 {
|
||||
cfg.MaxAttempts = v
|
||||
}
|
||||
@@ -129,7 +226,7 @@ func intFromAny(v any) int {
|
||||
|
||||
func parseDBTime(s string) time.Time {
|
||||
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"} {
|
||||
if t, err := time.ParseInLocation(layout, strings.TrimSpace(s), time.Local); err == nil {
|
||||
if t, err := time.ParseInLocation(layout, strings.TrimSpace(s), time.UTC); err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -78,7 +79,7 @@ func TestReviewRequestRuleDue(t *testing.T) {
|
||||
order := db.Order{
|
||||
OrderID: "o1",
|
||||
SystemShipped: true,
|
||||
ShippedAt: time.Now().Add(-2 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
ShippedAt: time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
ReviewRequestCount: 0,
|
||||
}
|
||||
if !reviewRequestRuleDue(order, rule) {
|
||||
@@ -86,13 +87,13 @@ func TestReviewRequestRuleDue(t *testing.T) {
|
||||
}
|
||||
|
||||
// 发货不到 1 小时 → 不 due。
|
||||
order.ShippedAt = time.Now().Add(-30 * time.Minute).Format("2006-01-02 15:04:05")
|
||||
order.ShippedAt = time.Now().UTC().Add(-30 * time.Minute).Format("2006-01-02 15:04:05")
|
||||
if reviewRequestRuleDue(order, rule) {
|
||||
t.Error("发货仅 30min 不应 due")
|
||||
}
|
||||
|
||||
// 已达最大次数 → 不 due。
|
||||
order.ShippedAt = time.Now().Add(-2 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
order.ShippedAt = time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
order.ReviewRequestCount = 2
|
||||
if reviewRequestRuleDue(order, rule) {
|
||||
t.Error("达到 max_attempts 不应 due")
|
||||
@@ -107,13 +108,31 @@ func TestReviewRequestRuleDue(t *testing.T) {
|
||||
// 缺 shipped_at 时回退到 updated_at。
|
||||
order3 := db.Order{
|
||||
OrderID: "o3",
|
||||
UpdatedAt: time.Now().Add(-3 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
UpdatedAt: time.Now().UTC().Add(-3 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if !reviewRequestRuleDue(order3, rule) {
|
||||
t.Error("缺 shipped_at 应回退 updated_at 判定 due")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewRequestRuleDueUsesRepeatIntervalAfterFirstAttempt(t *testing.T) {
|
||||
rule := db.AutomationRule{ConfigJSON: `{"first_delay_hours":1,"repeat_interval_hours":24,"max_attempts":3}`}
|
||||
order := db.Order{
|
||||
OrderID: "repeat-review",
|
||||
SystemShipped: true,
|
||||
ShippedAt: time.Now().UTC().Add(-72 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
ReviewRequestCount: 1,
|
||||
LastReviewRequestAt: time.Now().UTC().Add(-23 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if reviewRequestRuleDue(order, rule) {
|
||||
t.Fatal("repeat request must wait from last_review_request_at, not shipped_at")
|
||||
}
|
||||
order.LastReviewRequestAt = time.Now().UTC().Add(-25 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
if !reviewRequestRuleDue(order, rule) {
|
||||
t.Fatal("repeat request should be due after repeat_interval_hours")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstNonEmpty 返回首个非空串。
|
||||
func TestFirstNonEmpty(t *testing.T) {
|
||||
if got := firstNonEmpty("", "", "x", "y"); got != "x" {
|
||||
@@ -163,7 +182,7 @@ func TestSchedulerScanExecutesDueThenSkipsOnMaxAttempts(t *testing.T) {
|
||||
}
|
||||
|
||||
// 已发货、未评价、有 chat_id 的订单。
|
||||
shipped := time.Now().Add(-2 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
shipped := time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO orders
|
||||
(order_id, cookie_id, item_id, buyer_id, chat_id, system_shipped, shipped_at, review_request_count)
|
||||
VALUES ('o-sched', 'cid', 'item-1', 'buyer-1', 'chat-1', 1, ?, 0)`, shipped); err != nil {
|
||||
@@ -194,3 +213,30 @@ func TestSchedulerScanExecutesDueThenSkipsOnMaxAttempts(t *testing.T) {
|
||||
t.Fatalf("达到 max_attempts 不应再发送,got %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerScansMoreThanOneReviewPage(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "review-all", TriggerType: TriggerReviewMissingTimeout, Enabled: true,
|
||||
ConfigJSON: `{"after_shipped_hours":1,"max_attempts":1}`,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "review", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shipped := time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
for i := 0; i < 205; i++ {
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO orders
|
||||
(order_id,cookie_id,buyer_id,chat_id,system_shipped,shipped_at,review_request_count,updated_at)
|
||||
VALUES (?,?,?,?,1,?,0,?)`, fmt.Sprintf("review-%03d", i), "cid", "buyer", fmt.Sprintf("chat-%03d", i), shipped, shipped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
sender := &testSender{}
|
||||
NewScheduler(New(store, testSenderProvider{sender: sender}, nil)).scan(ctx)
|
||||
if len(sender.texts) != 205 {
|
||||
t.Fatalf("sent=%d want 205", len(sender.texts))
|
||||
}
|
||||
}
|
||||
+350
-147
@@ -2,10 +2,12 @@ package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
@@ -17,7 +19,14 @@ const (
|
||||
quickRenewPageLoadWait = 3 * time.Second
|
||||
quickRenewAfterClick = 5 * time.Second
|
||||
quickRenewTimeoutMS = 30000
|
||||
quickRenewUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
|
||||
officialAutoLoginWait = 10 * time.Second
|
||||
officialFetchDrainWait = 30 * time.Second
|
||||
officialReloadWait = 5 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInteractiveLoginRequired = errors.New("浏览器会话已退出登录,需要交互式登录")
|
||||
ErrSecurityVerification = errors.New("闲鱼要求安全验证,需要人工处理")
|
||||
)
|
||||
|
||||
// CookieRenew 用现有 Cookie 打开闲鱼页面,尝试通过“快速进入”刷新浏览器登录态。
|
||||
@@ -32,59 +41,87 @@ func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, h
|
||||
return cookierefresh.ParseCookieString(newCookies), nil
|
||||
}
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
|
||||
if cookieStr == "" {
|
||||
return "", fmt.Errorf("Cookie为空,无法浏览器续期")
|
||||
}
|
||||
func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, userDataDir string, headless bool) (playwright.BrowserContext, func(), error) {
|
||||
lock := m.accountRenewLock(cookieID)
|
||||
lock.Lock()
|
||||
unlock := func() { lock.Unlock() }
|
||||
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, nil, quickRenewHeadless(headless))
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
if err := m.init(); err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
userDataDir, err = resolvePersistentUserDataDir(userDataDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("新建 page 失败: %w", err)
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
}); err != nil {
|
||||
m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
|
||||
cleanSingletonFiles(userDataDir)
|
||||
var bctx playwright.BrowserContext
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless))
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
lastErr = err
|
||||
cleanSingletonFiles(userDataDir)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
|
||||
hasQuickEnter := clickQuickEnter(page)
|
||||
if hasQuickEnter {
|
||||
time.Sleep(quickRenewAfterClick)
|
||||
} else if !checkAlreadyLoggedIn(page) {
|
||||
return "", fmt.Errorf("未找到[快速进入]按钮且未检测到登录状态,需要账号密码登录")
|
||||
if bctx == nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
|
||||
}
|
||||
|
||||
all, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("提取 cookie 失败: %w", err)
|
||||
release := func() {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
unlock()
|
||||
}
|
||||
newSnapshot := cookieSnapshotFromPlaywright(all)
|
||||
if len(newSnapshot) == 0 {
|
||||
return "", fmt.Errorf("点击[快速进入]后未获取到浏览器Cookie")
|
||||
}
|
||||
cookieFromBrowser := cookierefresh.CookieStringFromSnapshot(newSnapshot)
|
||||
merged := cookierefresh.MergeOriginalFields(cookieStr, cookieFromBrowser)
|
||||
m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
|
||||
return merged, nil
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
// CookiesRefreshSnapshot 执行定时 COOKIES 续期:打开首页、刷新页面并返回完整 Cookie 快照。
|
||||
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
if cookieStr == "" && len(snapshot) == 0 {
|
||||
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
|
||||
func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions {
|
||||
return playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
Viewport: &playwright.Size{Width: 1980, Height: 1024},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
AcceptDownloads: playwright.Bool(true),
|
||||
IgnoreHttpsErrors: playwright.Bool(true),
|
||||
ExtraHttpHeaders: map[string]string{
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
},
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
}
|
||||
bctx, release, err := m.newEphemeralRefreshContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
|
||||
}
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
|
||||
newCookies, _, err := m.BrowserQuickRenewSnapshot(ctx, cookieID, cookieStr, nil, headless)
|
||||
return newCookies, err
|
||||
}
|
||||
|
||||
// BrowserQuickRenewSnapshot is the full-fidelity variant of BrowserQuickRenew.
|
||||
// Callers that persist cookie metadata should use it directly: Chromium's final
|
||||
// jar is authoritative for both deletions and attributes such as expiry/path.
|
||||
func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
if cookieStr == "" && snapshot == nil {
|
||||
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法浏览器续期")
|
||||
}
|
||||
// 持久化的扁平值始终以消息页为 canonical scope;这里也必须按 /im
|
||||
// 解释,避免漏掉或错误映射 Path=/im 的连接凭证。
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -97,50 +134,213 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
}); err != nil {
|
||||
m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
|
||||
hasQuickEnter := false
|
||||
var renewErr error
|
||||
if err := verifyHomeLoginState(page); err != nil {
|
||||
if errors.Is(err, ErrSecurityVerification) {
|
||||
renewErr = err
|
||||
} else {
|
||||
hasQuickEnter = clickQuickEnter(page)
|
||||
if !hasQuickEnter {
|
||||
renewErr = err
|
||||
} else {
|
||||
time.Sleep(quickRenewAfterClick)
|
||||
renewErr = verifyHomeLoginState(page)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
if err != nil {
|
||||
return "", nil, errors.Join(renewErr, err)
|
||||
}
|
||||
if len(newSnapshot) == 0 {
|
||||
renewErr = errors.Join(renewErr, fmt.Errorf("点击[快速进入]后浏览器 Cookie Jar 为空"))
|
||||
}
|
||||
if renewErr != nil {
|
||||
return newCookies, newSnapshot, renewErr
|
||||
}
|
||||
m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
|
||||
return newCookies, newSnapshot, nil
|
||||
}
|
||||
|
||||
// CookiesRefreshSnapshot executes the optional browser-backed renewal in the
|
||||
// account's persistent profile. One ordinary page load is enough to run the
|
||||
// site's own auto-login plugin; repeated reloads create an avoidable risk
|
||||
// signal and are deliberately not used.
|
||||
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error) {
|
||||
if cookieStr == "" && snapshot == nil {
|
||||
return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
|
||||
}
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
reloaded, renewErr := navigateOfficialRenewPage(ctx, page)
|
||||
if renewErr == nil {
|
||||
renewErr = verifyHomeLoginState(page)
|
||||
}
|
||||
|
||||
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
if err != nil {
|
||||
return "", nil, reloaded, errors.Join(renewErr, err)
|
||||
}
|
||||
if len(newSnapshot) == 0 {
|
||||
renewErr = errors.Join(renewErr, fmt.Errorf("消息页执行后浏览器 Cookie Jar 为空"))
|
||||
}
|
||||
if renewErr != nil {
|
||||
return newCookies, newSnapshot, reloaded, renewErr
|
||||
}
|
||||
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot), "official_reload", reloaded)
|
||||
return newCookies, newSnapshot, reloaded, nil
|
||||
}
|
||||
|
||||
func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool, error) {
|
||||
silentStarted := make(chan struct{}, 1)
|
||||
silentSettled := make(chan bool, 1)
|
||||
reloadCommitted := make(chan struct{}, 1)
|
||||
var navigationArmed atomic.Bool
|
||||
page.OnRequest(func(request playwright.Request) {
|
||||
if isSilentHasLoginURL(request.URL()) {
|
||||
select {
|
||||
case silentStarted <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
})
|
||||
page.OnFrameNavigated(func(frame playwright.Frame) {
|
||||
if navigationArmed.Load() && frame.ParentFrame() == nil && strings.HasPrefix(frame.URL(), goofishIMURL) {
|
||||
select {
|
||||
case reloadCommitted <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
})
|
||||
page.OnRequestFinished(func(request playwright.Request) {
|
||||
if isSilentHasLoginURL(request.URL()) {
|
||||
select {
|
||||
case silentSettled <- true:
|
||||
default:
|
||||
}
|
||||
}
|
||||
})
|
||||
page.OnRequestFailed(func(request playwright.Request) {
|
||||
if isSilentHasLoginURL(request.URL()) {
|
||||
select {
|
||||
case silentSettled <- false:
|
||||
default:
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(60000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err)
|
||||
return false, fmt.Errorf("COOKIES续期访问消息页: %w", err)
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(60000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("COOKIES续期 reload 异常", "cookieID", cookieID, "attempt", i+1, "err", err)
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
navigationArmed.Store(true)
|
||||
// The plugin starts after the SPA hydrates, then waits 2s before issuing
|
||||
// silentHasLogin. Observe the actual request instead of assuming hydration
|
||||
// completed at DOMContentLoaded; navigation Set-Cookie may also change the
|
||||
// sdkSilent/long-login branch.
|
||||
observeTimer := time.NewTimer(officialAutoLoginWait)
|
||||
requestStarted := false
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
observeTimer.Stop()
|
||||
return false, ctx.Err()
|
||||
case <-silentStarted:
|
||||
requestStarted = true
|
||||
observeTimer.Stop()
|
||||
case <-observeTimer.C:
|
||||
}
|
||||
|
||||
if modal, err := page.QuerySelector(".ant-modal-body"); err == nil && modal != nil {
|
||||
text, _ := modal.TextContent()
|
||||
if len(text) > 120 {
|
||||
text = text[:120]
|
||||
if requestStarted {
|
||||
// The plugin's 2s Promise timeout does not abort fetch. Keep the page
|
||||
// alive until Chromium finishes the response body (and applies Set-Cookie), while
|
||||
// leaving reload/no-reload entirely to the official JavaScript.
|
||||
drainTimer := time.NewTimer(officialFetchDrainWait)
|
||||
requestFinished := false
|
||||
select {
|
||||
case requestFinished = <-silentSettled:
|
||||
drainTimer.Stop()
|
||||
case <-ctx.Done():
|
||||
drainTimer.Stop()
|
||||
return false, ctx.Err()
|
||||
case <-drainTimer.C:
|
||||
}
|
||||
if text != "" {
|
||||
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败: %s", text)
|
||||
if requestFinished {
|
||||
reloadTimer := time.NewTimer(officialReloadWait)
|
||||
select {
|
||||
case <-reloadCommitted:
|
||||
reloadTimer.Stop()
|
||||
if err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
|
||||
State: playwright.LoadStateDomcontentloaded, Timeout: playwright.Float(10000),
|
||||
}); err != nil {
|
||||
return true, fmt.Errorf("等待官网续期 reload 完成: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
case <-ctx.Done():
|
||||
reloadTimer.Stop()
|
||||
return false, ctx.Err()
|
||||
case <-reloadTimer.C:
|
||||
}
|
||||
}
|
||||
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败")
|
||||
}
|
||||
// Absence of a reload is the official outcome for fatigue, timeout or a
|
||||
// non-100 business result.
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (string, []cookierefresh.BrowserCookie, error) {
|
||||
all, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("提取 cookie 失败: %w", err)
|
||||
return "", nil, fmt.Errorf("提取浏览器 Cookie Jar: %w", err)
|
||||
}
|
||||
newSnapshot := cookieSnapshotFromPlaywright(all)
|
||||
if len(newSnapshot) == 0 {
|
||||
return "", nil, fmt.Errorf("页面刷新完成,但未获取到浏览器Cookie")
|
||||
snapshot := cookieSnapshotFromPlaywright(all)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
newCookies := cookierefresh.CookieStringFromSnapshot(newSnapshot)
|
||||
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot))
|
||||
return newCookies, newSnapshot, nil
|
||||
return currentCookieHeader(snapshot, rawURL), snapshot, nil
|
||||
}
|
||||
|
||||
func isSilentHasLoginURL(rawURL string) bool {
|
||||
return strings.Contains(rawURL, "/newlogin/silentHasLogin.do")
|
||||
}
|
||||
|
||||
func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie, cookieStr, rawURL string) []cookierefresh.BrowserCookie {
|
||||
if snapshot == nil {
|
||||
return nil
|
||||
}
|
||||
if len(snapshot) == 0 {
|
||||
return []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
return cookierefresh.NormalizeSnapshot(snapshot)
|
||||
}
|
||||
return credentialCookieSnapshotForURL(snapshot, parseCookieStr(cookieStr), rawURL)
|
||||
}
|
||||
|
||||
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
|
||||
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
|
||||
cookies, refreshed, _, err := m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
|
||||
return cookies, refreshed, err
|
||||
}
|
||||
|
||||
func clickQuickEnter(page playwright.Page) bool {
|
||||
@@ -176,30 +376,62 @@ var quickEnterSelectors = []string{
|
||||
`.fn-button:has-text("快速进入")`,
|
||||
}
|
||||
|
||||
var loggedInSelectors = []string{
|
||||
"div.nick",
|
||||
".header-right .nick",
|
||||
".rc-virtual-list-holder-inner",
|
||||
`img[src*="img.alicdn.com"][class*="avatar"]`,
|
||||
`img[src*="img.alicdn.com"][style*="border-radius"]`,
|
||||
`.header-container img[src*="img.alicdn.com"]`,
|
||||
"#nc_1_n1z",
|
||||
".nc-container",
|
||||
".nc_scale",
|
||||
`div:has-text("请拖动下方滑块完成验证")`,
|
||||
`div:has-text("请按住滑块")`,
|
||||
func verifyHomeLoginState(page playwright.Page) error {
|
||||
if pageHasSecurityVerification(page) {
|
||||
return ErrSecurityVerification
|
||||
}
|
||||
result, err := page.Evaluate(`() => {
|
||||
const visible = (el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const style = getComputedStyle(el);
|
||||
return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden';
|
||||
};
|
||||
const links = Array.from(document.querySelectorAll('a'));
|
||||
const personal = links.some((el) => {
|
||||
if (!visible(el)) return false;
|
||||
try { return new URL(el.href, location.href).pathname === '/personal'; } catch (_) { return false; }
|
||||
});
|
||||
const login = Array.from(document.querySelectorAll('a,button,[role="button"]')).some((el) => {
|
||||
if (!visible(el) || (el.textContent || '').trim() !== '登录') return false;
|
||||
return el.getBoundingClientRect().top < 120;
|
||||
});
|
||||
return { personal, login };
|
||||
}`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取浏览器登录状态失败: %w", err)
|
||||
}
|
||||
signals, ok := result.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("浏览器登录状态返回格式异常")
|
||||
}
|
||||
personal, _ := signals["personal"].(bool)
|
||||
login, _ := signals["login"].(bool)
|
||||
if personal && !login {
|
||||
return nil
|
||||
}
|
||||
if login {
|
||||
return ErrInteractiveLoginRequired
|
||||
}
|
||||
return fmt.Errorf("%w: 页面未出现个人主页入口", ErrInteractiveLoginRequired)
|
||||
}
|
||||
|
||||
func checkAlreadyLoggedIn(page playwright.Page) bool {
|
||||
for _, sel := range loggedInSelectors {
|
||||
el, err := page.QuerySelector(sel)
|
||||
if err == nil && el != nil && elementVisible(el) {
|
||||
return true
|
||||
func pageHasSecurityVerification(page playwright.Page) bool {
|
||||
for _, frame := range page.Frames() {
|
||||
lowerURL := strings.ToLower(frame.URL())
|
||||
for _, marker := range []string{"photoverify", "normal_validate", "identity_verify", "baxia-punish", "/punish"} {
|
||||
if strings.Contains(lowerURL, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
content, err := frame.Content()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, marker := range []string{"拍摄脸部", "请拖动下方滑块完成验证", "请按住滑块", "安全验证未通过"} {
|
||||
if strings.Contains(content, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
bodyText, err := page.TextContent("body")
|
||||
if err == nil && strings.Contains(bodyText, "消息") && (strings.Contains(bodyText, "订单") || strings.Contains(bodyText, "发闲置")) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -215,7 +447,7 @@ func cleanSingletonFiles(userDataDir string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
|
||||
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool, captchaProfile ...bool) (playwright.BrowserContext, func(), error) {
|
||||
lock := m.accountRenewLock(cookieID)
|
||||
lock.Lock()
|
||||
unlock := func() { lock.Unlock() }
|
||||
@@ -232,8 +464,17 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
userDataDir := filepath.Join("browser_data", "user_"+pureUserID(cookieID))
|
||||
userDataDir, err := resolvePersistentUserDataDir(filepath.Join("browser_data", "user_"+pureUserID(cookieID)))
|
||||
if err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanSingletonFiles(userDataDir)
|
||||
viewport := &playwright.Size{Width: 1280, Height: 720}
|
||||
if len(captchaProfile) > 0 && captchaProfile[0] {
|
||||
viewport = &playwright.Size{Width: 1980, Height: 1024}
|
||||
}
|
||||
var bctx playwright.BrowserContext
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
@@ -241,8 +482,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
UserAgent: playwright.String(quickRenewUA),
|
||||
Viewport: &playwright.Size{Width: 1280, Height: 720},
|
||||
Viewport: viewport,
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
@@ -263,13 +503,25 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if len(snapshot) > 0 {
|
||||
if snapshot != nil {
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, fmt.Errorf("浏览器续期清理旧 Cookie 失败: %w", err)
|
||||
}
|
||||
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
|
||||
m.logger.Warn("浏览器续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, fmt.Errorf("浏览器续期注入 Cookie 快照失败: %w", err)
|
||||
}
|
||||
} else if cookieStr != "" {
|
||||
if err := addCookieStr(bctx, cookieStr); err != nil {
|
||||
m.logger.Warn("浏览器续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, fmt.Errorf("浏览器续期注入 Cookie 字符串失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,55 +533,6 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
func (m *Manager) newEphemeralRefreshContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := m.init(); err != nil {
|
||||
releaseSlot()
|
||||
return nil, nil, err
|
||||
}
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
releaseSlot()
|
||||
return nil, nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
UserAgent: playwright.String("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
|
||||
Viewport: &playwright.Size{Width: 1280, Height: 720},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
})
|
||||
if err != nil {
|
||||
_ = browser.Close()
|
||||
releaseSlot()
|
||||
return nil, nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
}
|
||||
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(`Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] }); window.chrome = { runtime: {} };`)}); err != nil {
|
||||
m.logger.Warn("注入 COOKIES 续期 stealth 脚本失败", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
if len(snapshot) > 0 {
|
||||
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
|
||||
m.logger.Warn("COOKIES续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
} else if cookieStr != "" {
|
||||
if err := addCookieStr(bctx, cookieStr); err != nil {
|
||||
m.logger.Warn("COOKIES续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
release := func() {
|
||||
_ = bctx.Close()
|
||||
_ = browser.Close()
|
||||
releaseSlot()
|
||||
}
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
func quickRenewHeadless(headless bool) bool {
|
||||
return resolveHeadlessRequest(headless)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T) {
|
||||
existing := []cookierefresh.BrowserCookie{
|
||||
{Name: "session", Value: "stale", Domain: ".goofish.com", Path: "/", Expires: 123, HTTPOnly: true, Secure: true, SameSite: "Lax"},
|
||||
{Name: "removed", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "passport", Value: "keep", Domain: ".taobao.com", Path: "/", Secure: true},
|
||||
}
|
||||
got := credentialCookieSnapshot(existing, map[string]string{
|
||||
"session": "fresh",
|
||||
"new": "value",
|
||||
})
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("snapshot len=%d, want 3: %+v", len(got), got)
|
||||
}
|
||||
byName := make(map[string]cookierefresh.BrowserCookie, len(got))
|
||||
for _, cookie := range got {
|
||||
byName[cookie.Name] = cookie
|
||||
}
|
||||
session := byName["session"]
|
||||
if session.Value != "fresh" || session.Expires != 123 || !session.HTTPOnly || session.SameSite != "Lax" {
|
||||
t.Fatalf("existing attributes or fresh value were lost: %+v", session)
|
||||
}
|
||||
if _, exists := byName["removed"]; exists {
|
||||
t.Fatalf("cookie absent from current flat value was resurrected: %+v", got)
|
||||
}
|
||||
if passport := byName["passport"]; passport.Value != "keep" || passport.Domain != ".taobao.com" {
|
||||
t.Fatalf("out-of-scope cookie was lost: %+v", passport)
|
||||
}
|
||||
added := byName["new"]
|
||||
if added.Value != "value" || added.Domain != goofishDot || added.Path != "/" || !added.Secure {
|
||||
t.Fatalf("new cookie defaults mismatch: %+v", added)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T) {
|
||||
existing := []cookierefresh.BrowserCookie{
|
||||
{Name: "token", Value: "old-root", Domain: ".goofish.com", Path: "/"},
|
||||
{Name: "token", Value: "old-im", Domain: "www.goofish.com", Path: "/im", HTTPOnly: true},
|
||||
}
|
||||
got := credentialCookieSnapshot(existing, map[string]string{"token": "fresh"})
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("same-name scoped cookies collapsed: %+v", got)
|
||||
}
|
||||
values := map[string]string{}
|
||||
for _, cookie := range got {
|
||||
values[cookie.Path] = cookie.Value
|
||||
}
|
||||
if values["/"] != "old-root" || values["/im"] != "old-im" {
|
||||
t.Fatalf("ambiguous flat value corrupted scoped cookies: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
|
||||
snapshot := []cookierefresh.BrowserCookie{{Name: "session", Value: "old", Domain: ".goofish.com", Path: "/", Expires: 456}}
|
||||
|
||||
got := reconcileSnapshotWithCurrentCookie(snapshot, "session=new", goofishIMURL)
|
||||
if len(got) != 1 || got[0].Value != "new" || got[0].Expires != 456 {
|
||||
t.Fatalf("flat cookie did not update snapshot without losing attributes: %+v", got)
|
||||
}
|
||||
|
||||
got = reconcileSnapshotWithCurrentCookie(snapshot, "", goofishIMURL)
|
||||
if len(got) != 1 || got[0].Value != "old" {
|
||||
t.Fatalf("snapshot-only renewal input was discarded: %+v", got)
|
||||
}
|
||||
|
||||
got = reconcileSnapshotWithCurrentCookie([]cookierefresh.BrowserCookie{}, "session=stale", goofishIMURL)
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("authoritative empty snapshot must not fall back to flat cookies: %#v", got)
|
||||
}
|
||||
if got := reconcileSnapshotWithCurrentCookie(nil, "session=legacy", goofishIMURL); got != nil {
|
||||
t.Fatalf("missing snapshot should preserve the legacy flat-cookie fallback: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSilentHasLoginURLMatcher(t *testing.T) {
|
||||
if !isSilentHasLoginURL("https://passport.goofish.com/newlogin/silentHasLogin.do?appName=xianyu") {
|
||||
t.Fatal("official silentHasLogin request was not recognized")
|
||||
}
|
||||
if isSilentHasLoginURL("https://passport.goofish.com/newlogin/hasLogin.do") {
|
||||
t.Fatal("ordinary hasLogin request must not be treated as silentHasLogin")
|
||||
}
|
||||
}
|
||||
+38
-43
@@ -2,8 +2,8 @@ package browser
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
@@ -11,8 +11,6 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
var cookieDomains = []string{".goofish.com", ".taobao.com", ".alipay.com"}
|
||||
|
||||
// parseCookieStr 把 "k=v; k2=v2" 解析为 map。
|
||||
func parseCookieStr(s string) map[string]string {
|
||||
m := make(map[string]string)
|
||||
@@ -50,14 +48,12 @@ func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
for _, domain := range cookieDomains {
|
||||
cookies = append(cookies, playwright.OptionalCookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Domain: playwright.String(domain),
|
||||
Path: playwright.String("/"),
|
||||
})
|
||||
}
|
||||
cookies = append(cookies, playwright.OptionalCookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Domain: playwright.String(goofishDot),
|
||||
Path: playwright.String("/"),
|
||||
})
|
||||
}
|
||||
}
|
||||
return cookies
|
||||
@@ -85,6 +81,9 @@ func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwri
|
||||
if c.Expires > 0 {
|
||||
oc.Expires = playwright.Float(c.Expires)
|
||||
}
|
||||
if c.PartitionKey != "" {
|
||||
oc.PartitionKey = playwright.String(c.PartitionKey)
|
||||
}
|
||||
switch c.SameSite {
|
||||
case "Strict":
|
||||
oc.SameSite = playwright.SameSiteAttributeStrict
|
||||
@@ -113,6 +112,9 @@ func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.Browse
|
||||
if c.SameSite != nil {
|
||||
bc.SameSite = string(*c.SameSite)
|
||||
}
|
||||
if c.PartitionKey != nil {
|
||||
bc.PartitionKey = *c.PartitionKey
|
||||
}
|
||||
out = append(out, bc)
|
||||
}
|
||||
return cookierefresh.NormalizeSnapshot(out)
|
||||
@@ -127,38 +129,31 @@ func cookiesToMap(cs []playwright.Cookie) map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// rng 只用于模拟浏览器轨迹和指纹扰动,不用于凭证或安全令牌。
|
||||
// #nosec G404 -- 此处需要可重复的非密码学伪随机序列。
|
||||
var rng = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
// rng is used only for human-like pointer timing in interactive captcha
|
||||
// handling. It must not be used to alter the browser/device fingerprint.
|
||||
// #nosec G404 -- non-cryptographic interaction jitter only.
|
||||
var rng = &lockedRand{value: rand.New(rand.NewSource(time.Now().UnixNano()))}
|
||||
|
||||
// stealthScript 生成隐身 JS(移植自 xianyu_slider_stealth._get_stealth_script)。
|
||||
// 使用占位符并在 Go 运行时替换随机值。
|
||||
type lockedRand struct {
|
||||
mu sync.Mutex
|
||||
value *rand.Rand
|
||||
}
|
||||
|
||||
func (r *lockedRand) Intn(n int) int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.value.Intn(n)
|
||||
}
|
||||
|
||||
func (r *lockedRand) Float64() float64 {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.value.Float64()
|
||||
}
|
||||
|
||||
// stealthScript is intentionally stable. Randomly overriding canvas, WebGL,
|
||||
// hardware, platform, or timing APIs makes one account present a different
|
||||
// device fingerprint on every renewal and is itself a strong risk signal.
|
||||
func stealthScript() string {
|
||||
pluginCount := rng.Intn(6) + 3 // 3-8
|
||||
hwCores := []int{2, 4, 6, 8}[rng.Intn(4)]
|
||||
mem := []int{4, 8, 16}[rng.Intn(3)]
|
||||
effType := []string{"3g", "4g", "5g"}[rng.Intn(3)]
|
||||
rtt := rng.Intn(81) + 20 // 20-100
|
||||
downlink := float64(rng.Intn(901)+100) / 100.0 // 1.00-10.00
|
||||
maxTouch := []int{0, 1, 5, 10}[rng.Intn(4)]
|
||||
battCharging := []string{"true", "false"}[rng.Intn(2)]
|
||||
battLevel := float64(rng.Intn(66)+30) / 100.0 // 0.30-0.95
|
||||
|
||||
repl := strings.NewReplacer(
|
||||
"{{PLUGIN_COUNT}}", strconv.Itoa(pluginCount),
|
||||
"{{LOCALE}}", defaultLang,
|
||||
"{{VW}}", strconv.Itoa(defaultW),
|
||||
"{{VH}}", strconv.Itoa(defaultH),
|
||||
"{{HW_CORES}}", strconv.Itoa(hwCores),
|
||||
"{{MEM}}", strconv.Itoa(mem),
|
||||
"{{TZ}}", defaultTZ,
|
||||
"{{EFF_TYPE}}", effType,
|
||||
"{{RTT}}", strconv.Itoa(rtt),
|
||||
"{{DOWNLINK}}", strconv.FormatFloat(downlink, 'f', 2, 64),
|
||||
"{{MAX_TOUCH}}", strconv.Itoa(maxTouch),
|
||||
"{{BATT_CHARGE}}", battCharging,
|
||||
"{{BATT_LEVEL}}", strconv.FormatFloat(battLevel, 'f', 2, 64),
|
||||
"{{UA}}", defaultUA,
|
||||
)
|
||||
return repl.Replace(stealthTemplate)
|
||||
return stealthTemplate
|
||||
}
|
||||
@@ -22,8 +22,8 @@ func TestParseCookieStrRoundTrip(t *testing.T) {
|
||||
|
||||
func TestParseCookieStrToPlaywright(t *testing.T) {
|
||||
cookies := parseCookieStrToPlaywright("a=1; b=2")
|
||||
if len(cookies) != 2*len(cookieDomains) {
|
||||
t.Fatalf("应按多个域名注入 cookie,got %d", len(cookies))
|
||||
if len(cookies) != 2 {
|
||||
t.Fatalf("每个 Cookie 只应注入一次,got %d", len(cookies))
|
||||
}
|
||||
domains := make(map[string]bool)
|
||||
for _, c := range cookies {
|
||||
@@ -35,10 +35,8 @@ func TestParseCookieStrToPlaywright(t *testing.T) {
|
||||
t.Fatalf("path 应为 /: %+v", c.Path)
|
||||
}
|
||||
}
|
||||
for _, domain := range cookieDomains {
|
||||
if !domains[domain] {
|
||||
t.Fatalf("缺少 domain %s: %+v", domain, domains)
|
||||
}
|
||||
if len(domains) != 1 || !domains[goofishDot] {
|
||||
t.Fatalf("Cookie 只能注入 %s: %+v", goofishDot, domains)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,29 +59,23 @@ func TestCookiesToMapAndStr(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStealthScriptReplaced(t *testing.T) {
|
||||
func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
|
||||
s := stealthScript()
|
||||
if strings.Contains(s, "{{") {
|
||||
t.Fatalf("stealth 脚本仍有未替换占位符: %q", s[:min(200, len(s))])
|
||||
}
|
||||
for _, key := range []string{"webdriver", "chrome", "RTCPeerConnection", "toDataURL"} {
|
||||
if !strings.Contains(s, key) {
|
||||
t.Fatalf("stealth 脚本缺少关键段 %q", key)
|
||||
if !strings.Contains(s, "webdriver") {
|
||||
t.Fatal("stealth 脚本应只规范化 webdriver")
|
||||
}
|
||||
for _, forbidden := range []string{"toDataURL", "WebGL", "hardwareConcurrency", "deviceMemory", "RTCPeerConnection", "Math.random", "navigator.platform"} {
|
||||
if strings.Contains(s, forbidden) {
|
||||
t.Fatalf("stealth 脚本不应伪造 %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStealthScriptUnique(t *testing.T) {
|
||||
// 多次生成应有时不同(随机参数)。
|
||||
a := stealthScript()
|
||||
differ := false
|
||||
for i := 0; i < 10; i++ {
|
||||
if stealthScript() != a {
|
||||
differ = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !differ {
|
||||
t.Fatal("stealth 脚本多次生成应出现随机差异")
|
||||
func TestStealthScriptStable(t *testing.T) {
|
||||
if stealthScript() != stealthScript() {
|
||||
t.Fatal("同一浏览器配置不应产生漂移的指纹脚本")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// TokenCaptchaCookieSnapshot 在滑块引擎退出并释放持久化 Profile 后,重新打开
|
||||
// 同一 Profile 读取最终 Cookie Jar。它不访问任何业务页面,只用于把滑块验证
|
||||
// 已经产生的精确 Domain/Path/HttpOnly/Expires 属性交回 Go 凭证层。
|
||||
func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, "", nil, quickRenewHeadless(headless), true)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer release()
|
||||
return readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
}
|
||||
|
||||
// syncCredentialCookies 为 token 滑块上下文同步 Cookie。普通登录、
|
||||
// 续期、MTOP、Token 和 WebSocket 生产流程不得调用 Chromium。
|
||||
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
|
||||
if len(snapshots) > 0 && snapshots[0] != nil {
|
||||
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(preserved) == 0 {
|
||||
return nil
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
incoming := parseCookieStr(cookieStr)
|
||||
if len(incoming) == 0 {
|
||||
return fmt.Errorf("Cookie为空或格式错误")
|
||||
}
|
||||
existing, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
preserved := credentialCookieSnapshotForURL(cookieSnapshotFromPlaywright(existing), incoming, goofishIMURL)
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
|
||||
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
|
||||
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
|
||||
}
|
||||
|
||||
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
|
||||
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
|
||||
matched := make(map[string]bool, len(incoming))
|
||||
counts := make(map[string]int, len(existing))
|
||||
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
|
||||
counts[cookie.Name]++
|
||||
}
|
||||
for _, cookie := range existing {
|
||||
if !cookieScopeMatches(cookie, rawURL) {
|
||||
if value, ok := incoming[cookie.Name]; ok {
|
||||
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
|
||||
cookie.Value = value
|
||||
}
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
continue
|
||||
}
|
||||
value, ok := incoming[cookie.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if counts[cookie.Name] == 1 {
|
||||
cookie.Value = value
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
for name, value := range incoming {
|
||||
if matched[name] {
|
||||
continue
|
||||
}
|
||||
preserved = append(preserved, cookierefresh.BrowserCookie{
|
||||
Name: name, Value: value, Domain: goofishDot, Path: "/", Secure: true,
|
||||
})
|
||||
}
|
||||
return cookierefresh.NormalizeSnapshot(preserved)
|
||||
}
|
||||
|
||||
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
|
||||
return header != ""
|
||||
}
|
||||
|
||||
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
|
||||
return header
|
||||
}
|
||||
+128
-30
@@ -7,6 +7,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -20,7 +22,6 @@ import (
|
||||
|
||||
// 默认 UA、语言、时区与视口。
|
||||
const (
|
||||
defaultUA = xianyu.BrowserUA
|
||||
defaultW = 1920
|
||||
defaultH = 1080
|
||||
defaultLang = "zh-CN"
|
||||
@@ -36,21 +37,7 @@ func chromiumLaunchArgs() []string {
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--disable-extensions",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--disable-background-timer-throttling",
|
||||
"--disable-backgrounding-occluded-windows",
|
||||
"--disable-renderer-backgrounding",
|
||||
"--disable-features=TranslateUI",
|
||||
"--disable-ipc-flooding-protection",
|
||||
"--disable-default-apps",
|
||||
"--disable-sync",
|
||||
"--disable-translate",
|
||||
"--hide-scrollbars",
|
||||
"--mute-audio",
|
||||
"--no-default-browser-check",
|
||||
"--no-pings",
|
||||
"--lang=zh-CN",
|
||||
}
|
||||
}
|
||||
@@ -93,13 +80,19 @@ type Manager struct {
|
||||
// 允许测试注入自定义 playwright / 安装函数。
|
||||
installFn func() error
|
||||
runFn func() (*playwright.Playwright, error)
|
||||
|
||||
// 仅用于隔离 token 风控引擎编排测试;生产环境为 nil,调用真实实现。
|
||||
tokenCaptchaPrimaryFn tokenCaptchaEngineFunc
|
||||
tokenCaptchaFallbackFn tokenCaptchaEngineFunc
|
||||
}
|
||||
|
||||
type poolEntry struct {
|
||||
cookieID string
|
||||
browser playwright.Browser
|
||||
context playwright.BrowserContext
|
||||
lastUsed time.Time
|
||||
cookieID string
|
||||
browser playwright.Browser
|
||||
context playwright.BrowserContext
|
||||
lastUsed time.Time
|
||||
active int
|
||||
initialLeaseAvailable bool
|
||||
}
|
||||
|
||||
// NewManager 构造。logger 为 nil 用默认。
|
||||
@@ -169,12 +162,71 @@ func (m *Manager) init() error {
|
||||
return
|
||||
}
|
||||
m.pw = pw
|
||||
if err := m.detectBrowserFingerprint(); err != nil {
|
||||
m.initErr = fmt.Errorf("读取 Playwright Chromium 原生指纹失败: %w", err)
|
||||
_ = pw.Stop()
|
||||
m.pw = nil
|
||||
return
|
||||
}
|
||||
m.installed = true
|
||||
m.logger.Info("playwright chromium 就绪")
|
||||
})
|
||||
return m.initErr
|
||||
}
|
||||
|
||||
// Initialize starts Playwright and publishes the bundled Chromium's native
|
||||
// browser identity before any non-browser client sends requests.
|
||||
func (m *Manager) Initialize() error { return m.init() }
|
||||
|
||||
func (m *Manager) detectBrowserFingerprint() error {
|
||||
observed := make(chan http.Header, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
observed <- r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write([]byte("<!doctype html><title>fingerprint</title>"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
b, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = b.Close() }()
|
||||
ctx, err := b.NewContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = ctx.Close() }()
|
||||
page, err := ctx.NewPage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
return err
|
||||
}
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-observed:
|
||||
case <-time.After(5 * time.Second):
|
||||
return fmt.Errorf("等待 Chromium 指纹请求超时")
|
||||
}
|
||||
if strings.TrimSpace(headers.Get("User-Agent")) == "" {
|
||||
return fmt.Errorf("Chromium 返回空 userAgent")
|
||||
}
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
UserAgent: headers.Get("User-Agent"),
|
||||
SecChUA: headers.Get("sec-ch-ua"),
|
||||
Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`),
|
||||
Mobile: headers.Get("sec-ch-ua-mobile"),
|
||||
})
|
||||
m.logger.Info("已读取 Playwright Chromium 原生指纹", "browser_version", b.Version(), "user_agent", headers.Get("User-Agent"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 释放所有浏览器与 playwright。
|
||||
func (m *Manager) Close() error {
|
||||
m.mu.Lock()
|
||||
@@ -207,6 +259,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
page, err := entry.context.NewPage()
|
||||
if err != nil {
|
||||
// context 损坏,丢弃重建一次。
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
entry, err = m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
@@ -214,12 +267,14 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
}
|
||||
page, err = entry.context.NewPage()
|
||||
if err != nil {
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
}
|
||||
release := func() {
|
||||
_ = page.Close()
|
||||
m.touch(cookieID)
|
||||
m.releaseEntry(cookieID, entry)
|
||||
}
|
||||
return page, release, nil
|
||||
}
|
||||
@@ -227,7 +282,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
m.mu.Lock()
|
||||
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
e.lastUsed = time.Now()
|
||||
m.claimEntryLocked(e)
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
@@ -236,7 +291,6 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
|
||||
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
|
||||
m.mu.Lock()
|
||||
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
e.lastUsed = time.Now()
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
@@ -252,9 +306,38 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
|
||||
if !ok || entry == nil {
|
||||
return nil, fmt.Errorf("浏览器池创建返回异常")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if current := m.pool[cookieID]; current == entry {
|
||||
m.claimEntryLocked(entry)
|
||||
m.mu.Unlock()
|
||||
} else {
|
||||
m.mu.Unlock()
|
||||
return nil, fmt.Errorf("浏览器池条目在获取期间已失效")
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func (m *Manager) claimEntryLocked(entry *poolEntry) {
|
||||
entry.lastUsed = time.Now()
|
||||
if entry.initialLeaseAvailable {
|
||||
entry.initialLeaseAvailable = false
|
||||
return
|
||||
}
|
||||
entry.active++
|
||||
}
|
||||
|
||||
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if current := m.pool[cookieID]; current != entry {
|
||||
return
|
||||
}
|
||||
if entry.active > 0 {
|
||||
entry.active--
|
||||
}
|
||||
entry.lastUsed = time.Now()
|
||||
}
|
||||
|
||||
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
@@ -265,7 +348,6 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
context, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
UserAgent: playwright.String(defaultUA),
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
@@ -279,14 +361,18 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
}
|
||||
if cookieStr != "" {
|
||||
if err := addCookieStr(context, cookieStr); err != nil {
|
||||
m.logger.Warn("注入 cookie 失败", "err", err)
|
||||
_ = context.Close()
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("注入 cookie 失败: %w", err)
|
||||
}
|
||||
}
|
||||
entry := &poolEntry{
|
||||
cookieID: cookieID,
|
||||
browser: browser,
|
||||
context: context,
|
||||
lastUsed: time.Now(),
|
||||
cookieID: cookieID,
|
||||
browser: browser,
|
||||
context: context,
|
||||
lastUsed: time.Now(),
|
||||
active: 1,
|
||||
initialLeaseAvailable: true,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.pool[cookieID] = entry
|
||||
@@ -305,6 +391,10 @@ func (m *Manager) touch(cookieID string) {
|
||||
func (m *Manager) evict(cookieID string) {
|
||||
m.mu.Lock()
|
||||
e, ok := m.pool[cookieID]
|
||||
if ok && e.active > 0 {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(m.pool, cookieID)
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
@@ -321,12 +411,17 @@ func (m *Manager) evictIfNeeded() {
|
||||
var oldest *poolEntry
|
||||
var oldestID string
|
||||
for id, e := range m.pool {
|
||||
if e.active > 0 {
|
||||
continue
|
||||
}
|
||||
if oldest == nil || e.lastUsed.Before(oldest.lastUsed) {
|
||||
oldest = e
|
||||
oldestID = id
|
||||
}
|
||||
}
|
||||
delete(m.pool, oldestID)
|
||||
if oldest != nil {
|
||||
delete(m.pool, oldestID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if oldest != nil {
|
||||
closeEntry(oldest, m.logger)
|
||||
@@ -339,7 +434,7 @@ func (m *Manager) CleanupIdle() {
|
||||
m.mu.Lock()
|
||||
var toClose []*poolEntry
|
||||
for id, e := range m.pool {
|
||||
if now.Sub(e.lastUsed) > m.idleTTL {
|
||||
if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
|
||||
toClose = append(toClose, e)
|
||||
delete(m.pool, id)
|
||||
}
|
||||
@@ -368,5 +463,8 @@ func addCookieStr(ctx playwright.BrowserContext, cookieStr string) error {
|
||||
if len(cookies) == 0 {
|
||||
return errors.New("cookie 为空或格式错误")
|
||||
}
|
||||
if err := ctx.ClearCookies(); err != nil {
|
||||
return fmt.Errorf("清理浏览器旧 cookie: %w", err)
|
||||
}
|
||||
return ctx.AddCookies(cookies)
|
||||
}
|
||||
@@ -91,6 +91,44 @@ func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvictIfNeededSkipsActiveEntries(t *testing.T) {
|
||||
m := newTestManager(2)
|
||||
m.pool["active-old"] = &poolEntry{cookieID: "active-old", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
|
||||
m.pool["idle-new"] = &poolEntry{cookieID: "idle-new", lastUsed: time.Now()}
|
||||
m.evictIfNeeded()
|
||||
if _, ok := m.pool["active-old"]; !ok {
|
||||
t.Fatal("正在执行 token 请求的条目不得被淘汰")
|
||||
}
|
||||
if _, ok := m.pool["idle-new"]; ok {
|
||||
t.Fatal("池满时应优先淘汰空闲条目")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
|
||||
m := newTestManager(2)
|
||||
m.pool["active-1"] = &poolEntry{cookieID: "active-1", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
|
||||
m.pool["active-2"] = &poolEntry{cookieID: "active-2", lastUsed: time.Now().Add(-time.Hour), active: 1}
|
||||
m.evictIfNeeded()
|
||||
if len(m.pool) != 2 {
|
||||
t.Fatalf("所有条目活跃时不得强制淘汰,pool=%d", len(m.pool))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
|
||||
m := newTestManager(3)
|
||||
m.idleTTL = time.Minute
|
||||
old := time.Now().Add(-time.Hour)
|
||||
m.pool["active"] = &poolEntry{cookieID: "active", lastUsed: old, active: 1}
|
||||
m.pool["idle"] = &poolEntry{cookieID: "idle", lastUsed: old}
|
||||
m.CleanupIdle()
|
||||
if _, ok := m.pool["active"]; !ok {
|
||||
t.Fatal("CleanupIdle 不得关闭仍有租约的条目")
|
||||
}
|
||||
if _, ok := m.pool["idle"]; ok {
|
||||
t.Fatal("CleanupIdle 应清理过期空闲条目")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarshalCookies 导出包装器等价 cookieMarshal。
|
||||
func TestMarshalCookies(t *testing.T) {
|
||||
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
@@ -18,13 +19,15 @@ const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail"
|
||||
|
||||
// OrderDetail 订单详情(对齐 engine.OrderDetail)。
|
||||
type OrderDetail struct {
|
||||
OrderID string `json:"order_id"`
|
||||
Quantity string `json:"quantity"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
OrderStatus string `json:"order_status"`
|
||||
Amount string `json:"amount"`
|
||||
UpdatedCookies string `json:"-"`
|
||||
OrderID string `json:"order_id"`
|
||||
Quantity string `json:"quantity"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
OrderStatus string `json:"order_status"`
|
||||
Amount string `json:"amount"`
|
||||
UpdatedCookies string `json:"-"`
|
||||
CookieSnapshot []cookierefresh.BrowserCookie `json:"-"`
|
||||
CookieSnapshotComplete bool `json:"-"`
|
||||
}
|
||||
|
||||
// orderStatusMap 移植自 order_fetcher_optimized._parse_api_response。纯映射,可单测。
|
||||
@@ -48,6 +51,12 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
} else if directErr != nil {
|
||||
m.logger.Warn("MTop 订单详情获取失败,回退浏览器", "order_id", orderID, "err", directErr)
|
||||
}
|
||||
// A shared Chromium context owns one mutable Cookie Jar. Serialize browser
|
||||
// fallback refreshes for the account so concurrent batch rows cannot clear
|
||||
// and re-inject different snapshots underneath each other.
|
||||
browserCredentialLock := m.accountRenewLock("order_credential_" + cookieID)
|
||||
browserCredentialLock.Lock()
|
||||
defer browserCredentialLock.Unlock()
|
||||
if err := m.init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,6 +65,11 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
if session := mtop.CookieSessionFromContext(ctx); session != nil {
|
||||
if err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
|
||||
return nil, fmt.Errorf("订单详情同步完整 Cookie Jar: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
var mu sync.Mutex
|
||||
var apiBody map[string]any
|
||||
@@ -121,6 +135,19 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
|
||||
// DOM 补充(金额 / SKU)。
|
||||
parseDOMContent(page, od)
|
||||
allCookies, cookieErr := page.Context().Cookies()
|
||||
if cookieErr != nil {
|
||||
return nil, fmt.Errorf("读取订单详情浏览器 Cookie Jar: %w", cookieErr)
|
||||
}
|
||||
od.CookieSnapshot = cookieSnapshotFromPlaywright(allCookies)
|
||||
if od.CookieSnapshot == nil {
|
||||
od.CookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
od.CookieSnapshotComplete = true
|
||||
od.UpdatedCookies = currentCookieHeader(od.CookieSnapshot, goofishIMURL)
|
||||
if session := mtop.CookieSessionFromContext(ctx); session != nil {
|
||||
session.ReplaceSnapshot(od.CookieSnapshot)
|
||||
}
|
||||
if od.Amount == "" {
|
||||
title, _ := page.Title()
|
||||
m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", page.URL(), "api_captured", body != nil, "observed_apis", observedAPIs)
|
||||
|
||||
@@ -30,11 +30,15 @@ var loginSuccessSelectors = []string{
|
||||
const (
|
||||
passwordVerificationWaitInterval = 10 * time.Second
|
||||
passwordVerificationMaxWait = 5 * time.Minute
|
||||
passwordLoginPageLoadWait = 2 * time.Second
|
||||
passwordLoginTabWait = 1500 * time.Millisecond
|
||||
passwordLoginAfterSubmitWait = 3 * time.Second
|
||||
passwordLoginCompletionWait = 5 * time.Second
|
||||
)
|
||||
|
||||
// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。
|
||||
// 移植自 xianyu_slider_stealth.login_with_password_playwright。
|
||||
// userDataDir:空字符串用临时目录,非空则持久化(跨次复用 session)。
|
||||
// userDataDir:空字符串使用按账号划分的默认持久化目录。
|
||||
func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
|
||||
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, nil)
|
||||
}
|
||||
@@ -45,32 +49,20 @@ func (m *Manager) PasswordLoginWithEvents(ctx context.Context, account, password
|
||||
}
|
||||
|
||||
func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
|
||||
if err := m.init(); err != nil {
|
||||
return nil, err
|
||||
if strings.TrimSpace(account) == "" || strings.TrimSpace(password) == "" {
|
||||
return nil, fmt.Errorf("账号或密码不能为空")
|
||||
}
|
||||
|
||||
if userDataDir == "" {
|
||||
userDataDir = filepath.Join("browser_data", "user_"+sanitize(cookieID))
|
||||
if strings.TrimSpace(userDataDir) == "" {
|
||||
userDataDir = filepath.Join("browser_data", "user_"+pureUserID(cookieID))
|
||||
}
|
||||
headless = quickRenewHeadless(headless)
|
||||
|
||||
bctx, err := m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
UserAgent: playwright.String(defaultUA),
|
||||
Viewport: &playwright.Size{Width: 1980, Height: 1024},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
})
|
||||
bctx, release, err := m.newPersistentPasswordContext(ctx, cookieID, userDataDir, headless)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("启动持久化浏览器失败: %w", err)
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
|
||||
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
@@ -78,17 +70,12 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
}
|
||||
|
||||
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateNetworkidle,
|
||||
Timeout: playwright.Float(60000),
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("访问 goofish.com/im 超时", "err", err)
|
||||
}
|
||||
|
||||
// 检查是否已经登录。
|
||||
if checkLoginSuccess(page) {
|
||||
m.logger.Info("密码登录:已有有效 session,无需重新登录", "cookieID", cookieID)
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
time.Sleep(passwordLoginPageLoadWait)
|
||||
|
||||
if clickQuickEnter(page) {
|
||||
m.logger.Info("密码登录:已点击[快速进入],等待页面刷新", "cookieID", cookieID)
|
||||
@@ -108,42 +95,56 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
if clickPasswordLoginTab(page) {
|
||||
time.Sleep(passwordLoginTabWait)
|
||||
}
|
||||
|
||||
// 在主页和所有 iframe 中找登录表单。
|
||||
idEl, pwdEl, submitEl := findLoginForm(page)
|
||||
if idEl == nil {
|
||||
return nil, fmt.Errorf("未找到登录表单,可能页面结构已变更")
|
||||
time.Sleep(2 * time.Second)
|
||||
if handled := detectAndHandlePasswordSlider(page, m.logger); handled {
|
||||
m.logger.Info("密码登录:未找到表单时已处理滑块", "cookieID", cookieID)
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
if checkLoginSuccess(page) {
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
return nil, fmt.Errorf("未找到登录表单且未检测到登录状态")
|
||||
}
|
||||
if pwdEl == nil {
|
||||
return nil, fmt.Errorf("未找到密码输入框,可能页面结构已变更")
|
||||
}
|
||||
|
||||
if err := idEl.Click(); err == nil {
|
||||
_ = page.Fill(getCSSSelector(idEl, loginIDSelectors), account)
|
||||
}
|
||||
if err := pwdEl.Click(); err == nil {
|
||||
_ = page.Fill(getCSSSelector(pwdEl, loginPwdSelectors), password)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
_ = idEl.Fill(account)
|
||||
time.Sleep(secondsDuration(randomFloat(0.5, 1.0)))
|
||||
_ = pwdEl.Fill(password)
|
||||
time.Sleep(secondsDuration(randomFloat(0.5, 1.0)))
|
||||
// 同意协议复选框(若存在)。
|
||||
if cb, err := page.QuerySelector("#fm-agreement-checkbox"); err == nil && cb != nil {
|
||||
if checked, _ := cb.GetAttribute("checked"); checked == "" {
|
||||
if cb := findPasswordElement(page, []string{"#fm-agreement-checkbox"}); cb != nil {
|
||||
checked, _ := cb.Evaluate(`el => Boolean(el.checked)`)
|
||||
if isChecked, _ := checked.(bool); !isChecked {
|
||||
_ = cb.Click()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
if submitEl != nil {
|
||||
_ = submitEl.Click()
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
time.Sleep(passwordLoginAfterSubmitWait)
|
||||
|
||||
// 登录后可能出现滑块。
|
||||
content, _ := page.Content()
|
||||
if strings.Contains(content, "nc-container") || strings.Contains(content, "scratch-captcha") {
|
||||
scratch := isScratchCaptcha(content)
|
||||
m.logger.Info("密码登录后出现滑块,自动处理")
|
||||
if err := solveSlider(page, scratch, m.logger); err != nil {
|
||||
m.logger.Warn("密码登录滑块处理失败", "err", err)
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
if detectAndHandlePasswordSlider(page, m.logger) {
|
||||
m.logger.Info("密码登录后滑块处理完成")
|
||||
}
|
||||
time.Sleep(passwordLoginCompletionWait)
|
||||
time.Sleep(time.Second)
|
||||
if detectAndHandlePasswordSlider(page, m.logger) {
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
|
||||
if !checkLoginSuccess(page) {
|
||||
return m.handlePasswordLoginPending(ctx, page, onEvent)
|
||||
@@ -153,6 +154,34 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
|
||||
func findPasswordElement(page playwright.Page, selectors []string) playwright.ElementHandle {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
if el := queryFirst(frame, selectors); el != nil {
|
||||
return el
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func clickPasswordLoginTab(page playwright.Page) bool {
|
||||
el := findPasswordElement(page, []string{"a.password-login-tab-item"})
|
||||
return el != nil && el.Click() == nil
|
||||
}
|
||||
|
||||
func detectAndHandlePasswordSlider(page playwright.Page, logger sliderLogger) bool {
|
||||
content, _ := page.Content()
|
||||
if !strings.Contains(content, "nc-container") && !strings.Contains(content, "scratch-captcha") {
|
||||
// 参考实现把“未发现滑块”也视为检测流程成功;调用方据此保持相同的等待节奏。
|
||||
return true
|
||||
}
|
||||
if err := solveSlider(page, isScratchCaptcha(content), logger); err != nil {
|
||||
logger.Warn("密码登录滑块处理失败", "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func quickEnterCookiesUsable(cookies map[string]string) bool {
|
||||
if len(cookies) == 0 {
|
||||
return false
|
||||
@@ -344,14 +373,6 @@ func findLoginForm(page playwright.Page) (idEl, pwdEl, submitEl playwright.Eleme
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
// getCSSSelector 返回元素对应的第一个匹配选择器(用于 page.Fill)。
|
||||
func getCSSSelector(el playwright.ElementHandle, selectors []string) string {
|
||||
if el == nil {
|
||||
return selectors[0]
|
||||
}
|
||||
return selectors[0] // page.Fill 用首选器即可,元素已 Click
|
||||
}
|
||||
|
||||
func sanitize(s string) string {
|
||||
r := strings.NewReplacer("/", "_", "\\", "_", ":", "_", " ", "_")
|
||||
return r.Replace(s)
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package browser
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
|
||||
html := `<div id="baxia-punish"><div class="captcha-question">请找两个松鼠</div></div>`
|
||||
@@ -59,3 +64,61 @@ func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
|
||||
t.Fatal("空 Cookie 不应视为成功")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
|
||||
if passwordLoginPageLoadWait != 2*time.Second || passwordLoginTabWait != 1500*time.Millisecond ||
|
||||
passwordLoginAfterSubmitWait != 3*time.Second || passwordLoginCompletionWait != 5*time.Second {
|
||||
t.Fatalf("密码登录等待节奏未与参考实现一致: page=%s tab=%s submit=%s completion=%s",
|
||||
passwordLoginPageLoadWait, passwordLoginTabWait, passwordLoginAfterSubmitWait, passwordLoginCompletionWait)
|
||||
}
|
||||
if passwordVerificationWaitInterval != 10*time.Second || passwordVerificationMaxWait != 5*time.Minute {
|
||||
t.Fatalf("人工验证轮询节奏未与参考实现一致: interval=%s max=%s",
|
||||
passwordVerificationWaitInterval, passwordVerificationMaxWait)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium")
|
||||
opts := passwordPersistentContextOptions(true)
|
||||
if opts.Headless == nil || !*opts.Headless {
|
||||
t.Fatal("密码登录应按调用参数使用无头模式")
|
||||
}
|
||||
if opts.UserAgent != nil {
|
||||
t.Fatalf("密码登录不应覆盖 Playwright Chromium 原生 UA: %v", *opts.UserAgent)
|
||||
}
|
||||
if opts.Viewport == nil || opts.Viewport.Width != 1980 || opts.Viewport.Height != 1024 {
|
||||
t.Fatalf("密码登录 viewport=%+v", opts.Viewport)
|
||||
}
|
||||
if opts.Locale == nil || *opts.Locale != "zh-CN" || opts.TimezoneId == nil || *opts.TimezoneId != "Asia/Shanghai" {
|
||||
t.Fatalf("密码登录区域参数异常: locale=%v timezone=%v", opts.Locale, opts.TimezoneId)
|
||||
}
|
||||
if opts.AcceptDownloads == nil || !*opts.AcceptDownloads || opts.IgnoreHttpsErrors == nil || !*opts.IgnoreHttpsErrors {
|
||||
t.Fatal("密码登录下载/HTTPS 参数未与参考实现一致")
|
||||
}
|
||||
if opts.ExtraHttpHeaders["Accept-Language"] != "zh-CN,zh;q=0.9,en;q=0.8" {
|
||||
t.Fatalf("Accept-Language=%q", opts.ExtraHttpHeaders["Accept-Language"])
|
||||
}
|
||||
if opts.Timeout == nil || *opts.Timeout != 30000 {
|
||||
t.Fatalf("密码登录启动超时=%v", opts.Timeout)
|
||||
}
|
||||
if opts.ExecutablePath == nil || *opts.ExecutablePath != "/opt/chromium" {
|
||||
t.Fatalf("Chromium 路径=%v", opts.ExecutablePath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
|
||||
m := &Manager{}
|
||||
for _, tc := range []struct {
|
||||
account string
|
||||
password string
|
||||
}{
|
||||
{account: "", password: "secret"},
|
||||
{account: "account", password: ""},
|
||||
{account: " ", password: "secret"},
|
||||
} {
|
||||
_, err := m.PasswordLogin(context.Background(), tc.account, tc.password, "cookie-id", "", true)
|
||||
if err == nil || !strings.Contains(err.Error(), "账号或密码不能为空") {
|
||||
t.Fatalf("account=%q password=%q: err=%v", tc.account, tc.password, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,6 @@ func TestSanitize(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetCSSSelector 始终返回首选器(元素句柄仅占位,nil 与非 nil 同结果)。
|
||||
func TestGetCSSSelector(t *testing.T) {
|
||||
selectors := []string{"#user", "input[name=user]"}
|
||||
if got := getCSSSelector(nil, selectors); got != "#user" {
|
||||
t.Errorf("应返回首选器,got %q", got)
|
||||
}
|
||||
// 单元素切片。
|
||||
if got := getCSSSelector(nil, []string{"#pwd"}); got != "#pwd" {
|
||||
t.Errorf("单元素应返回该项,got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPureUserIDMatchesReferenceRule(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"foo_1234567890": "foo",
|
||||
|
||||
@@ -36,8 +36,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
defer func() { _ = browser.Close() }()
|
||||
|
||||
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
UserAgent: playwright.String(defaultUA),
|
||||
Viewport: &playwright.Size{Width: 400, Height: 400},
|
||||
Viewport: &playwright.Size{Width: 1100, Height: 760},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
})
|
||||
@@ -94,23 +93,17 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
// 访问 /im 触发 unb 写入。
|
||||
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateNetworkidle,
|
||||
// A single normal home-page load runs goofish-auto-login and loginuser.get.
|
||||
// Do not reload repeatedly: the browser client does not do that and the
|
||||
// duplicate burst is an avoidable risk signal.
|
||||
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(20000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("访问 goofish.com/im 异常", "err", err)
|
||||
m.logger.Warn("访问 goofish.com 首页异常", "err", err)
|
||||
}
|
||||
m.logger.Info("goto /im 完成", "current_url", logsafe.URL(page.URL()))
|
||||
|
||||
// reload 后再等网络空闲,确保 unb 写入。
|
||||
if _, err := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateNetworkidle,
|
||||
Timeout: playwright.Float(15000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("reload 异常", "err", err)
|
||||
}
|
||||
m.logger.Info("reload 完成", "current_url", logsafe.URL(page.URL()))
|
||||
m.logger.Info("首页加载完成", "current_url", logsafe.URL(page.URL()))
|
||||
sleep(quickRenewPageLoadWait)
|
||||
|
||||
// 轮询直到 unb 出现或超时(最长15秒)。
|
||||
var all []playwright.Cookie
|
||||
|
||||
+620
-60
@@ -1,6 +1,7 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
@@ -18,8 +19,18 @@ var sliderTrackSelectors = []string{
|
||||
"#nc_1_n1t", ".nc_scale", ".nc_1_n1t",
|
||||
}
|
||||
var sliderRetrySelectors = []string{
|
||||
".nc-lang-cnt", "#nc_1_n1z",
|
||||
"#nc_1_refresh1", ".nc_iconfont.btn_refresh", ".errloading",
|
||||
"[class*='refresh']", ".nc-container",
|
||||
}
|
||||
var sliderExplicitRetrySelectors = sliderRetrySelectors[:4]
|
||||
var sliderSuccessSelectors = []string{
|
||||
".nc_ok_icon", ".nc-lang-cnt .nc_ok", "#nc_1_n1z.nc_ok",
|
||||
}
|
||||
|
||||
const (
|
||||
sliderSuccessCheckAttempts = 4
|
||||
sliderSuccessCheckInterval = 400 * time.Millisecond
|
||||
)
|
||||
|
||||
// trajectoryPoint 轨迹中的单个采样点。
|
||||
type trajectoryPoint struct {
|
||||
@@ -28,24 +39,85 @@ type trajectoryPoint struct {
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
// generateTrajectory 生成仿人类滑动轨迹(移植自 _generate_physics_trajectory)。
|
||||
// 过冲 100-110%,15-25 步,progress^1.5 加速曲线。纯数学,可单测。
|
||||
func generateTrajectory(distance float64) []trajectoryPoint {
|
||||
overshoot := distance * (1.0 + 0.1*float64(rng.Intn(11))/10.0) // 100-110%
|
||||
steps := 15 + rng.Intn(11) // 15-25
|
||||
baseDelay := 3.0 + float64(rng.Intn(6)) // 3-8 ms
|
||||
type slideMotionMetrics struct {
|
||||
points int
|
||||
plannedDelay time.Duration
|
||||
targetMovement time.Duration
|
||||
movementElapsed time.Duration
|
||||
totalElapsed time.Duration
|
||||
finalLeft string
|
||||
finalClass string
|
||||
}
|
||||
|
||||
pts := make([]trajectoryPoint, steps)
|
||||
for i := 0; i < steps; i++ {
|
||||
progress := float64(i+1) / float64(steps)
|
||||
x := overshoot * math.Pow(progress, 1.5)
|
||||
y := float64(rng.Intn(3)) // 0-2 px
|
||||
d := time.Duration((baseDelay * (0.9 + 0.2*float64(rng.Intn(11))/10.0)) * float64(time.Millisecond))
|
||||
pts[i] = trajectoryPoint{x: x, y: y, delay: d}
|
||||
type sliderResetResult struct {
|
||||
method string
|
||||
selector string
|
||||
ready bool
|
||||
err error
|
||||
}
|
||||
|
||||
// generateTrajectory mirrors the reference Playwright engine's short
|
||||
// acceleration/constant/deceleration trajectory. Each point is a high-level
|
||||
// browser protocol call, so generating dozens of points makes the drag unlike
|
||||
// the reference implementation even when the wall-clock duration is similar.
|
||||
func generateTrajectory(distance float64) []trajectoryPoint {
|
||||
requestedSteps := 5 + rng.Intn(2)
|
||||
totalDuration := randomFloat(0.010, 0.020)
|
||||
avgDelay := totalDuration / float64(requestedSteps)
|
||||
|
||||
accelRatio := 0.35 + randomFloat(-0.05, 0.05)
|
||||
decelRatio := 0.30 + randomFloat(-0.05, 0.05)
|
||||
accelSteps := max(2, int(math.Round(float64(requestedSteps)*accelRatio)))
|
||||
decelSteps := max(2, int(math.Round(float64(requestedSteps)*decelRatio)))
|
||||
constantSteps := max(2, requestedSteps-accelSteps-decelSteps)
|
||||
|
||||
accelDistance := distance * randomFloat(0.25, 0.35)
|
||||
constantDistance := distance * randomFloat(0.50, 0.60)
|
||||
decelDistance := distance - accelDistance - constantDistance
|
||||
pts := make([]trajectoryPoint, 0, accelSteps+constantSteps+decelSteps)
|
||||
|
||||
for i := 1; i <= accelSteps; i++ {
|
||||
progress := float64(i) / float64(accelSteps)
|
||||
pts = append(pts, trajectoryPoint{
|
||||
x: accelDistance * progress * progress,
|
||||
y: randomFloat(-1, 1),
|
||||
delay: secondsDuration(avgDelay * randomFloat(1, 1.3)),
|
||||
})
|
||||
}
|
||||
for i := 1; i <= constantSteps; i++ {
|
||||
progress := float64(i) / float64(constantSteps)
|
||||
delay := avgDelay * randomFloat(0.85, 1.15)
|
||||
if randomFloat(0, 1) < 0.03 {
|
||||
delay *= randomFloat(1.1, 1.3)
|
||||
}
|
||||
pts = append(pts, trajectoryPoint{
|
||||
x: accelDistance + constantDistance*progress,
|
||||
y: randomFloat(-1, 1) * 0.6,
|
||||
delay: secondsDuration(delay),
|
||||
})
|
||||
}
|
||||
for i := 1; i <= decelSteps; i++ {
|
||||
progress := float64(i) / float64(decelSteps)
|
||||
pts = append(pts, trajectoryPoint{
|
||||
x: accelDistance + constantDistance + decelDistance*(1-math.Pow(1-progress, 2)),
|
||||
y: randomFloat(-1, 1) * 0.4,
|
||||
delay: secondsDuration(avgDelay * randomFloat(1.1, 1.5)),
|
||||
})
|
||||
}
|
||||
if len(pts) > 0 {
|
||||
pts[len(pts)-1].x = distance
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
func randomFloat(minValue, maxValue float64) float64 {
|
||||
return minValue + rng.Float64()*(maxValue-minValue)
|
||||
}
|
||||
|
||||
func secondsDuration(seconds float64) time.Duration {
|
||||
return time.Duration(seconds * float64(time.Second))
|
||||
}
|
||||
|
||||
// isScratchCaptcha 判断是否为刮刮乐验证码(只滑 25-35%)。
|
||||
func isScratchCaptcha(content string) bool {
|
||||
return strings.Contains(content, "scratch-captcha") ||
|
||||
@@ -53,17 +125,42 @@ func isScratchCaptcha(content string) bool {
|
||||
strings.Contains(content, "scratch-captcha-slider")
|
||||
}
|
||||
|
||||
// solveSlider 在 page 上求解滑块,最多重试 3 次。
|
||||
func solveSlider(page playwright.Page, scratch bool, logger interface {
|
||||
type sliderLogger interface {
|
||||
Info(string, ...any)
|
||||
Warn(string, ...any)
|
||||
Error(string, ...any)
|
||||
}) error {
|
||||
}
|
||||
|
||||
// solveSlider 在 page 上求解滑块,最多重试 3 次。
|
||||
func solveSlider(page playwright.Page, scratch bool, logger sliderLogger) error {
|
||||
return solveSliderStrict(page, scratch, logger, nil, time.Time{})
|
||||
}
|
||||
|
||||
func solveSliderStrict(page playwright.Page, scratch bool, logger sliderLogger, previousX5Sec map[string]struct{}, deadline time.Time) error {
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
btn, track, _, err := findSliderElements(page)
|
||||
if !deadline.IsZero() && time.Now().After(deadline) {
|
||||
return fmt.Errorf("滑块验证超过浏览器总超时")
|
||||
}
|
||||
btn, track, frame, err := findSliderElements(page)
|
||||
if err != nil {
|
||||
logger.Warn("未找到滑块元素", "attempt", attempt, "err", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
var verified bool
|
||||
if previousX5Sec != nil {
|
||||
verified = waitForStrictSliderSuccess(page, previousX5Sec, 600*time.Millisecond, 100*time.Millisecond)
|
||||
} else {
|
||||
verified = checkSliderSuccess(page)
|
||||
}
|
||||
if verified {
|
||||
logger.Info("滑块元素消失且严格成功条件成立", "attempt", attempt+1)
|
||||
return nil
|
||||
}
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(context.Background(), page, deadline)
|
||||
logSliderReset(logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return fmt.Errorf("未找到滑块且无法恢复: %w", reset.err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -72,41 +169,135 @@ func solveSlider(page playwright.Page, scratch bool, logger interface {
|
||||
logger.Warn("计算滑块距离失败", "err", err)
|
||||
dist = 200 // 降级默认值
|
||||
}
|
||||
logSliderAttemptStart(logger, page, frame, btn, track, attempt+1, dist)
|
||||
|
||||
if err := simulateSlide(page, btn, dist); err != nil {
|
||||
motion, err := simulateSlide(page, btn, dist)
|
||||
if err != nil {
|
||||
logger.Warn("模拟滑动失败", "err", err)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(context.Background(), page, deadline)
|
||||
logSliderReset(logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return fmt.Errorf("滑块执行失败后无法恢复: %w", reset.err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
logger.Info("滑块拖动已释放",
|
||||
"attempt", attempt+1,
|
||||
"points", motion.points,
|
||||
"planned_delay", motion.plannedDelay,
|
||||
"target_movement", motion.targetMovement,
|
||||
"movement_elapsed", motion.movementElapsed,
|
||||
"total_elapsed", motion.totalElapsed,
|
||||
"final_left", motion.finalLeft,
|
||||
"final_class", motion.finalClass,
|
||||
)
|
||||
time.Sleep(800 * time.Millisecond)
|
||||
|
||||
if checkSliderSuccess(page) {
|
||||
logger.Info("滑块验证成功", "attempt", attempt)
|
||||
var verified bool
|
||||
if previousX5Sec != nil {
|
||||
confirmTimeout := 5 * time.Second
|
||||
if !deadline.IsZero() {
|
||||
confirmTimeout = min(confirmTimeout, time.Until(deadline.Add(-2*time.Second)))
|
||||
if confirmTimeout < time.Second {
|
||||
confirmTimeout = time.Second
|
||||
}
|
||||
}
|
||||
verified = waitForStrictSliderSuccess(page, previousX5Sec, confirmTimeout, 300*time.Millisecond)
|
||||
} else {
|
||||
verified = checkSliderSuccess(page)
|
||||
}
|
||||
if verified {
|
||||
logger.Info("滑块验证成功", "attempt", attempt+1)
|
||||
return nil
|
||||
}
|
||||
// 失败后尝试点重试按钮。
|
||||
clickRetry(page)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
logSliderFailureState(logger, page, attempt+1)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(context.Background(), page, deadline)
|
||||
logSliderReset(logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return fmt.Errorf("滑块第 %d 次失败后无法恢复: %w", attempt+1, reset.err)
|
||||
}
|
||||
if err := sleepUntil(context.Background(), deadline, secondsDuration(randomFloat(1, 2))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("滑块验证 3 次均失败")
|
||||
}
|
||||
|
||||
func waitForStrictSliderSuccess(page playwright.Page, previousValues map[string]struct{}, timeout, interval time.Duration) bool {
|
||||
if timeout <= 0 || interval <= 0 {
|
||||
return false
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
cookies, err := page.Context().Cookies()
|
||||
if err == nil {
|
||||
_, fresh := freshX5Cookies(cookies, previousValues)
|
||||
if fresh && !isPunishURL(page.URL()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if hasDefinitiveSliderFailure(page) {
|
||||
return false
|
||||
}
|
||||
if time.Now().Add(interval).After(deadline) {
|
||||
return false
|
||||
}
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
|
||||
func isPunishURL(rawURL string) bool {
|
||||
lower := strings.ToLower(rawURL)
|
||||
for _, marker := range []string{"punish", "x5step=2", "action=captcha", "purecaptcha", "/captcha"} {
|
||||
if strings.Contains(lower, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// findSliderElements 在 page 和所有 iframe 中找到按钮与轨道元素。
|
||||
func findSliderElements(page playwright.Page) (btn, track playwright.ElementHandle, frame playwright.Frame, err error) {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
// The current NC page normally exposes this exact pair. Require both
|
||||
// elements to be visible in the same frame before trying broad fallbacks.
|
||||
for _, f := range frames {
|
||||
b := queryFirst(f, sliderButtonSelectors)
|
||||
b := queryVisible(f, "#nc_1_n1z")
|
||||
t := queryVisible(f, "#nc_1_n1t")
|
||||
if b != nil && t != nil {
|
||||
return b, t, f, nil
|
||||
}
|
||||
}
|
||||
for _, f := range frames {
|
||||
b := queryFirstVisible(f, sliderButtonSelectors)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
t := queryFirst(f, sliderTrackSelectors)
|
||||
return b, t, f, nil
|
||||
t := queryFirstVisible(f, sliderTrackSelectors)
|
||||
if t != nil {
|
||||
return b, t, f, nil
|
||||
}
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("未找到滑块元素")
|
||||
return nil, nil, nil, fmt.Errorf("未找到同一 frame 内可见的滑块按钮和轨道")
|
||||
}
|
||||
|
||||
func queryVisible(f playwright.Frame, selector string) playwright.ElementHandle {
|
||||
el, err := f.QuerySelector(selector)
|
||||
if err != nil || el == nil || !elementVisible(el) {
|
||||
return nil
|
||||
}
|
||||
return el
|
||||
}
|
||||
|
||||
// queryFirst is shared by non-slider browser flows that intentionally handle
|
||||
// visibility after locating an element. Slider code uses queryFirstVisible.
|
||||
func queryFirst(f playwright.Frame, selectors []string) playwright.ElementHandle {
|
||||
for _, sel := range selectors {
|
||||
el, err := f.QuerySelector(sel)
|
||||
for _, selector := range selectors {
|
||||
el, err := f.QuerySelector(selector)
|
||||
if err == nil && el != nil {
|
||||
return el
|
||||
}
|
||||
@@ -114,15 +305,35 @@ func queryFirst(f playwright.Frame, selectors []string) playwright.ElementHandle
|
||||
return nil
|
||||
}
|
||||
|
||||
func queryFirstVisible(f playwright.Frame, selectors []string) playwright.ElementHandle {
|
||||
for _, sel := range selectors {
|
||||
if el := queryVisible(f, sel); el != nil {
|
||||
return el
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// calculateSlideDistance 计算需要滑动的像素距离。
|
||||
func calculateSlideDistance(btn, track playwright.ElementHandle, scratch bool) (float64, error) {
|
||||
var dist float64
|
||||
if track != nil {
|
||||
tb, err := track.BoundingBox()
|
||||
if err == nil && tb != nil {
|
||||
bb, err2 := btn.BoundingBox()
|
||||
if err2 == nil && bb != nil {
|
||||
dist = tb.Width - bb.Width + float64(rng.Intn(2)) - 0.5
|
||||
// Use the exact usable rail width. Overshoot is interpreted as a failed
|
||||
// drag by the current captcha implementation.
|
||||
if precise, err := btn.Evaluate(`(button, track) => {
|
||||
const buttonRect = button.getBoundingClientRect();
|
||||
const trackRect = track.getBoundingClientRect();
|
||||
return trackRect.width - buttonRect.width;
|
||||
}`, track); err == nil {
|
||||
if value, ok := precise.(float64); ok && value > 0 {
|
||||
dist = value
|
||||
}
|
||||
}
|
||||
if dist <= 0 {
|
||||
tb, trackErr := track.BoundingBox()
|
||||
bb, buttonErr := btn.BoundingBox()
|
||||
if trackErr == nil && buttonErr == nil && tb != nil && bb != nil {
|
||||
dist = tb.Width - bb.Width
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,68 +341,417 @@ func calculateSlideDistance(btn, track playwright.ElementHandle, scratch bool) (
|
||||
dist = 220 + float64(rng.Intn(40))
|
||||
}
|
||||
if scratch {
|
||||
dist *= 0.25 + float64(rng.Intn(11))*0.01 // 25-35%
|
||||
dist *= randomFloat(0.25, 0.35)
|
||||
}
|
||||
return dist, nil
|
||||
}
|
||||
|
||||
// simulateSlide 模拟人类滑动。
|
||||
func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance float64) error {
|
||||
// simulateSlide 模拟人类滑动,并返回协议调用后的真实墙钟耗时。
|
||||
func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance float64) (slideMotionMetrics, error) {
|
||||
metrics := slideMotionMetrics{}
|
||||
totalStarted := time.Now()
|
||||
time.Sleep(secondsDuration(randomFloat(0.1, 0.3)))
|
||||
bb, err := btn.BoundingBox()
|
||||
if err != nil || bb == nil {
|
||||
return fmt.Errorf("无法获取按钮位置")
|
||||
return metrics, fmt.Errorf("无法获取按钮位置")
|
||||
}
|
||||
startX := bb.X + bb.Width/2
|
||||
startY := bb.Y + bb.Height/2
|
||||
mouse := page.Mouse()
|
||||
|
||||
// 移到按钮旁边再到中心,模拟自然接近。
|
||||
_ = mouse.Move(startX-float64(10+rng.Intn(20)), startY+float64(rng.Intn(31)-15),
|
||||
playwright.MouseMoveOptions{Steps: playwright.Int(3 + rng.Intn(3))})
|
||||
time.Sleep(100*time.Millisecond + time.Duration(rng.Intn(200))*time.Millisecond)
|
||||
_ = mouse.Move(startX, startY, playwright.MouseMoveOptions{Steps: playwright.Int(2)})
|
||||
time.Sleep(100*time.Millisecond + time.Duration(rng.Intn(200))*time.Millisecond)
|
||||
// 第一阶段:从左侧附近自然接近滑块。
|
||||
_ = mouse.Move(startX+randomFloat(-30, -10), startY+randomFloat(-15, 15),
|
||||
playwright.MouseMoveOptions{Steps: playwright.Int(5 + rng.Intn(6))})
|
||||
time.Sleep(secondsDuration(randomFloat(0.15, 0.30)))
|
||||
_ = mouse.Move(startX, startY, playwright.MouseMoveOptions{Steps: playwright.Int(3 + rng.Intn(4))})
|
||||
time.Sleep(secondsDuration(randomFloat(0.10, 0.25)))
|
||||
|
||||
// 第二阶段:悬停与按下前停顿。
|
||||
_ = btn.Hover(playwright.ElementHandleHoverOptions{Timeout: playwright.Float(2000)})
|
||||
time.Sleep(secondsDuration(randomFloat(0.10, 0.30)))
|
||||
_ = mouse.Move(startX, startY)
|
||||
time.Sleep(secondsDuration(randomFloat(0.05, 0.15)))
|
||||
|
||||
if err := mouse.Down(); err != nil {
|
||||
return err
|
||||
return metrics, err
|
||||
}
|
||||
time.Sleep(secondsDuration(randomFloat(0.05, 0.15)))
|
||||
|
||||
pts := generateTrajectory(distance)
|
||||
metrics.points = len(pts)
|
||||
for _, pt := range pts {
|
||||
_ = mouse.Move(startX+pt.x, startY+pt.y, playwright.MouseMoveOptions{Steps: playwright.Int(1)})
|
||||
time.Sleep(pt.delay)
|
||||
metrics.plannedDelay += pt.delay
|
||||
}
|
||||
// The reference implementation gets roughly 80-150ms of CDP round-trip
|
||||
// latency per high-level point. The Go driver is often much faster, so keep
|
||||
// the same six-point shape while compensating to the observed 480-900ms
|
||||
// movement window using wall-clock time.
|
||||
metrics.targetMovement = secondsDuration(randomFloat(0.48, 0.90))
|
||||
movementStarted := time.Now()
|
||||
currentX, currentY := startX, startY
|
||||
for index, pt := range pts {
|
||||
currentX, currentY = startX+pt.x, startY+pt.y
|
||||
if err := mouse.Move(currentX, currentY, playwright.MouseMoveOptions{Steps: playwright.Int(1 + rng.Intn(3))}); err != nil {
|
||||
_ = mouse.Up()
|
||||
return metrics, err
|
||||
}
|
||||
planned := time.Duration(float64(pt.delay) * randomFloat(0.9, 1.1))
|
||||
remainingPoints := len(pts) - index
|
||||
delay := compensatedTrajectoryDelay(planned, metrics.targetMovement, time.Since(movementStarted), remainingPoints)
|
||||
time.Sleep(delay)
|
||||
}
|
||||
metrics.movementElapsed = time.Since(movementStarted)
|
||||
if isScratchCaptchaFromPage(page) {
|
||||
time.Sleep(secondsDuration(randomFloat(0.3, 0.5)))
|
||||
}
|
||||
time.Sleep(secondsDuration(randomFloat(0.02, 0.05)))
|
||||
if err := mouse.Up(); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
time.Sleep(secondsDuration(randomFloat(0.01, 0.03)))
|
||||
_, _ = btn.Evaluate(`(slider, point) => {
|
||||
const event = new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
view: window,
|
||||
clientX: point.x,
|
||||
clientY: point.y,
|
||||
button: 0,
|
||||
});
|
||||
slider.dispatchEvent(event);
|
||||
}`, map[string]any{"x": currentX, "y": currentY})
|
||||
metrics.finalLeft = readSliderLeft(btn)
|
||||
metrics.finalClass, _ = btn.GetAttribute("class")
|
||||
metrics.totalElapsed = time.Since(totalStarted)
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
return mouse.Up()
|
||||
func compensatedTrajectoryDelay(planned, target, elapsed time.Duration, remainingPoints int) time.Duration {
|
||||
if remainingPoints <= 0 || target <= elapsed {
|
||||
return planned
|
||||
}
|
||||
compensated := (target - elapsed) / time.Duration(remainingPoints)
|
||||
if compensated > planned {
|
||||
return compensated
|
||||
}
|
||||
return planned
|
||||
}
|
||||
|
||||
func readSliderLeft(button playwright.ElementHandle) string {
|
||||
value, err := button.Evaluate(`button => {
|
||||
if (button.style && button.style.left) return button.style.left;
|
||||
const parent = button.parentElement;
|
||||
if (!parent) return null;
|
||||
return (button.getBoundingClientRect().left - parent.getBoundingClientRect().left) + 'px';
|
||||
}`)
|
||||
if err != nil || value == nil {
|
||||
return "<unavailable>"
|
||||
}
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
|
||||
func isScratchCaptchaFromPage(page playwright.Page) bool {
|
||||
content, err := page.Content()
|
||||
return err == nil && isScratchCaptcha(content)
|
||||
}
|
||||
|
||||
type sliderContainerState struct {
|
||||
found bool
|
||||
visible bool
|
||||
visibilityKnown bool
|
||||
}
|
||||
|
||||
// checkSliderSuccess 检查验证是否成功(nc-container 消失或 frame 断开)。
|
||||
func checkSliderSuccess(page playwright.Page) bool {
|
||||
for attempt := 0; attempt < sliderSuccessCheckAttempts; attempt++ {
|
||||
if sliderContainerStatesSucceeded(readSliderContainerStates(page)) || hasVisibleSliderSuccessMarker(page) {
|
||||
return true
|
||||
}
|
||||
if attempt+1 < sliderSuccessCheckAttempts {
|
||||
time.Sleep(sliderSuccessCheckInterval)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hasVisibleSliderSuccessMarker(page playwright.Page) bool {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
if queryFirstVisible(frame, sliderSuccessSelectors) != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func readSliderContainerStates(page playwright.Page) []sliderContainerState {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
states := make([]sliderContainerState, 0, len(frames))
|
||||
for _, f := range frames {
|
||||
el, err := f.QuerySelector(".nc-container")
|
||||
if err != nil || el == nil {
|
||||
continue
|
||||
}
|
||||
vis, err := el.IsVisible()
|
||||
if err != nil || !vis {
|
||||
return true
|
||||
}
|
||||
states = append(states, sliderContainerState{
|
||||
found: true,
|
||||
visible: vis,
|
||||
visibilityKnown: err == nil,
|
||||
})
|
||||
}
|
||||
return true // 找不到容器也视为成功
|
||||
return states
|
||||
}
|
||||
|
||||
func clickRetry(page playwright.Page) {
|
||||
func sliderContainerStatesSucceeded(states []sliderContainerState) bool {
|
||||
for _, state := range states {
|
||||
if state.found && (!state.visibilityKnown || state.visible) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func clickRetry(page playwright.Page) (string, error) {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, f := range frames {
|
||||
for _, sel := range sliderRetrySelectors {
|
||||
el, err := f.QuerySelector(sel)
|
||||
if err == nil && el != nil {
|
||||
_ = el.Click()
|
||||
return
|
||||
for _, sel := range sliderExplicitRetrySelectors {
|
||||
if el := queryVisible(f, sel); el != nil {
|
||||
if err := el.Click(playwright.ElementHandleClickOptions{
|
||||
Timeout: playwright.Float(2000),
|
||||
}); err != nil {
|
||||
return sel, err
|
||||
}
|
||||
return sel, nil
|
||||
}
|
||||
}
|
||||
// .nc-container is only safe to click once it actually contains a
|
||||
// failure/retry prompt. Clicking the initial container can start a drag.
|
||||
if el := queryVisible(f, ".nc-container"); el != nil {
|
||||
text, _ := el.InnerText()
|
||||
if sliderRetryText(text) {
|
||||
if err := el.Click(playwright.ElementHandleClickOptions{Timeout: playwright.Float(2000)}); err != nil {
|
||||
return ".nc-container", err
|
||||
}
|
||||
return ".nc-container", nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("未找到可见的滑块失败重试控件")
|
||||
}
|
||||
|
||||
func sliderRetryText(text string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(text))
|
||||
for _, marker := range []string{"重试", "刷新", "失败", "retry", "refresh", "failed"} {
|
||||
if strings.Contains(lower, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func resetSliderForRetry(ctx context.Context, page playwright.Page, deadline time.Time) sliderResetResult {
|
||||
result := sliderResetResult{}
|
||||
selector, clickErr := clickRetry(page)
|
||||
if clickErr != nil {
|
||||
// AWSC can publish the failure control shortly after its verification
|
||||
// request completes. Give it a brief chance before reloading the page.
|
||||
waitDeadline := boundedDeadline(deadline, 800*time.Millisecond)
|
||||
for time.Now().Before(waitDeadline) {
|
||||
if err := sleepUntil(ctx, waitDeadline, 100*time.Millisecond); err != nil {
|
||||
break
|
||||
}
|
||||
selector, clickErr = clickRetry(page)
|
||||
if clickErr == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if clickErr == nil {
|
||||
result.method = "click"
|
||||
result.selector = selector
|
||||
result.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 4*time.Second))
|
||||
if result.ready {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
result.method = "reload"
|
||||
reloadTimeout := boundedDuration(deadline, 8*time.Second)
|
||||
if reloadTimeout <= 0 {
|
||||
result.err = fmt.Errorf("滑块恢复前已超过总超时")
|
||||
return result
|
||||
}
|
||||
_, reloadErr := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(float64(reloadTimeout.Milliseconds())),
|
||||
})
|
||||
if reloadErr != nil {
|
||||
result.err = fmt.Errorf("重载滑块验证页: %w", reloadErr)
|
||||
return result
|
||||
}
|
||||
result.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 5*time.Second))
|
||||
if !result.ready {
|
||||
result.err = fmt.Errorf("重载后滑块未重新出现")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func waitForSliderReady(ctx context.Context, page playwright.Page, deadline time.Time) bool {
|
||||
for {
|
||||
btn, track, _, err := findSliderElements(page)
|
||||
if err == nil && sliderAtOrigin(btn, track) {
|
||||
return true
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return false
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, 100*time.Millisecond); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sliderAtOrigin(btn, track playwright.ElementHandle) bool {
|
||||
buttonBox, buttonErr := btn.BoundingBox()
|
||||
trackBox, trackErr := track.BoundingBox()
|
||||
if buttonErr != nil || trackErr != nil || buttonBox == nil || trackBox == nil {
|
||||
return false
|
||||
}
|
||||
return math.Abs(buttonBox.X-trackBox.X) <= 3
|
||||
}
|
||||
|
||||
func boundedDeadline(deadline time.Time, limit time.Duration) time.Time {
|
||||
bounded := time.Now().Add(limit)
|
||||
if !deadline.IsZero() && deadline.Before(bounded) {
|
||||
return deadline
|
||||
}
|
||||
return bounded
|
||||
}
|
||||
|
||||
func boundedDuration(deadline time.Time, limit time.Duration) time.Duration {
|
||||
if deadline.IsZero() {
|
||||
return limit
|
||||
}
|
||||
remaining := time.Until(deadline)
|
||||
if remaining < limit {
|
||||
return remaining
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
func logSliderAttemptStart(logger sliderLogger, page playwright.Page, frame playwright.Frame, btn, track playwright.ElementHandle, attempt int, distance float64) {
|
||||
buttonBox, _ := btn.BoundingBox()
|
||||
trackBox, _ := track.BoundingBox()
|
||||
buttonClass, _ := btn.GetAttribute("class")
|
||||
trackClass, _ := track.GetAttribute("class")
|
||||
interference := detectInjectedPageTools(page)
|
||||
logger.Info("滑块拖动准备",
|
||||
"attempt", attempt,
|
||||
"page", redactedPageURL(page.URL()),
|
||||
"frame", redactedPageURL(frame.URL()),
|
||||
"distance_px", fmt.Sprintf("%.2f", distance),
|
||||
"button_box", formatBoundingBox(buttonBox),
|
||||
"track_box", formatBoundingBox(trackBox),
|
||||
"button_class", buttonClass,
|
||||
"track_class", trackClass,
|
||||
"injected_tools", strings.Join(interference, ","),
|
||||
)
|
||||
}
|
||||
|
||||
func logSliderFailureState(logger sliderLogger, page playwright.Page, attempt int) {
|
||||
button, track, _, _ := findSliderElements(page)
|
||||
buttonStyle, buttonClass, trackClass := "<missing>", "<missing>", "<missing>"
|
||||
if button != nil {
|
||||
buttonStyle, _ = button.GetAttribute("style")
|
||||
buttonClass, _ = button.GetAttribute("class")
|
||||
}
|
||||
if track != nil {
|
||||
trackClass, _ = track.GetAttribute("class")
|
||||
}
|
||||
retrySelector, retryText := visibleSliderRetryState(page)
|
||||
logger.Warn("滑块验证失败态",
|
||||
"attempt", attempt,
|
||||
"page", redactedPageURL(page.URL()),
|
||||
"button_style", buttonStyle,
|
||||
"button_class", buttonClass,
|
||||
"track_class", trackClass,
|
||||
"retry_selector", retrySelector,
|
||||
"retry_text", retryText,
|
||||
)
|
||||
}
|
||||
|
||||
func logSliderReset(logger sliderLogger, attempt int, reset sliderResetResult) {
|
||||
if reset.err != nil {
|
||||
logger.Warn("滑块失败后恢复失败", "attempt", attempt, "method", reset.method, "selector", reset.selector, "err", reset.err)
|
||||
return
|
||||
}
|
||||
logger.Info("滑块失败后已恢复", "attempt", attempt, "method", reset.method, "selector", reset.selector, "ready", reset.ready)
|
||||
}
|
||||
|
||||
func visibleSliderRetryState(page playwright.Page) (string, string) {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
for _, selector := range sliderExplicitRetrySelectors {
|
||||
if el := queryVisible(frame, selector); el != nil {
|
||||
text, _ := el.InnerText()
|
||||
return selector, truncateSliderText(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func hasDefinitiveSliderFailure(page playwright.Page) bool {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
for _, selector := range sliderRetrySelectors[:3] {
|
||||
if queryVisible(frame, selector) != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func detectInjectedPageTools(page playwright.Page) []string {
|
||||
markers := []struct {
|
||||
name string
|
||||
selector string
|
||||
}{
|
||||
{name: "requestly", selector: "rq-implicit-test-rule-widget"},
|
||||
{name: "pikpak", selector: "#__PIKPAK_EXTENSION__"},
|
||||
{name: "deepl", selector: "deepl-input-controller"},
|
||||
{name: "immersive-translate", selector: "#immersive-translate-browser-popup"},
|
||||
}
|
||||
found := make([]string, 0, len(markers))
|
||||
for _, marker := range markers {
|
||||
if el, err := page.MainFrame().QuerySelector(marker.selector); err == nil && el != nil {
|
||||
found = append(found, marker.name)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func redactedPageURL(rawURL string) string {
|
||||
if index := strings.IndexAny(rawURL, "?#"); index >= 0 {
|
||||
return rawURL[:index]
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
|
||||
func formatBoundingBox(box *playwright.Rect) string {
|
||||
if box == nil {
|
||||
return "<missing>"
|
||||
}
|
||||
return fmt.Sprintf("x=%.1f y=%.1f w=%.1f h=%.1f", box.X, box.Y, box.Width, box.Height)
|
||||
}
|
||||
|
||||
func truncateSliderText(text string) string {
|
||||
text = strings.Join(strings.Fields(text), " ")
|
||||
if len(text) > 160 {
|
||||
return text[:160]
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// extractPageCookies 从 page 的 context 提取所有 cookie 返回 map。
|
||||
|
||||
@@ -3,32 +3,77 @@ package browser
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGenerateTrajectoryShape(t *testing.T) {
|
||||
pts := generateTrajectory(200)
|
||||
if len(pts) < 15 || len(pts) > 25 {
|
||||
t.Fatalf("steps 应在 15-25,got %d", len(pts))
|
||||
if len(pts) != 6 {
|
||||
t.Fatalf("参考三阶段轨迹应生成 6 个高层点,got %d", len(pts))
|
||||
}
|
||||
// 最终 x 应在 distance*1.0 ~ distance*1.1 附近(最后一点在过冲范围内)。
|
||||
// 参考实现明确禁止超调,最后一点必须精确落在目标位置。
|
||||
last := pts[len(pts)-1]
|
||||
if last.x < 190 || last.x > 240 {
|
||||
t.Fatalf("末端 x 应约等于 distance*1.05,got %.1f", last.x)
|
||||
if math.Abs(last.x-200) > 1e-9 {
|
||||
t.Fatalf("末端 x 必须精确等于 distance,got %.6f", last.x)
|
||||
}
|
||||
// x 应单调不减(加速曲线)。
|
||||
// 三阶段轨迹不超调,且保持向目标方向移动。
|
||||
for i := 1; i < len(pts); i++ {
|
||||
if pts[i].x < pts[i-1].x-1 {
|
||||
if pts[i].x < pts[i-1].x {
|
||||
t.Fatalf("轨迹 x 不单调: pts[%d]=%.1f < pts[%d]=%.1f", i, pts[i].x, i-1, pts[i-1].x)
|
||||
}
|
||||
if pts[i].x > 200 {
|
||||
t.Fatalf("主引擎轨迹不应超调: pts[%d]=%.1f", i, pts[i].x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateTrajectoryDelay(t *testing.T) {
|
||||
pts := generateTrajectory(150)
|
||||
var total time.Duration
|
||||
for i, pt := range pts {
|
||||
if pt.delay < 2*1e6 || pt.delay > 15*1e6 { // 2ms-15ms in nanoseconds
|
||||
total += pt.delay
|
||||
if pt.delay <= 0 || pt.delay > 8*time.Millisecond {
|
||||
t.Fatalf("delay[%d]=%v 超出合理范围", i, pt.delay)
|
||||
}
|
||||
if pt.y < -1 || pt.y > 1 {
|
||||
t.Fatalf("y[%d]=%.2f 超出合理抖动", i, pt.y)
|
||||
}
|
||||
}
|
||||
if total < 8*time.Millisecond || total > 35*time.Millisecond {
|
||||
t.Fatalf("总轨迹时长不合理: %s", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompensatedTrajectoryDelayUsesWallClockBudget(t *testing.T) {
|
||||
planned := 3 * time.Millisecond
|
||||
if got := compensatedTrajectoryDelay(planned, 600*time.Millisecond, 100*time.Millisecond, 5); got != 100*time.Millisecond {
|
||||
t.Fatalf("应按剩余墙钟预算补偿,got %s", got)
|
||||
}
|
||||
if got := compensatedTrajectoryDelay(planned, 100*time.Millisecond, 120*time.Millisecond, 2); got != planned {
|
||||
t.Fatalf("达到目标时长后应保留原始微延迟,got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliderSelectorsMatchReferencePriority(t *testing.T) {
|
||||
if sliderButtonSelectors[0] != "#nc_1_n1z" || sliderTrackSelectors[0] != "#nc_1_n1t" {
|
||||
t.Fatalf("滑块精确选择器必须优先: button=%q track=%q", sliderButtonSelectors[0], sliderTrackSelectors[0])
|
||||
}
|
||||
wantRetry := []string{"#nc_1_refresh1", ".nc_iconfont.btn_refresh", ".errloading"}
|
||||
for i, want := range wantRetry {
|
||||
if sliderRetrySelectors[i] != want {
|
||||
t.Fatalf("重试选择器[%d]=%q want %q", i, sliderRetrySelectors[i], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliderRetryTextOnlyAcceptsFailurePrompts(t *testing.T) {
|
||||
for _, text := range []string{"验证失败,点击框体重试", "刷新验证码", "Retry verification"} {
|
||||
if !sliderRetryText(text) {
|
||||
t.Fatalf("应识别重试文案 %q", text)
|
||||
}
|
||||
}
|
||||
if sliderRetryText("请按住滑块,拖动到最右边") {
|
||||
t.Fatal("初始滑块容器不应被当作重试控件")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +89,53 @@ func TestIsScratchCaptcha(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPunishURL(t *testing.T) {
|
||||
for _, rawURL := range []string{
|
||||
"https://example/punish?x=1", "https://example/?x5step=2",
|
||||
"https://example/?action=captcha", "https://example/PURECAPTCHA",
|
||||
"https://example/captcha/check",
|
||||
} {
|
||||
if !isPunishURL(rawURL) {
|
||||
t.Fatalf("应识别风控 URL: %s", rawURL)
|
||||
}
|
||||
}
|
||||
if isPunishURL("https://www.goofish.com/item/1") {
|
||||
t.Fatal("普通页面不应识别为风控 URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptchaURLExpiredRequiresReferenceErrorPage(t *testing.T) {
|
||||
if !captchaURLExpired("<main>抱歉,页面访问出现了问题</main>") {
|
||||
t.Fatal("应识别参考项目定义的验证链接过期页")
|
||||
}
|
||||
if captchaURLExpired("<main>验证码加载中,请稍候</main>") {
|
||||
t.Fatal("普通验证码页面不应被当作链接过期")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliderContainerStatesSucceeded(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
states []sliderContainerState
|
||||
want bool
|
||||
}{
|
||||
{name: "container missing", want: true},
|
||||
{name: "container hidden", states: []sliderContainerState{{found: true, visibilityKnown: true}}, want: true},
|
||||
{name: "container visible", states: []sliderContainerState{{found: true, visible: true, visibilityKnown: true}}, want: false},
|
||||
{name: "visibility unknown", states: []sliderContainerState{{found: true}}, want: false},
|
||||
{name: "one visible", states: []sliderContainerState{{found: true, visibilityKnown: true}, {found: true, visible: true, visibilityKnown: true}}, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := sliderContainerStatesSucceeded(tt.states); got != tt.want {
|
||||
t.Fatalf("sliderContainerStatesSucceeded()=%v want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrajectoryPhysics(t *testing.T) {
|
||||
// progress^1.5 曲线:中间步进应比线性大。
|
||||
pts := generateTrajectory(100)
|
||||
// 前半段增量应小于后半段增量(加速)。
|
||||
half := len(pts) / 2
|
||||
frontIncrement := pts[half-1].x - pts[0].x
|
||||
backIncrement := pts[len(pts)-1].x - pts[half].x
|
||||
|
||||
+18
-294
@@ -1,298 +1,22 @@
|
||||
package browser
|
||||
|
||||
// stealthTemplate 是浏览器侧反检测 JS。模板使用 {{占位符}},由
|
||||
// stealthScript() 在 Go 侧生成随机值后替换。JS 本身未改动。
|
||||
// Keep Chromium's native fingerprint intact. The launch arguments already
|
||||
// disable AutomationControlled; this only removes well-known automation
|
||||
// globals and never patches input events or hardware properties.
|
||||
const stealthTemplate = `
|
||||
// 隐藏webdriver属性
|
||||
Object.defineProperty(navigator, 'webdriver', {
|
||||
get: () => undefined,
|
||||
});
|
||||
|
||||
// 隐藏自动化相关属性
|
||||
delete navigator.__proto__.webdriver;
|
||||
delete window.navigator.webdriver;
|
||||
delete window.navigator.__proto__.webdriver;
|
||||
|
||||
// 模拟真实浏览器环境
|
||||
window.chrome = {
|
||||
runtime: {},
|
||||
loadTimes: function() {},
|
||||
csi: function() {},
|
||||
app: {}
|
||||
};
|
||||
|
||||
// 覆盖plugins - 随机化
|
||||
const pluginCount = {{PLUGIN_COUNT}};
|
||||
Object.defineProperty(navigator, 'plugins', {
|
||||
get: () => Array.from({length: pluginCount}, (_, i) => ({
|
||||
name: 'Plugin' + i,
|
||||
description: 'Plugin ' + i
|
||||
})),
|
||||
});
|
||||
|
||||
// 覆盖languages
|
||||
Object.defineProperty(navigator, 'languages', {
|
||||
get: () => ['{{LOCALE}}', 'zh', 'en'],
|
||||
});
|
||||
|
||||
// 模拟真实的屏幕信息
|
||||
Object.defineProperty(screen, 'availWidth', { get: () => {{VW}} });
|
||||
Object.defineProperty(screen, 'availHeight', { get: () => {{VH}} - 40 });
|
||||
Object.defineProperty(screen, 'width', { get: () => {{VW}} });
|
||||
Object.defineProperty(screen, 'height', { get: () => {{VH}} });
|
||||
|
||||
// 隐藏自动化检测 - 随机化硬件信息
|
||||
Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => {{HW_CORES}} });
|
||||
Object.defineProperty(navigator, 'deviceMemory', { get: () => {{MEM}} });
|
||||
|
||||
// 模拟真实的时区
|
||||
Object.defineProperty(Intl.DateTimeFormat.prototype, 'resolvedOptions', {
|
||||
value: function() {
|
||||
return { timeZone: '{{TZ}}' };
|
||||
}
|
||||
});
|
||||
|
||||
// 隐藏自动化痕迹
|
||||
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array;
|
||||
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise;
|
||||
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol;
|
||||
|
||||
// 模拟有头模式的特征
|
||||
Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0 });
|
||||
Object.defineProperty(navigator, 'platform', { get: () => 'Win32' });
|
||||
Object.defineProperty(navigator, 'vendor', { get: () => 'Google Inc.' });
|
||||
Object.defineProperty(navigator, 'vendorSub', { get: () => '' });
|
||||
Object.defineProperty(navigator, 'productSub', { get: () => '20030107' });
|
||||
|
||||
// 模拟真实的连接信息
|
||||
Object.defineProperty(navigator, 'connection', {
|
||||
get: () => ({
|
||||
effectiveType: "{{EFF_TYPE}}",
|
||||
rtt: {{RTT}},
|
||||
downlink: {{DOWNLINK}}
|
||||
})
|
||||
});
|
||||
|
||||
// 隐藏无头模式特征
|
||||
Object.defineProperty(navigator, 'headless', { get: () => undefined });
|
||||
Object.defineProperty(window, 'outerHeight', { get: () => {{VH}} });
|
||||
Object.defineProperty(window, 'outerWidth', { get: () => {{VW}} });
|
||||
|
||||
// 模拟真实的媒体设备
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
get: () => ({
|
||||
enumerateDevices: () => Promise.resolve([])
|
||||
}),
|
||||
});
|
||||
|
||||
// 隐藏自动化检测特征
|
||||
Object.defineProperty(navigator, '__webdriver_script_fn', { get: () => undefined });
|
||||
Object.defineProperty(navigator, '__webdriver_evaluate', { get: () => undefined });
|
||||
Object.defineProperty(navigator, '__webdriver_unwrapped', { get: () => undefined });
|
||||
Object.defineProperty(navigator, '__fxdriver_evaluate', { get: () => undefined });
|
||||
Object.defineProperty(navigator, '__driver_evaluate', { get: () => undefined });
|
||||
Object.defineProperty(navigator, '__webdriver_script_func', { get: () => undefined });
|
||||
|
||||
// 隐藏Playwright特定的对象
|
||||
delete window.playwright;
|
||||
delete window.__playwright;
|
||||
delete window.__pw_manual;
|
||||
delete window.__pw_original;
|
||||
|
||||
// 模拟真实的用户代理
|
||||
Object.defineProperty(navigator, 'userAgent', {
|
||||
get: () => '{{UA}}'
|
||||
});
|
||||
|
||||
// 隐藏自动化相关的全局变量
|
||||
delete window.webdriver;
|
||||
delete window.__webdriver_script_fn;
|
||||
delete window.__webdriver_evaluate;
|
||||
delete window.__webdriver_unwrapped;
|
||||
delete window.__fxdriver_evaluate;
|
||||
delete window.__driver_evaluate;
|
||||
delete window.__webdriver_script_func;
|
||||
delete window._selenium;
|
||||
delete window._phantom;
|
||||
delete window.callPhantom;
|
||||
delete window.phantom;
|
||||
delete window.Buffer;
|
||||
delete window.emit;
|
||||
delete window.spawn;
|
||||
|
||||
// Canvas指纹随机化
|
||||
const originalToDataURL = HTMLCanvasElement.prototype.toDataURL;
|
||||
HTMLCanvasElement.prototype.toDataURL = function() {
|
||||
const context = this.getContext('2d');
|
||||
if (context) {
|
||||
const imageData = context.getImageData(0, 0, this.width, this.height);
|
||||
const data = imageData.data;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
if (Math.random() < 0.001) {
|
||||
data[i] = Math.floor(Math.random() * 256);
|
||||
}
|
||||
}
|
||||
context.putImageData(imageData, 0, 0);
|
||||
}
|
||||
return originalToDataURL.apply(this, arguments);
|
||||
};
|
||||
|
||||
// 音频指纹随机化
|
||||
const originalGetChannelData = AudioBuffer.prototype.getChannelData;
|
||||
AudioBuffer.prototype.getChannelData = function(channel) {
|
||||
const data = originalGetChannelData.call(this, channel);
|
||||
for (let i = 0; i < data.length; i += 1000) {
|
||||
if (Math.random() < 0.01) {
|
||||
data[i] += Math.random() * 0.0001;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
// WebGL指纹随机化
|
||||
const originalGetParameter = WebGLRenderingContext.prototype.getParameter;
|
||||
WebGLRenderingContext.prototype.getParameter = function(parameter) {
|
||||
if (parameter === 37445) { // UNMASKED_VENDOR_WEBGL
|
||||
return 'Intel Inc.';
|
||||
}
|
||||
if (parameter === 37446) { // UNMASKED_RENDERER_WEBGL
|
||||
return 'Intel Iris OpenGL Engine';
|
||||
}
|
||||
return originalGetParameter.call(this, parameter);
|
||||
};
|
||||
|
||||
// 模拟真实的鼠标事件
|
||||
const originalAddEventListener = EventTarget.prototype.addEventListener;
|
||||
EventTarget.prototype.addEventListener = function(type, listener, options) {
|
||||
if (type === 'mousedown' || type === 'mouseup' || type === 'mousemove') {
|
||||
const originalListener = listener;
|
||||
listener = function(event) {
|
||||
setTimeout(() => originalListener.call(this, event), Math.random() * 10);
|
||||
};
|
||||
}
|
||||
return originalAddEventListener.call(this, type, listener, options);
|
||||
};
|
||||
|
||||
// 随机化字体检测
|
||||
Object.defineProperty(document, 'fonts', {
|
||||
get: () => ({
|
||||
ready: Promise.resolve(),
|
||||
check: () => true,
|
||||
load: () => Promise.resolve([])
|
||||
})
|
||||
});
|
||||
|
||||
// 增强鼠标移动轨迹记录
|
||||
let mouseMovements = [];
|
||||
let lastMouseTime = Date.now();
|
||||
document.addEventListener('mousemove', function(e) {
|
||||
const now = Date.now();
|
||||
const timeDiff = now - lastMouseTime;
|
||||
mouseMovements.push({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
time: now,
|
||||
timeDiff: timeDiff
|
||||
});
|
||||
lastMouseTime = now;
|
||||
if (mouseMovements.length > 100) {
|
||||
mouseMovements.shift();
|
||||
}
|
||||
}, true);
|
||||
|
||||
// 模拟真实的电池API
|
||||
if (navigator.getBattery) {
|
||||
const originalGetBattery = navigator.getBattery;
|
||||
navigator.getBattery = async function() {
|
||||
const battery = await originalGetBattery.call(navigator);
|
||||
Object.defineProperty(battery, 'charging', { get: () => {{BATT_CHARGE}} });
|
||||
Object.defineProperty(battery, 'level', { get: () => {{BATT_LEVEL}} });
|
||||
return battery;
|
||||
};
|
||||
}
|
||||
|
||||
// 伪装鼠标移动加速度(反检测关键)
|
||||
let velocityProfile = [];
|
||||
window.addEventListener('mousemove', function(e) {
|
||||
const now = performance.now();
|
||||
velocityProfile.push({ x: e.clientX, y: e.clientY, t: now });
|
||||
if (velocityProfile.length > 50) velocityProfile.shift();
|
||||
}, true);
|
||||
|
||||
// 伪装Permission API
|
||||
const originalQuery = Permissions.prototype.query;
|
||||
Permissions.prototype.query = function(parameters) {
|
||||
if (parameters.name === 'notifications') {
|
||||
return Promise.resolve({ state: 'denied' });
|
||||
}
|
||||
return originalQuery.apply(this, arguments);
|
||||
};
|
||||
|
||||
// 伪装Performance API
|
||||
const originalNow = Performance.prototype.now;
|
||||
Performance.prototype.now = function() {
|
||||
return originalNow.call(this) + Math.random() * 0.1;
|
||||
};
|
||||
|
||||
// 伪装RTCPeerConnection(WebRTC指纹)
|
||||
if (window.RTCPeerConnection) {
|
||||
const originalRTC = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = function(...args) {
|
||||
const pc = new originalRTC(...args);
|
||||
const originalCreateOffer = pc.createOffer;
|
||||
pc.createOffer = function(...args) {
|
||||
return originalCreateOffer.apply(this, args).then(offer => {
|
||||
offer.sdp = offer.sdp.replace(/a=fingerprint:.*\r\n/g,
|
||||
'a=fingerprint:sha-256 ' + Array.from({length:64}, ()=>Math.floor(Math.random()*16).toString(16)).join('') + '\r\n');
|
||||
return offer;
|
||||
});
|
||||
};
|
||||
return pc;
|
||||
};
|
||||
}
|
||||
|
||||
// 🔑 关键优化:隐藏CDP运行时特征
|
||||
Object.defineProperty(navigator, 'webdriver', {
|
||||
get: () => undefined
|
||||
});
|
||||
|
||||
// 🔑 隐藏自动化控制特征
|
||||
window.navigator.chrome = {
|
||||
runtime: {},
|
||||
loadTimes: function() {},
|
||||
csi: function() {},
|
||||
app: {}
|
||||
};
|
||||
|
||||
// 🔑 隐藏Playwright特征
|
||||
delete window.__playwright;
|
||||
delete window.__pw_manual;
|
||||
delete window.__PW_inspect;
|
||||
|
||||
// 🔑 伪装chrome对象(防止检测headless)
|
||||
if (!window.chrome) {
|
||||
window.chrome = {};
|
||||
}
|
||||
window.chrome.runtime = {
|
||||
id: undefined,
|
||||
sendMessage: function() {},
|
||||
connect: function() {}
|
||||
};
|
||||
|
||||
// 🔑 伪装Permissions API
|
||||
const originalQuery2 = window.navigator.permissions.query;
|
||||
window.navigator.permissions.query = (parameters) => (
|
||||
parameters.name === 'notifications' ?
|
||||
Promise.resolve({ state: Notification.permission }) :
|
||||
originalQuery2(parameters)
|
||||
);
|
||||
|
||||
// 🔑 覆盖Function.prototype.toString以隐藏代理
|
||||
const oldToString = Function.prototype.toString;
|
||||
Function.prototype.toString = function() {
|
||||
if (this === navigator.permissions.query) {
|
||||
return 'function query() { [native code] }';
|
||||
}
|
||||
return oldToString.call(this);
|
||||
};
|
||||
(() => {
|
||||
try {
|
||||
Object.defineProperty(Navigator.prototype, 'webdriver', {
|
||||
configurable: true,
|
||||
get: () => undefined,
|
||||
});
|
||||
} catch (_) {}
|
||||
for (const key of [
|
||||
'__playwright', '__pw_manual', '__PW_inspect', '__pw_original',
|
||||
'webdriver', '__webdriver_script_fn', '__webdriver_evaluate',
|
||||
'__webdriver_unwrapped', '__driver_evaluate'
|
||||
]) {
|
||||
try { delete window[key]; } catch (_) {}
|
||||
}
|
||||
})();
|
||||
`
|
||||
@@ -2,19 +2,129 @@ package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
// TokenCaptchaURLProvider is called after Chromium is ready, so the token API
|
||||
// can return a fresh punish URL instead of using one that expired while waiting.
|
||||
const (
|
||||
tokenCaptchaCookieWait = 15 * time.Second
|
||||
tokenCaptchaCookiePoll = 250 * time.Millisecond
|
||||
tokenCaptchaBrowserTTL = 45 * time.Second
|
||||
)
|
||||
|
||||
type browserCookieReader interface {
|
||||
Cookies(urls ...string) ([]playwright.Cookie, error)
|
||||
}
|
||||
|
||||
// TokenCaptchaURLProvider obtains a fresh punish URL between browser attempts,
|
||||
// after the previous persistent profile has been closed.
|
||||
type TokenCaptchaURLProvider func(ctx context.Context, currentCookies string) (url string, tokenOK bool, updatedCookies string, err error)
|
||||
|
||||
type tokenCaptchaEngineFunc func(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, error)
|
||||
|
||||
var errTokenCaptchaURLExpired = errors.New("token 风控验证链接已过期")
|
||||
|
||||
// TokenCaptchaRecover solves a token-refresh captcha and returns cookies with x5sec merged in.
|
||||
func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, error) {
|
||||
cookies, _, err := m.TokenCaptchaRecoverWithEngine(ctx, cookieID, cookieStr, verificationURL, headless, provider)
|
||||
return cookies, err
|
||||
}
|
||||
|
||||
// TokenCaptchaRecoverWithEngine 按参考项目顺序执行 Playwright 主引擎,再执行直接 CDP 备用引擎。
|
||||
func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider TokenCaptchaURLProvider) (string, string, error) {
|
||||
primary := m.tokenCaptchaPrimaryFn
|
||||
if primary == nil {
|
||||
primary = m.tokenCaptchaPlaywrightRecover
|
||||
}
|
||||
currentCookies := cookieStr
|
||||
primaryURL := verificationURL
|
||||
var primaryErr error
|
||||
for refreshCount := 0; ; refreshCount++ {
|
||||
var cookies string
|
||||
// The provider may issue another browser token request. Calling it while
|
||||
// the primary engine owns this account's persistent profile deadlocks on
|
||||
// the same account lock, so URL refresh is orchestrated only after the
|
||||
// primary context has closed.
|
||||
cookies, primaryErr = primary(ctx, cookieID, currentCookies, primaryURL, headless, nil)
|
||||
if primaryErr == nil {
|
||||
return cookies, "playwright", nil
|
||||
}
|
||||
if !errors.Is(primaryErr, errTokenCaptchaURLExpired) || provider == nil || refreshCount >= 2 {
|
||||
break
|
||||
}
|
||||
freshURL, tokenOK, updated, err := provider(ctx, currentCookies)
|
||||
if err != nil {
|
||||
primaryErr = fmt.Errorf("%w且重取失败: %v", errTokenCaptchaURLExpired, err)
|
||||
break
|
||||
}
|
||||
if strings.TrimSpace(updated) != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
if tokenOK {
|
||||
return currentCookies, "playwright", nil
|
||||
}
|
||||
if strings.TrimSpace(freshURL) == "" {
|
||||
primaryErr = fmt.Errorf("%w且接口未返回新链接", errTokenCaptchaURLExpired)
|
||||
break
|
||||
}
|
||||
primaryURL = freshURL
|
||||
}
|
||||
// An expired URL cannot be repaired by replaying it through the fallback.
|
||||
if errors.Is(primaryErr, errTokenCaptchaURLExpired) {
|
||||
return "", "", primaryErr
|
||||
}
|
||||
|
||||
if realMouseRequested() {
|
||||
// 参考实现仅在 Windows 桌面且 pyautogui 可用时启用;Go/Docker 构建没有物理桌面驱动,
|
||||
// 因此按其“开启但不可用则回退原逻辑”分支继续备用引擎。
|
||||
m.logger.Error("CAPTCHA_REAL_MOUSE 已开启但物理鼠标引擎不可用,回退备用滑块逻辑", "goos", runtime.GOOS)
|
||||
}
|
||||
if !drissionFallbackEnabled() {
|
||||
return "", "playwright", primaryErr
|
||||
}
|
||||
|
||||
fallbackURL := verificationURL
|
||||
if provider != nil {
|
||||
freshURL, tokenOK, updated, err := provider(ctx, currentCookies)
|
||||
if err != nil {
|
||||
m.logger.Warn("备用引擎启动前重取验证链接失败,沿用原链接", "cookieID", cookieID, "err", err)
|
||||
} else {
|
||||
if strings.TrimSpace(updated) != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
if tokenOK {
|
||||
return currentCookies, "playwright", nil
|
||||
}
|
||||
if strings.TrimSpace(freshURL) != "" {
|
||||
fallbackURL = freshURL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fallback := m.tokenCaptchaFallbackFn
|
||||
if fallback == nil {
|
||||
fallback = m.tokenCaptchaCDPFallback
|
||||
}
|
||||
fallbackCookies, fallbackErr := fallback(
|
||||
ctx, cookieID, currentCookies, fallbackURL, drissionFallbackHeadless(), nil,
|
||||
)
|
||||
if fallbackErr == nil && hasFreshX5InCookieString(currentCookies, fallbackCookies) {
|
||||
return fallbackCookies, "drissionpage", nil
|
||||
}
|
||||
if fallbackErr == nil {
|
||||
fallbackErr = fmt.Errorf("备用滑块引擎未获取到新的 x5sec Cookie")
|
||||
}
|
||||
return "", "", fmt.Errorf("Playwright 主引擎失败: %v;备用滑块引擎失败: %w", primaryErr, fallbackErr)
|
||||
}
|
||||
|
||||
func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
return "", fmt.Errorf("Cookie为空,无法处理 token 风控验证")
|
||||
}
|
||||
@@ -23,32 +133,18 @@ func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr,
|
||||
}
|
||||
|
||||
currentCookies := cookieStr
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless))
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless), true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
browserDeadline := time.Now().Add(tokenCaptchaBrowserTTL)
|
||||
|
||||
targetURL := verificationURL
|
||||
if provider != nil {
|
||||
freshURL, tokenOK, updated, err := provider(ctx, currentCookies)
|
||||
if err != nil {
|
||||
m.logger.Warn("token风控验证前重取链接失败,沿用原链接", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
if strings.TrimSpace(updated) != "" && updated != currentCookies {
|
||||
currentCookies = updated
|
||||
if err := addCookieStr(bctx, currentCookies); err != nil {
|
||||
m.logger.Warn("token风控验证注入重取后的 Cookie 失败", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if tokenOK {
|
||||
m.logger.Info("token风控验证前重取 token 已成功,无需滑块", "cookieID", cookieID)
|
||||
return currentCookies, nil
|
||||
}
|
||||
if strings.TrimSpace(freshURL) != "" {
|
||||
targetURL = freshURL
|
||||
}
|
||||
beforeCookies, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取 token 风控验证前 Cookie 失败: %w", err)
|
||||
}
|
||||
previousX5SecValues := x5SecValues(beforeCookies)
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
@@ -56,38 +152,39 @@ func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr,
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if _, err := page.Goto(targetURL, playwright.PageGotoOptions{
|
||||
if time.Now().After(browserDeadline) {
|
||||
return "", fmt.Errorf("token 风控浏览器验证超过 %s", tokenCaptchaBrowserTTL)
|
||||
}
|
||||
if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
Timeout: playwright.Float(10000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("token风控验证页面访问异常", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
|
||||
time.Sleep(secondsDuration(randomFloat(0.3, 0.8)))
|
||||
_ = page.Mouse().Move(640, 360)
|
||||
time.Sleep(secondsDuration(randomFloat(0.02, 0.05)))
|
||||
_ = page.Mouse().Wheel(0, float64(200+rng.Intn(301)))
|
||||
time.Sleep(secondsDuration(randomFloat(0.02, 0.05)))
|
||||
if title, titleErr := page.Title(); titleErr == nil {
|
||||
m.logger.Info("token风控验证页面已加载", "cookieID", cookieID, "title", title)
|
||||
}
|
||||
content, _ := page.Content()
|
||||
if captchaURLExpired(content) {
|
||||
return "", errTokenCaptchaURLExpired
|
||||
}
|
||||
if strings.Contains(content, "STATUS_BREAKPOINT") || strings.Contains(content, "崩溃") {
|
||||
return "", fmt.Errorf("token 风控验证页面崩溃")
|
||||
}
|
||||
|
||||
scratch := isScratchCaptcha(content)
|
||||
if err := solveSlider(page, scratch, m.logger); err != nil {
|
||||
if err := solveSliderStrict(page, scratch, m.logger, previousX5SecValues, browserDeadline); err != nil {
|
||||
return "", err
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
all, err := bctx.Cookies()
|
||||
x5, err := waitForFreshX5SecCookie(ctx, bctx, previousX5SecValues, tokenCaptchaCookieWait, tokenCaptchaCookiePoll)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("提取 token 风控 cookie 失败: %w", err)
|
||||
}
|
||||
x5 := make(map[string]string)
|
||||
hasX5Sec := false
|
||||
for _, c := range all {
|
||||
name := strings.ToLower(c.Name)
|
||||
if strings.HasPrefix(name, "x5") || strings.Contains(name, "x5sec") {
|
||||
x5[c.Name] = c.Value
|
||||
if name == "x5sec" && strings.TrimSpace(c.Value) != "" {
|
||||
hasX5Sec = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasX5Sec {
|
||||
return "", fmt.Errorf("滑块验证未获取到 x5sec cookie")
|
||||
return "", err
|
||||
}
|
||||
merged := parseCookieStr(currentCookies)
|
||||
for k, v := range x5 {
|
||||
@@ -96,3 +193,131 @@ func (m *Manager) TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr,
|
||||
m.logger.Info("token风控验证成功", "cookieID", cookieID, "x5_cookie_count", len(x5))
|
||||
return cookieMarshal(merged), nil
|
||||
}
|
||||
|
||||
func realMouseRequested() bool {
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_REAL_MOUSE"))
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
return err == nil && parsed
|
||||
}
|
||||
|
||||
func drissionFallbackEnabled() bool {
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED"))
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
return err != nil || parsed
|
||||
}
|
||||
|
||||
func drissionFallbackHeadless() bool {
|
||||
if strings.EqualFold(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS")), "true") {
|
||||
return true
|
||||
}
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_DRISSIONPAGE_HEADLESS"))
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
return err != nil || parsed
|
||||
}
|
||||
|
||||
func drissionFallbackTimeout() time.Duration {
|
||||
value, err := strconv.Atoi(strings.TrimSpace(os.Getenv("CAPTCHA_DRISSIONPAGE_TIMEOUT")))
|
||||
if err != nil || value <= 0 {
|
||||
value = 25
|
||||
}
|
||||
return time.Duration(value) * time.Second
|
||||
}
|
||||
|
||||
func hasFreshX5InCookieString(before, after string) bool {
|
||||
oldValues := make(map[string]struct{})
|
||||
for name, value := range parseCookieStr(before) {
|
||||
if strings.EqualFold(name, "x5sec") && strings.TrimSpace(value) != "" {
|
||||
oldValues[value] = struct{}{}
|
||||
}
|
||||
}
|
||||
for name, value := range parseCookieStr(after) {
|
||||
lower := strings.ToLower(name)
|
||||
if !(strings.HasPrefix(lower, "x5") || strings.Contains(lower, "x5sec")) || strings.TrimSpace(value) == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(name, "x5sec") {
|
||||
if _, stale := oldValues[value]; stale {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func captchaURLExpired(content string) bool {
|
||||
return strings.Contains(content, "抱歉,页面访问出现了问题")
|
||||
}
|
||||
|
||||
func waitForFreshX5SecCookie(ctx context.Context, reader browserCookieReader, previousValues map[string]struct{}, timeout, pollInterval time.Duration) (map[string]string, error) {
|
||||
if timeout <= 0 || pollInterval <= 0 {
|
||||
return nil, fmt.Errorf("等待 x5sec Cookie 的超时和轮询间隔必须大于 0")
|
||||
}
|
||||
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
ticker := time.NewTicker(pollInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("等待新的 x5sec Cookie: %w", err)
|
||||
}
|
||||
all, err := reader.Cookies()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("提取 token 风控 Cookie 失败: %w", err)
|
||||
}
|
||||
x5, fresh := freshX5Cookies(all, previousValues)
|
||||
if fresh {
|
||||
return x5, nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("等待新的 x5sec Cookie: %w", ctx.Err())
|
||||
case <-timer.C:
|
||||
return nil, fmt.Errorf("滑块验证完成后 %s 内未获取到新的 x5sec Cookie", timeout)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func freshX5Cookies(cookies []playwright.Cookie, previousValues map[string]struct{}) (map[string]string, bool) {
|
||||
x5 := make(map[string]string)
|
||||
var freshName, freshValue string
|
||||
for _, cookie := range cookies {
|
||||
name := strings.ToLower(cookie.Name)
|
||||
if strings.HasPrefix(name, "x5") || strings.Contains(name, "x5sec") {
|
||||
x5[cookie.Name] = cookie.Value
|
||||
}
|
||||
if name == "x5sec" && strings.TrimSpace(cookie.Value) != "" {
|
||||
if _, stale := previousValues[cookie.Value]; !stale {
|
||||
freshName = cookie.Name
|
||||
freshValue = cookie.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
if freshValue == "" {
|
||||
return x5, false
|
||||
}
|
||||
// Cookies with the same name may coexist on several domains. Ensure the
|
||||
// value merged into the HTTP Cookie string is the newly issued one.
|
||||
x5[freshName] = freshValue
|
||||
return x5, true
|
||||
}
|
||||
|
||||
func x5SecValues(cookies []playwright.Cookie) map[string]struct{} {
|
||||
values := make(map[string]struct{})
|
||||
for _, cookie := range cookies {
|
||||
if strings.EqualFold(cookie.Name, "x5sec") && strings.TrimSpace(cookie.Value) != "" {
|
||||
values[cookie.Value] = struct{}{}
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
var fallbackTrackSelectors = []string{
|
||||
"#nc_1_n1t", ".nc_scale",
|
||||
"#nc_1__scale_text", ".nc-lang-cnt", "#nc_1_wrapper", ".nc_wrapper",
|
||||
}
|
||||
|
||||
// tokenCaptchaCDPFallback 直接启动 Chromium 并通过 CDP 连接,复现参考项目的
|
||||
// DrissionPage 第二引擎:它不复用 Playwright launch 协议,使用同一持久化目录和另一套轨迹。
|
||||
func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
if strings.TrimSpace(cookieStr) == "" || strings.TrimSpace(verificationURL) == "" {
|
||||
return "", fmt.Errorf("备用滑块引擎参数不完整")
|
||||
}
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer releaseSlot()
|
||||
lock := m.accountRenewLock(cookieID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
if err := m.init(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
profileDir, err := resolvePersistentUserDataDir(filepath.Join("browser_data", "user_"+pureUserID(cookieID)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cleanSingletonFiles(profileDir)
|
||||
_ = os.Remove(filepath.Join(profileDir, "DevToolsActivePort"))
|
||||
|
||||
executable := m.pw.Chromium.ExecutablePath()
|
||||
if configured := chromiumExecutablePath(); configured != nil {
|
||||
executable = *configured
|
||||
}
|
||||
if strings.TrimSpace(executable) == "" {
|
||||
return "", fmt.Errorf("备用滑块引擎未找到 Chromium")
|
||||
}
|
||||
args := fallbackChromiumArgs(profileDir, headless)
|
||||
cmd := exec.Command(executable, args...)
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎启动 Chromium: %w", err)
|
||||
}
|
||||
processDone := make(chan error, 1)
|
||||
go func() { processDone <- cmd.Wait() }()
|
||||
defer func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
select {
|
||||
case <-processDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
cleanSingletonFiles(profileDir)
|
||||
}()
|
||||
|
||||
endpoint, err := waitForDevToolsEndpoint(ctx, profileDir, processDone, 10*time.Second)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
connected, err := m.pw.Chromium.ConnectOverCDP(endpoint, playwright.BrowserTypeConnectOverCDPOptions{
|
||||
Timeout: playwright.Float(10000),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎连接 Chromium: %w", err)
|
||||
}
|
||||
defer func() { _ = connected.Close() }()
|
||||
contexts := connected.Contexts()
|
||||
if len(contexts) == 0 {
|
||||
return "", fmt.Errorf("备用滑块引擎未取得默认浏览器上下文")
|
||||
}
|
||||
bctx := contexts[0]
|
||||
if err := addCookieStr(bctx, cookieStr); err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎注入 Cookie: %w", err)
|
||||
}
|
||||
before, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎读取旧 Cookie: %w", err)
|
||||
}
|
||||
previousX5 := x5SecValues(before)
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎创建页面: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
deadline := time.Now().Add(drissionFallbackTimeout())
|
||||
if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(15000),
|
||||
}); err != nil {
|
||||
m.logger.Warn("备用滑块引擎访问验证页异常,继续检测页面", "cookieID", cookieID, "err", err)
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, secondsDuration(randomFloat(1, 3))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
if err := contextDeadlineError(ctx, deadline); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if attempt > 0 {
|
||||
if err := sleepUntil(ctx, deadline, secondsDuration(randomFloat(1, 2))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
button, track, err := waitForFallbackSlider(ctx, page, boundedDeadline(deadline, 5*time.Second))
|
||||
if err != nil {
|
||||
m.logger.Warn("备用滑块引擎未找到滑块", "cookieID", cookieID, "attempt", attempt+1, "err", err)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(ctx, page, deadline)
|
||||
logSliderReset(m.logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return "", fmt.Errorf("备用滑块第 %d 次前无法恢复: %w", attempt+1, reset.err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
distance := fallbackSlideDistance(page, button, track)
|
||||
frame, _ := button.OwnerFrame()
|
||||
if frame == nil {
|
||||
frame = page.MainFrame()
|
||||
}
|
||||
logSliderAttemptStart(m.logger, page, frame, button, track, attempt+1, distance)
|
||||
mode := fallbackMotionForAttempt(attempt)
|
||||
motion, err := simulateFallbackSlide(ctx, page, button, distance, mode, deadline)
|
||||
if err != nil {
|
||||
m.logger.Warn("备用滑块引擎滑动失败", "cookieID", cookieID, "attempt", attempt+1, "err", err)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(ctx, page, deadline)
|
||||
logSliderReset(m.logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return "", fmt.Errorf("备用滑块第 %d 次失败后无法恢复: %w", attempt+1, reset.err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
m.logger.Info("备用滑块拖动已释放",
|
||||
"cookieID", cookieID,
|
||||
"attempt", attempt+1,
|
||||
"points", motion.points,
|
||||
"planned_duration", motion.plannedDuration,
|
||||
"movement_elapsed", motion.movementElapsed,
|
||||
"total_elapsed", motion.totalElapsed,
|
||||
"final_offset_x", fmt.Sprintf("%.1f", motion.finalOffsetX),
|
||||
"final_left", motion.finalLeft,
|
||||
)
|
||||
x5, fresh := waitForFallbackSuccess(ctx, bctx, page, previousX5, boundedDeadline(deadline, 3*time.Second))
|
||||
if fresh {
|
||||
merged := parseCookieStr(cookieStr)
|
||||
for name, value := range x5 {
|
||||
merged[name] = value
|
||||
}
|
||||
m.logger.Info("备用滑块引擎验证成功", "cookieID", cookieID, "attempt", attempt+1)
|
||||
return cookieMarshal(merged), nil
|
||||
}
|
||||
logSliderFailureState(m.logger, page, attempt+1)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(ctx, page, deadline)
|
||||
logSliderReset(m.logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return "", fmt.Errorf("备用滑块第 %d 次失败后无法恢复: %w", attempt+1, reset.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("备用滑块引擎 3 次均失败")
|
||||
}
|
||||
|
||||
func fallbackChromiumArgs(profileDir string, headless bool) []string {
|
||||
args := []string{
|
||||
"--user-data-dir=" + profileDir,
|
||||
"--remote-debugging-port=0",
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--no-first-run",
|
||||
"--window-size=1920,1080",
|
||||
"--lang=zh-CN",
|
||||
"about:blank",
|
||||
}
|
||||
if headless {
|
||||
args = append([]string{"--headless=new"}, args...)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func waitForDevToolsEndpoint(ctx context.Context, profileDir string, processDone <-chan error, timeout time.Duration) (string, error) {
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
path := filepath.Join(profileDir, "DevToolsActivePort")
|
||||
for {
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
|
||||
if len(lines) > 0 {
|
||||
if port, err := strconv.Atoi(strings.TrimSpace(lines[0])); err == nil && port > 0 {
|
||||
return "http://127.0.0.1:" + strconv.Itoa(port), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case err := <-processDone:
|
||||
return "", fmt.Errorf("备用 Chromium 提前退出: %w", err)
|
||||
case <-timer.C:
|
||||
return "", fmt.Errorf("等待备用 Chromium 调试端口超时")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fallbackMotion struct {
|
||||
totalTime time.Duration
|
||||
points int
|
||||
impatient bool
|
||||
}
|
||||
|
||||
type fallbackSlideMetrics struct {
|
||||
points int
|
||||
plannedDuration time.Duration
|
||||
movementElapsed time.Duration
|
||||
totalElapsed time.Duration
|
||||
finalOffsetX float64
|
||||
finalLeft string
|
||||
}
|
||||
|
||||
func fallbackMotionForAttempt(attempt int) fallbackMotion {
|
||||
switch attempt {
|
||||
case 0:
|
||||
return fallbackMotion{totalTime: secondsDuration(randomFloat(1.5, 4)), points: 60 + rng.Intn(91)}
|
||||
case 1:
|
||||
return fallbackMotion{totalTime: secondsDuration(randomFloat(0.9, 1.3)), points: 30 + rng.Intn(31), impatient: true}
|
||||
default:
|
||||
return fallbackMotion{totalTime: secondsDuration(randomFloat(1, 2)), points: 50 + rng.Intn(41)}
|
||||
}
|
||||
}
|
||||
|
||||
func fallbackSlideDistance(page playwright.Page, button, track playwright.ElementHandle) float64 {
|
||||
if track != nil {
|
||||
if box, err := track.BoundingBox(); err == nil && box != nil && box.Width > 0 {
|
||||
if button != nil {
|
||||
if buttonBox, buttonErr := button.BoundingBox(); buttonErr == nil && buttonBox != nil {
|
||||
if distance := fallbackUsableDistance(box.Width, buttonBox.Width); distance > 0 {
|
||||
return distance
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallbackDistanceFromTrackWidth(box.Width)
|
||||
}
|
||||
}
|
||||
width := 1920.0
|
||||
if value, err := page.Evaluate(`() => window.innerWidth || 1920`); err == nil {
|
||||
if parsed, ok := value.(float64); ok {
|
||||
width = parsed
|
||||
}
|
||||
}
|
||||
if width <= 1366 {
|
||||
return 250 + float64(rng.Intn(71))
|
||||
}
|
||||
if width <= 1920 {
|
||||
return 300 + float64(rng.Intn(101))
|
||||
}
|
||||
return 350 + float64(rng.Intn(131))
|
||||
}
|
||||
|
||||
func fallbackUsableDistance(trackWidth, buttonWidth float64) float64 {
|
||||
if trackWidth <= 0 || buttonWidth <= 0 || buttonWidth >= trackWidth {
|
||||
return 0
|
||||
}
|
||||
return trackWidth - buttonWidth
|
||||
}
|
||||
|
||||
func fallbackDistanceFromTrackWidth(width float64) float64 {
|
||||
distance := width*randomFloat(0.70, 0.90) + float64(rng.Intn(41)-20)
|
||||
return math.Max(200, math.Min(600, distance))
|
||||
}
|
||||
|
||||
func waitForFallbackSlider(ctx context.Context, page playwright.Page, deadline time.Time) (playwright.ElementHandle, playwright.ElementHandle, error) {
|
||||
for {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
for _, frame := range frames {
|
||||
button := queryVisible(frame, "#nc_1_n1z")
|
||||
if button == nil {
|
||||
continue
|
||||
}
|
||||
track := queryFirstVisible(frame, fallbackTrackSelectors)
|
||||
return button, track, nil
|
||||
}
|
||||
if err := contextDeadlineError(ctx, deadline); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
return nil, nil, fmt.Errorf("等待备用滑块元素超时")
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, 100*time.Millisecond); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func simulateFallbackSlide(ctx context.Context, page playwright.Page, button playwright.ElementHandle, distance float64, mode fallbackMotion, deadline time.Time) (fallbackSlideMetrics, error) {
|
||||
metrics := fallbackSlideMetrics{plannedDuration: mode.totalTime}
|
||||
totalStarted := time.Now()
|
||||
box, err := button.BoundingBox()
|
||||
if err != nil || box == nil {
|
||||
return metrics, fmt.Errorf("备用引擎无法获取滑块位置")
|
||||
}
|
||||
waitBefore := secondsDuration(randomFloat(0.8, 2))
|
||||
if mode.impatient {
|
||||
waitBefore = secondsDuration(randomFloat(0.1, 0.5))
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, waitBefore); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
_ = button.Hover()
|
||||
if err := sleepUntil(ctx, deadline, secondsDuration(randomFloat(0.05, 0.3))); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
startX, startY := box.X+box.Width/2, box.Y+box.Height/2
|
||||
mouse := page.Mouse()
|
||||
if err := mouse.Move(startX, startY); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
if err := mouse.Down(); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
mouseDown := true
|
||||
defer func() {
|
||||
if mouseDown {
|
||||
_ = mouse.Up()
|
||||
}
|
||||
}()
|
||||
if err := sleepUntil(ctx, deadline, secondsDuration(randomFloat(0.05, 0.3))); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
tracks := generateFallbackTracks(distance, mode.points)
|
||||
if len(tracks) == 0 {
|
||||
return metrics, fmt.Errorf("备用引擎轨迹为空")
|
||||
}
|
||||
metrics.points = len(tracks)
|
||||
started := time.Now()
|
||||
lastX := 0.0
|
||||
currentY := startY
|
||||
direction := 1.0
|
||||
if rng.Intn(2) == 0 {
|
||||
direction = -1
|
||||
}
|
||||
yTrend := randomFloat(-3, 3)
|
||||
for i, absoluteX := range tracks {
|
||||
offsetX := absoluteX - lastX
|
||||
lastX = absoluteX
|
||||
if math.Abs(offsetX) < 0.1 {
|
||||
continue
|
||||
}
|
||||
progress := float64(i) / float64(len(tracks))
|
||||
yShake := randomFloat(-1.5, 1.5)
|
||||
if math.Abs(offsetX) > 8 {
|
||||
yShake *= randomFloat(1.2, 1.8)
|
||||
}
|
||||
offsetY := math.Max(-8, math.Min(8, yTrend*math.Pow(progress, 0.7)+yShake+direction*randomFloat(0.2, 1)))
|
||||
currentY += offsetY
|
||||
if err := mouse.Move(startX+absoluteX, currentY); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
remaining := mode.totalTime - time.Since(started)
|
||||
steps := len(tracks) - i
|
||||
stepDelay := time.Millisecond
|
||||
if steps > 0 && remaining > 0 {
|
||||
stepDelay = remaining / time.Duration(steps)
|
||||
}
|
||||
stepDelay = time.Duration(float64(stepDelay) * randomFloat(0.7, 1.3))
|
||||
if stepDelay < time.Millisecond {
|
||||
stepDelay = time.Millisecond
|
||||
}
|
||||
if stepDelay > 150*time.Millisecond {
|
||||
stepDelay = 150 * time.Millisecond
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, stepDelay); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
}
|
||||
metrics.movementElapsed = time.Since(started)
|
||||
metrics.finalOffsetX = lastX
|
||||
releaseWait := secondsDuration(randomFloat(0.2, 0.8))
|
||||
if mode.impatient {
|
||||
releaseWait = secondsDuration(randomFloat(0.05, 0.2))
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, releaseWait); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
if err := mouse.Up(); err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
mouseDown = false
|
||||
metrics.finalLeft = readSliderLeft(button)
|
||||
metrics.totalElapsed = time.Since(totalStarted)
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
func waitForFallbackSuccess(ctx context.Context, bctx playwright.BrowserContext, page playwright.Page, previousX5 map[string]struct{}, deadline time.Time) (map[string]string, bool) {
|
||||
var latest map[string]string
|
||||
for {
|
||||
all, err := bctx.Cookies()
|
||||
if err == nil {
|
||||
x5, fresh := freshX5Cookies(all, previousX5)
|
||||
latest = x5
|
||||
if fresh && !isPunishURL(page.URL()) {
|
||||
return x5, true
|
||||
}
|
||||
}
|
||||
if hasDefinitiveSliderFailure(page) {
|
||||
return latest, false
|
||||
}
|
||||
if time.Now().After(deadline) || ctx.Err() != nil {
|
||||
return latest, false
|
||||
}
|
||||
if err := sleepUntil(ctx, deadline, 100*time.Millisecond); err != nil {
|
||||
return latest, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generateFallbackTracks 移植 DrissionPage fallback 的加速/匀速/减速、犹豫、超调和重采样。
|
||||
func generateFallbackTracks(distance float64, targetPoints int) []float64 {
|
||||
if distance <= 0 || targetPoints <= 1 {
|
||||
return nil
|
||||
}
|
||||
tracks := []float64{0}
|
||||
current, velocity := 0.0, 0.0
|
||||
maxVelocity := randomFloat(80, 150)
|
||||
accelerationPhase := distance * randomFloat(0.3, 0.6)
|
||||
decelerationStart := distance * randomFloat(0.6, 0.85)
|
||||
dt := math.Max(0.01, math.Min(0.2, distance/(float64(targetPoints)*maxVelocity*0.5)*randomFloat(0.8, 1.2)))
|
||||
hesitationCounter := 0
|
||||
for step := 1; current < distance && step <= 10000; step++ {
|
||||
var acceleration float64
|
||||
switch {
|
||||
case current < accelerationPhase:
|
||||
acceleration = randomFloat(15, 35)
|
||||
if step%(3+rng.Intn(6)) == 0 {
|
||||
acceleration *= randomFloat(0.7, 1.4)
|
||||
}
|
||||
case current < decelerationStart:
|
||||
acceleration = randomFloat(-2, 2)
|
||||
if randomFloat(0, 1) < 0.2 {
|
||||
acceleration = randomFloat(-8, 8)
|
||||
}
|
||||
case distance-current > 20:
|
||||
acceleration = randomFloat(-25, -8)
|
||||
default:
|
||||
acceleration = randomFloat(-15, -3)
|
||||
}
|
||||
if randomFloat(0, 1) < 0.15 && current > accelerationPhase {
|
||||
hesitationCounter++
|
||||
if hesitationCounter < 3 {
|
||||
if randomFloat(0, 1) < 0.4 {
|
||||
acceleration = randomFloat(-8, -2)
|
||||
} else {
|
||||
acceleration = randomFloat(-2, 2)
|
||||
}
|
||||
} else {
|
||||
hesitationCounter = 0
|
||||
}
|
||||
}
|
||||
velocity = math.Max(0, math.Min(maxVelocity, velocity*0.95+acceleration*dt))
|
||||
old := current
|
||||
current += velocity * dt
|
||||
if len(tracks) > 5 {
|
||||
current += randomFloat(-0.3, 0.3) * (velocity / maxVelocity)
|
||||
}
|
||||
if randomFloat(0, 1) < 0.12 && current > 50 {
|
||||
switch correction := randomFloat(0, 1); {
|
||||
case correction < 0.6:
|
||||
current -= randomFloat(1, 4)
|
||||
case correction >= 0.8:
|
||||
current += randomFloat(0.2, 1)
|
||||
}
|
||||
}
|
||||
if current < old {
|
||||
current = old + randomFloat(0.1, 0.8)
|
||||
}
|
||||
if current-old > 15 {
|
||||
current = old + randomFloat(8, 15)
|
||||
}
|
||||
tracks = append(tracks, math.Round(current*10)/10)
|
||||
}
|
||||
if randomFloat(0, 1) < 0.3 {
|
||||
overshoot := randomFloat(2, 8)
|
||||
tracks = append(tracks, math.Round((distance+overshoot)*10)/10)
|
||||
correctionSteps := 2 + rng.Intn(4)
|
||||
for i := 0; i < correctionSteps; i++ {
|
||||
correction := overshoot * (1 - float64(i+1)/float64(correctionSteps))
|
||||
tracks = append(tracks, math.Round((distance+correction+randomFloat(-0.3, 0.3))*10)/10)
|
||||
}
|
||||
}
|
||||
finalTarget := distance + randomFloat(-1, 2)
|
||||
for i := 0; i < 1+rng.Intn(3); i++ {
|
||||
finalTarget += randomFloat(-0.5, 0.5)
|
||||
tracks = append(tracks, math.Round(finalTarget*10)/10)
|
||||
}
|
||||
result := resampleFallbackTracks(cleanFallbackTracks(tracks), targetPoints)
|
||||
return result
|
||||
}
|
||||
|
||||
func cleanFallbackTracks(tracks []float64) []float64 {
|
||||
if len(tracks) == 0 {
|
||||
return nil
|
||||
}
|
||||
cleaned := []float64{tracks[0]}
|
||||
last := tracks[0]
|
||||
for _, current := range tracks[1:] {
|
||||
if math.Abs(current-last) < 1.5 {
|
||||
continue
|
||||
}
|
||||
if current < last && last-current >= 3 {
|
||||
current = last + randomFloat(0.1, 1)
|
||||
}
|
||||
cleaned = append(cleaned, current)
|
||||
last = current
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
func resampleFallbackTracks(tracks []float64, target int) []float64 {
|
||||
if len(tracks) <= 1 || target <= 1 || len(tracks) == target {
|
||||
return tracks
|
||||
}
|
||||
if len(tracks) > target {
|
||||
step := float64(len(tracks)) / float64(target)
|
||||
out := make([]float64, 0, target)
|
||||
out = append(out, tracks[0])
|
||||
for i := 1; i < target-1; i++ {
|
||||
index := min(int(float64(i)*step), len(tracks)-1)
|
||||
out = append(out, tracks[index])
|
||||
}
|
||||
return append(out, tracks[len(tracks)-1])
|
||||
}
|
||||
for len(tracks) < target && len(tracks) > 1 {
|
||||
out := make([]float64, 0, min(target, len(tracks)*2))
|
||||
out = append(out, tracks[0])
|
||||
for i := 0; i < len(tracks)-1 && len(out) < target; i++ {
|
||||
if i > 0 {
|
||||
out = append(out, tracks[i])
|
||||
}
|
||||
if len(out) < target {
|
||||
out = append(out, (tracks[i]+tracks[i+1])/2+randomFloat(-0.5, 0.5))
|
||||
}
|
||||
}
|
||||
if len(out) < target {
|
||||
out = append(out, tracks[len(tracks)-1])
|
||||
}
|
||||
tracks = out
|
||||
}
|
||||
if len(tracks) > target {
|
||||
tracks = tracks[:target]
|
||||
}
|
||||
return tracks
|
||||
}
|
||||
|
||||
func contextDeadlineError(ctx context.Context, deadline time.Time) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !deadline.IsZero() && time.Now().After(deadline) {
|
||||
return fmt.Errorf("备用滑块引擎超过 %s", drissionFallbackTimeout())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sleepUntil(ctx context.Context, deadline time.Time, duration time.Duration) error {
|
||||
if duration <= 0 {
|
||||
return contextDeadlineError(ctx, deadline)
|
||||
}
|
||||
if remaining := time.Until(deadline); !deadline.IsZero() && duration > remaining {
|
||||
duration = remaining
|
||||
}
|
||||
if duration <= 0 {
|
||||
return contextDeadlineError(ctx, deadline)
|
||||
}
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return contextDeadlineError(ctx, deadline)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
func TestReferencePlaywrightSliderBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise the Playwright slider")
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>验证码拦截</title></head><body>
|
||||
<div class="nc-container">
|
||||
<div id="nc_1_n1t" class="nc_scale" style="position:relative;width:420px;height:44px;background:#ddd">
|
||||
<span id="nc_1_n1z" style="display:block;width:44px;height:44px;background:#333"></span>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const slider = document.querySelector('#nc_1_n1z');
|
||||
let pressed = false;
|
||||
let released = false;
|
||||
let startX = 0;
|
||||
slider.addEventListener('mousedown', event => {
|
||||
pressed = true;
|
||||
startX = event.clientX;
|
||||
});
|
||||
window.addEventListener('mouseup', () => {
|
||||
released = pressed;
|
||||
});
|
||||
slider.addEventListener('click', event => {
|
||||
if (!released || event.clientX - startX < 300) return;
|
||||
document.cookie = 'x5sec=playwright-integration-fresh; path=/';
|
||||
history.replaceState({}, '', '/done');
|
||||
document.querySelector('.nc-container').remove();
|
||||
document.title = '验证完成';
|
||||
});
|
||||
</script></body></html>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
bctx, err := browser.NewContext()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := page.Goto(server.URL+"/punish", playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := solveSliderStrict(page, false, m.logger, map[string]struct{}{}, time.Now().Add(15*time.Second)); err != nil {
|
||||
t.Fatalf("Playwright slider: %v", err)
|
||||
}
|
||||
cookies, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, fresh := freshX5Cookies(cookies, nil); !fresh || isPunishURL(page.URL()) {
|
||||
t.Fatalf("slider did not complete reference success flow: url=%s cookies=%v", page.URL(), cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaywrightSliderRecoversFromHiddenFailureState(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise slider failure recovery")
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>验证码拦截</title></head><body>
|
||||
<div id="nocaptcha" class="nc-container"><div id="nc_1_wrapper"></div></div>
|
||||
<script>
|
||||
let dragAttempts = 0;
|
||||
let retryClicks = 0;
|
||||
let pressed = false;
|
||||
let startX = 0;
|
||||
function renderSlider() {
|
||||
document.querySelector('#nc_1_wrapper').innerHTML = '<div id="nc_1_n1t" class="nc_scale" style="position:relative;width:300px;height:34px;background:#ddd"><span id="nc_1_n1z" class="nc_iconfont btn_slide" style="position:absolute;left:0;width:42px;height:34px;background:#333"></span></div>';
|
||||
}
|
||||
renderSlider();
|
||||
document.addEventListener('mousedown', event => {
|
||||
if (event.target.id !== 'nc_1_n1z') return;
|
||||
pressed = true;
|
||||
startX = event.clientX;
|
||||
});
|
||||
document.addEventListener('mouseup', event => {
|
||||
if (!pressed) return;
|
||||
pressed = false;
|
||||
dragAttempts++;
|
||||
if (dragAttempts === 1) {
|
||||
document.querySelector('#nc_1_wrapper').innerHTML = '<div class="errloading">验证失败,点击框体重试</div>';
|
||||
return;
|
||||
}
|
||||
if (event.clientX - startX < 250) return;
|
||||
document.cookie = 'x5sec=playwright-retry-fresh; path=/';
|
||||
history.replaceState({}, '', '/done');
|
||||
document.querySelector('.nc-container').remove();
|
||||
document.title = '验证完成';
|
||||
});
|
||||
document.addEventListener('click', event => {
|
||||
if (!event.target.closest('.errloading')) return;
|
||||
retryClicks++;
|
||||
renderSlider();
|
||||
});
|
||||
</script></body></html>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
bctx, err := browser.NewContext()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := page.Goto(server.URL+"/punish", playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := solveSliderStrict(page, false, m.logger, map[string]struct{}{}, time.Now().Add(25*time.Second)); err != nil {
|
||||
t.Fatalf("slider recovery: %v", err)
|
||||
}
|
||||
state, err := page.Evaluate(`() => ({dragAttempts, retryClicks})`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values, ok := state.(map[string]any)
|
||||
if !ok || fmt.Sprint(values["dragAttempts"]) != "2" || fmt.Sprint(values["retryClicks"]) != "1" {
|
||||
t.Fatalf("unexpected retry state: %#v", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaCDPFallbackBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise the direct-CDP Chromium fallback")
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>验证码拦截</title></head><body>
|
||||
<div class="nc-container"><div id="nc_1_wrapper"></div></div>
|
||||
<script>
|
||||
let attempts = 0;
|
||||
let pressed = false;
|
||||
let startX = 0;
|
||||
function renderSlider() {
|
||||
document.querySelector('#nc_1_wrapper').innerHTML = '<div id="nc_1_n1t" class="nc_scale" style="position:relative;width:300px;height:34px;background:#ddd"><span id="nc_1_n1z" style="position:absolute;left:0;width:42px;height:34px;background:#333"></span></div>';
|
||||
}
|
||||
renderSlider();
|
||||
document.addEventListener('mousedown', event => {
|
||||
if (event.target.id !== 'nc_1_n1z') return;
|
||||
pressed = true;
|
||||
startX = event.clientX;
|
||||
});
|
||||
document.addEventListener('mouseup', event => {
|
||||
if (!pressed) return;
|
||||
pressed = false;
|
||||
attempts++;
|
||||
if (attempts === 1) {
|
||||
document.querySelector('#nc_1_wrapper').innerHTML = '<div class="errloading">验证失败,点击框体重试</div>';
|
||||
return;
|
||||
}
|
||||
if (event.clientX - startX < 250) return;
|
||||
document.cookie = 'x5sec=integration-fresh; path=/';
|
||||
document.title = '验证完成';
|
||||
document.querySelector('.nc-container').remove();
|
||||
});
|
||||
document.addEventListener('click', event => {
|
||||
if (event.target.closest('.errloading')) renderSlider();
|
||||
});
|
||||
</script></body></html>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldWD, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chdir(t.TempDir()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = os.Chdir(oldWD) }()
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_TIMEOUT", "35")
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
cookies, err := m.tokenCaptchaCDPFallback(ctx, "integration-account", "unb=1", server.URL, true, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("direct CDP fallback: %v", err)
|
||||
}
|
||||
if !strings.Contains(cookies, "x5sec=integration-fresh") {
|
||||
t.Fatalf("fallback cookies=%q", cookies)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTokenCaptchaEngineOrderPrimarySuccess(t *testing.T) {
|
||||
fallbackCalls := 0
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "unb=1; x5sec=fresh", nil
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
fallbackCalls++
|
||||
return "", errors.New("must not run")
|
||||
},
|
||||
}
|
||||
cookies, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://captcha", true, nil)
|
||||
if err != nil || engine != "playwright" || !strings.Contains(cookies, "x5sec=fresh") || fallbackCalls != 0 {
|
||||
t.Fatalf("cookies=%q engine=%q fallback=%d err=%v", cookies, engine, fallbackCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaEngineOrderFallbackUsesFreshURLAndCookies(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED", "true")
|
||||
var gotURL, gotCookies string
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", errors.New("primary failed")
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(_ context.Context, _ string, cookies, url string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
gotURL, gotCookies = url, cookies
|
||||
if !headless {
|
||||
t.Fatal("备用引擎默认应无头")
|
||||
}
|
||||
return cookies + "; x5sec=fallback-new", nil
|
||||
},
|
||||
}
|
||||
providerCalls := 0
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
providerCalls++
|
||||
return "https://fresh.example", false, "unb=1; _m_h5_tk=fresh", nil
|
||||
}
|
||||
cookies, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1; x5sec=old", "https://old.example", false, provider)
|
||||
if err != nil || engine != "drissionpage" || !strings.Contains(cookies, "x5sec=fallback-new") {
|
||||
t.Fatalf("cookies=%q engine=%q err=%v", cookies, engine, err)
|
||||
}
|
||||
if providerCalls != 1 || gotURL != "https://fresh.example" || !strings.Contains(gotCookies, "_m_h5_tk=fresh") {
|
||||
t.Fatalf("provider=%d url=%q cookies=%q", providerCalls, gotURL, gotCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaExpiredURLSkipsFallback(t *testing.T) {
|
||||
fallbackCalls := 0
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", fmtTokenCaptchaExpired()
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
fallbackCalls++
|
||||
return "unb=1; x5sec=new", nil
|
||||
},
|
||||
}
|
||||
_, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://expired", true, nil)
|
||||
if !errors.Is(err, errTokenCaptchaURLExpired) || engine != "" || fallbackCalls != 0 {
|
||||
t.Fatalf("engine=%q fallback=%d err=%v", engine, fallbackCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaExpiredURLRefreshesAfterPrimaryCloses(t *testing.T) {
|
||||
primaryCalls := 0
|
||||
providerCalls := 0
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(_ context.Context, _ string, cookies, url string, _ bool, provider TokenCaptchaURLProvider) (string, error) {
|
||||
if provider != nil {
|
||||
t.Fatal("primary must not call provider while holding the persistent profile lock")
|
||||
}
|
||||
primaryCalls++
|
||||
if primaryCalls == 1 {
|
||||
return "", errTokenCaptchaURLExpired
|
||||
}
|
||||
if url != "https://fresh.example" || !strings.Contains(cookies, "_m_h5_tk=fresh") {
|
||||
t.Fatalf("url=%q cookies=%q", url, cookies)
|
||||
}
|
||||
return cookies + "; x5sec=new", nil
|
||||
},
|
||||
}
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
providerCalls++
|
||||
return "https://fresh.example", false, "unb=1; _m_h5_tk=fresh", nil
|
||||
}
|
||||
cookies, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://expired", true, provider)
|
||||
if err != nil || engine != "playwright" || primaryCalls != 2 || providerCalls != 1 || !strings.Contains(cookies, "x5sec=new") {
|
||||
t.Fatalf("cookies=%q engine=%q primary=%d provider=%d err=%v", cookies, engine, primaryCalls, providerCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func fmtTokenCaptchaExpired() error {
|
||||
return errors.Join(errTokenCaptchaURLExpired, errors.New("cannot refresh"))
|
||||
}
|
||||
|
||||
func TestTokenCaptchaFallbackCanBeDisabled(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED", "false")
|
||||
fallbackCalls := 0
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", errors.New("primary failed")
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
fallbackCalls++
|
||||
return "", nil
|
||||
},
|
||||
}
|
||||
_, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://captcha", true, nil)
|
||||
if err == nil || engine != "playwright" || fallbackCalls != 0 {
|
||||
t.Fatalf("engine=%q fallback=%d err=%v", engine, fallbackCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaProviderDetectsTokenBeforeFallback(t *testing.T) {
|
||||
fallbackCalls := 0
|
||||
m := &Manager{
|
||||
logger: slog.Default(),
|
||||
tokenCaptchaPrimaryFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
return "", errors.New("primary failed")
|
||||
},
|
||||
tokenCaptchaFallbackFn: func(context.Context, string, string, string, bool, TokenCaptchaURLProvider) (string, error) {
|
||||
fallbackCalls++
|
||||
return "", nil
|
||||
},
|
||||
}
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return "", true, "unb=1; _m_h5_tk=renewed", nil
|
||||
}
|
||||
cookies, engine, err := m.TokenCaptchaRecoverWithEngine(context.Background(), "cid", "unb=1", "https://captcha", true, provider)
|
||||
if err != nil || engine != "playwright" || fallbackCalls != 0 || !strings.Contains(cookies, "_m_h5_tk=renewed") {
|
||||
t.Fatalf("cookies=%q engine=%q fallback=%d err=%v", cookies, engine, fallbackCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackConfigurationMatchesReferenceDefaults(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED", "")
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_HEADLESS", "")
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_TIMEOUT", "")
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !drissionFallbackEnabled() || !drissionFallbackHeadless() || drissionFallbackTimeout() != 25*time.Second {
|
||||
t.Fatalf("fallback defaults enabled=%v headless=%v timeout=%s", drissionFallbackEnabled(), drissionFallbackHeadless(), drissionFallbackTimeout())
|
||||
}
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_TIMEOUT", "7")
|
||||
t.Setenv("CAPTCHA_DRISSIONPAGE_HEADLESS", "false")
|
||||
if drissionFallbackHeadless() || drissionFallbackTimeout() != 7*time.Second {
|
||||
t.Fatalf("fallback overrides headless=%v timeout=%s", drissionFallbackHeadless(), drissionFallbackTimeout())
|
||||
}
|
||||
t.Setenv("BROWSER_HEADLESS", "true")
|
||||
if !drissionFallbackHeadless() {
|
||||
t.Fatal("Docker BROWSER_HEADLESS=true 必须强制备用引擎无头")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackTracksAreResampledAndBounded(t *testing.T) {
|
||||
for _, points := range []int{30, 60, 90, 150} {
|
||||
tracks := generateFallbackTracks(320, points)
|
||||
if len(tracks) != points {
|
||||
t.Fatalf("points=%d got=%d", points, len(tracks))
|
||||
}
|
||||
if tracks[0] < -1 || tracks[len(tracks)-1] < 300 || tracks[len(tracks)-1] > 345 {
|
||||
t.Fatalf("points=%d first=%.1f last=%.1f", points, tracks[0], tracks[len(tracks)-1])
|
||||
}
|
||||
for i := 1; i < len(tracks); i++ {
|
||||
if tracks[i] < tracks[i-1]-10 {
|
||||
t.Fatalf("轨迹大幅回退: points=%d index=%d %.1f -> %.1f", points, i, tracks[i-1], tracks[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackDistanceMatchesReferenceRange(t *testing.T) {
|
||||
for i := 0; i < 100; i++ {
|
||||
distance := fallbackDistanceFromTrackWidth(420)
|
||||
if distance < 274 || distance > 398 {
|
||||
t.Fatalf("420px 轨道距离 %.1f 超出 70%%-90%% 加正负20px范围", distance)
|
||||
}
|
||||
}
|
||||
if got := fallbackDistanceFromTrackWidth(100); got != 200 {
|
||||
t.Fatalf("短轨道距离应限制为 200,got %.1f", got)
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
if got := fallbackDistanceFromTrackWidth(1000); got > 600 {
|
||||
t.Fatalf("长轨道距离应限制为 600,got %.1f", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackUsableDistanceMatchesStandardNCDOM(t *testing.T) {
|
||||
if got := fallbackUsableDistance(300, 42); got != 258 {
|
||||
t.Fatalf("标准 NC DOM 可用距离=%.1f want 258", got)
|
||||
}
|
||||
for _, invalid := range [][2]float64{{0, 42}, {300, 0}, {42, 42}, {40, 42}} {
|
||||
if got := fallbackUsableDistance(invalid[0], invalid[1]); got != 0 {
|
||||
t.Fatalf("无效尺寸 %v 不应产生距离,got %.1f", invalid, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackChromiumArgsUsePersistentCDPProfile(t *testing.T) {
|
||||
args := strings.Join(fallbackChromiumArgs("/tmp/profile", true), " ")
|
||||
for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled"} {
|
||||
if !strings.Contains(args, want) {
|
||||
t.Fatalf("args 缺少 %q: %s", want, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForDevToolsEndpoint(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
processDone := make(chan error)
|
||||
go func() {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
_ = os.WriteFile(filepath.Join(dir, "DevToolsActivePort"), []byte("9223\n/devtools/browser/id\n"), 0o600)
|
||||
}()
|
||||
endpoint, err := waitForDevToolsEndpoint(context.Background(), dir, processDone, time.Second)
|
||||
if err != nil || endpoint != "http://127.0.0.1:9223" {
|
||||
t.Fatalf("endpoint=%q err=%v", endpoint, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasFreshX5InCookieString(t *testing.T) {
|
||||
if hasFreshX5InCookieString("x5sec=old", "x5sec=old") {
|
||||
t.Fatal("旧 x5sec 不应被备用引擎当作成功")
|
||||
}
|
||||
if !hasFreshX5InCookieString("x5sec=old", "x5sec=new; x5sectag=tag") {
|
||||
t.Fatal("新的 x5sec 应被识别")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
)
|
||||
|
||||
type cookieReadResult struct {
|
||||
cookies []playwright.Cookie
|
||||
err error
|
||||
}
|
||||
|
||||
type sequenceCookieReader struct {
|
||||
results []cookieReadResult
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *sequenceCookieReader) Cookies(_ ...string) ([]playwright.Cookie, error) {
|
||||
index := r.calls
|
||||
r.calls++
|
||||
if index >= len(r.results) {
|
||||
index = len(r.results) - 1
|
||||
}
|
||||
return r.results[index].cookies, r.results[index].err
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieWaitsForChangedValue(t *testing.T) {
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{
|
||||
{cookies: []playwright.Cookie{{Name: "x5sec", Value: "old"}}},
|
||||
{cookies: []playwright.Cookie{
|
||||
{Name: "x5sec", Value: "new"},
|
||||
{Name: "x5sectag", Value: "tag"},
|
||||
}},
|
||||
}}
|
||||
|
||||
got, err := waitForFreshX5SecCookie(context.Background(), reader, map[string]struct{}{"old": {}}, 100*time.Millisecond, time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("waitForFreshX5SecCookie: %v", err)
|
||||
}
|
||||
if got["x5sec"] != "new" || got["x5sectag"] != "tag" {
|
||||
t.Fatalf("未返回完整的新 x5 Cookie,got %#v", got)
|
||||
}
|
||||
if reader.calls < 2 {
|
||||
t.Fatalf("旧值不应被立即接受,calls=%d", reader.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieAcceptsFirstValueWithoutBaseline(t *testing.T) {
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{{cookies: []playwright.Cookie{{Name: "X5SEC", Value: "fresh"}}}}}
|
||||
got, err := waitForFreshX5SecCookie(context.Background(), reader, nil, 100*time.Millisecond, time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("waitForFreshX5SecCookie: %v", err)
|
||||
}
|
||||
if got["X5SEC"] != "fresh" {
|
||||
t.Fatalf("x5sec 名称匹配应不区分大小写,got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieTimesOutOnStaleValue(t *testing.T) {
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{{cookies: []playwright.Cookie{{Name: "x5sec", Value: "old"}}}}}
|
||||
_, err := waitForFreshX5SecCookie(context.Background(), reader, map[string]struct{}{"old": {}}, 5*time.Millisecond, time.Millisecond)
|
||||
if err == nil || !strings.Contains(err.Error(), "未获取到新的") {
|
||||
t.Fatalf("持续旧值应超时,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieHonorsCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{{}}}
|
||||
_, err := waitForFreshX5SecCookie(ctx, reader, nil, time.Second, time.Millisecond)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("应返回 context.Canceled,got %v", err)
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatalf("上下文已取消时不应再读取 Cookie,calls=%d", reader.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieReturnsReadError(t *testing.T) {
|
||||
want := errors.New("read failed")
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{{err: want}}}
|
||||
_, err := waitForFreshX5SecCookie(context.Background(), reader, nil, time.Second, time.Millisecond)
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("应保留底层读取错误,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFreshX5SecCookieRejectsInvalidTiming(t *testing.T) {
|
||||
reader := &sequenceCookieReader{results: []cookieReadResult{{}}}
|
||||
_, err := waitForFreshX5SecCookie(context.Background(), reader, nil, 0, time.Millisecond)
|
||||
if err == nil || !strings.Contains(err.Error(), "必须大于 0") {
|
||||
t.Fatalf("无效超时应被拒绝,got %v", err)
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatalf("参数无效时不应读取 Cookie,calls=%d", reader.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreshX5CookiesFiltersRelatedNames(t *testing.T) {
|
||||
got, fresh := freshX5Cookies([]playwright.Cookie{
|
||||
{Name: "x5sec", Value: "value"},
|
||||
{Name: "x5sectag", Value: "tag"},
|
||||
{Name: "other", Value: "ignored"},
|
||||
}, nil)
|
||||
if !fresh || len(got) != 2 || got["x5sec"] != "value" || got["x5sectag"] != "tag" {
|
||||
t.Fatalf("freshX5Cookies got=%#v fresh=%v", got, fresh)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreshX5CookiesChoosesNewValueAcrossDomains(t *testing.T) {
|
||||
got, fresh := freshX5Cookies([]playwright.Cookie{
|
||||
{Name: "x5sec", Value: "old", Domain: ".taobao.com"},
|
||||
{Name: "x5sec", Value: "new", Domain: ".goofish.com"},
|
||||
{Name: "x5sec", Value: "old", Domain: ".alipay.com"},
|
||||
}, map[string]struct{}{"old": {}})
|
||||
if !fresh || got["x5sec"] != "new" {
|
||||
t.Fatalf("应选择新域名 Cookie 值,got=%#v fresh=%v", got, fresh)
|
||||
}
|
||||
}
|
||||
|
||||
func TestX5SecValuesCollectsAllDomains(t *testing.T) {
|
||||
got := x5SecValues([]playwright.Cookie{
|
||||
{Name: "x5sec", Value: "one", Domain: ".goofish.com"},
|
||||
{Name: "X5SEC", Value: "two", Domain: ".taobao.com"},
|
||||
{Name: "x5sectag", Value: "ignored"},
|
||||
})
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("应收集所有域名的旧 x5sec 值,got %#v", got)
|
||||
}
|
||||
if _, ok := got["one"]; !ok {
|
||||
t.Fatal("缺少 one")
|
||||
}
|
||||
if _, ok := got["two"]; !ok {
|
||||
t.Fatal("缺少 two")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) {
|
||||
existing := []cookierefresh.BrowserCookie{
|
||||
{Name: "cookie2", Value: "old", Domain: ".taobao.com", Path: "/", Expires: 12345, HTTPOnly: true, Secure: true, SameSite: "None"},
|
||||
{Name: "stale", Value: "remove", Domain: ".goofish.com", Path: "/"},
|
||||
}
|
||||
got := credentialCookieSnapshot(existing, map[string]string{"cookie2": "new", "unb": "1"})
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("snapshot length=%d want=2: %+v", len(got), got)
|
||||
}
|
||||
byName := map[string]cookierefresh.BrowserCookie{}
|
||||
for _, cookie := range got {
|
||||
byName[cookie.Name] = cookie
|
||||
}
|
||||
cookie2 := byName["cookie2"]
|
||||
if cookie2.Value != "new" || cookie2.Domain != ".taobao.com" || cookie2.Expires != 12345 || !cookie2.HTTPOnly || !cookie2.Secure || cookie2.SameSite != "None" {
|
||||
t.Fatalf("preserved cookie=%+v", cookie2)
|
||||
}
|
||||
if unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
|
||||
t.Fatalf("new cookie defaults=%+v", unb)
|
||||
}
|
||||
if _, ok := byName["stale"]; ok {
|
||||
t.Fatal("cookie absent from current snapshot must be removed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// resolvePersistentUserDataDir prepares the profile directory required by
|
||||
// Playwright's LaunchPersistentContext. playwright-go rejects relative paths.
|
||||
func resolvePersistentUserDataDir(path string) (string, error) {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("持久化浏览器用户数据目录不能为空")
|
||||
}
|
||||
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解析持久化浏览器用户数据目录失败: %w", err)
|
||||
}
|
||||
absPath = filepath.Clean(absPath)
|
||||
if !filepath.IsAbs(absPath) {
|
||||
return "", fmt.Errorf("持久化浏览器用户数据目录不是绝对路径: %s", absPath)
|
||||
}
|
||||
if err := os.MkdirAll(absPath, 0o700); err != nil {
|
||||
return "", fmt.Errorf("创建持久化浏览器用户数据目录失败: %w", err)
|
||||
}
|
||||
return absPath, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *testing.T) {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Getwd: %v", err)
|
||||
}
|
||||
target := filepath.Join(t.TempDir(), "nested", "profile")
|
||||
relative, err := filepath.Rel(cwd, target)
|
||||
if err != nil {
|
||||
t.Fatalf("Rel: %v", err)
|
||||
}
|
||||
|
||||
got, err := resolvePersistentUserDataDir(relative)
|
||||
if err != nil {
|
||||
t.Fatalf("resolvePersistentUserDataDir: %v", err)
|
||||
}
|
||||
if !filepath.IsAbs(got) {
|
||||
t.Fatalf("返回路径必须是绝对路径,got %q", got)
|
||||
}
|
||||
if got != filepath.Clean(target) {
|
||||
t.Fatalf("got %q, want %q", got, filepath.Clean(target))
|
||||
}
|
||||
info, err := os.Stat(got)
|
||||
if err != nil {
|
||||
t.Fatalf("Stat: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("%q 应为目录", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePersistentUserDataDirPreservesAbsolutePath(t *testing.T) {
|
||||
target := filepath.Join(t.TempDir(), "profile")
|
||||
got, err := resolvePersistentUserDataDir(" " + target + " ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolvePersistentUserDataDir: %v", err)
|
||||
}
|
||||
if got != target {
|
||||
t.Fatalf("got %q, want %q", got, target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePersistentUserDataDirRejectsEmptyPath(t *testing.T) {
|
||||
_, err := resolvePersistentUserDataDir(" ")
|
||||
if err == nil || !strings.Contains(err.Error(), "不能为空") {
|
||||
t.Fatalf("空路径应返回明确错误,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePersistentUserDataDirReportsCreateFailure(t *testing.T) {
|
||||
parentFile := filepath.Join(t.TempDir(), "file")
|
||||
if err := os.WriteFile(parentFile, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
_, err := resolvePersistentUserDataDir(filepath.Join(parentFile, "profile"))
|
||||
if err == nil || !strings.Contains(err.Error(), "创建") {
|
||||
t.Fatalf("目录创建失败应返回明确错误,got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -7,22 +7,22 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// AccountToken 持久化的账号登录凭证缓存(device_id + accessToken)。
|
||||
//
|
||||
// 设计动机(参考 xianyu-auto-reply 的 xy_token_cache):
|
||||
// - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控;
|
||||
// - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。
|
||||
// AccountToken 持久化最近一次页面运行实例的 device_id 和 token 请求元数据。
|
||||
// accessToken 不用于后续 WebSocket 注册;官方消息页在每次 loginV2/reConnect
|
||||
// 前都会重新获取 token,页面重载后也会生成新的 device_id。
|
||||
type AccountToken struct {
|
||||
CookieID string
|
||||
DeviceID string
|
||||
AccessToken string
|
||||
ExpireAt int64 // unix 秒,0 表示无有效 token
|
||||
CookieID string
|
||||
DeviceID string
|
||||
AccessToken string
|
||||
ExpireAt int64 // unix 秒,0 表示无有效 token
|
||||
CookieFingerprint string
|
||||
}
|
||||
|
||||
// AccountTokens 读写 account_tokens 表。
|
||||
type AccountTokens struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Get 取账号缓存的 device_id + accessToken。无记录返回 ErrNotFound。
|
||||
@@ -30,37 +30,99 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
|
||||
var tk AccountToken
|
||||
tk.CookieID = cookieID
|
||||
err := t.DB.QueryRowContext(ctx,
|
||||
`SELECT device_id, access_token, expire_at FROM account_tokens WHERE cookie_id=?`,
|
||||
cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt)
|
||||
`SELECT device_id, access_token, expire_at, cookie_fingerprint FROM account_tokens WHERE cookie_id=?`,
|
||||
cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt, &tk.CookieFingerprint)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return AccountToken{}, ErrNotFound
|
||||
}
|
||||
return AccountToken{}, err
|
||||
}
|
||||
tk.DeviceID, err = t.codec.decrypt("device-id", cookieID, tk.DeviceID)
|
||||
if err != nil {
|
||||
return AccountToken{}, err
|
||||
}
|
||||
tk.AccessToken, err = t.codec.decrypt("access-token", cookieID, tk.AccessToken)
|
||||
if err != nil {
|
||||
return AccountToken{}, err
|
||||
}
|
||||
return tk, nil
|
||||
}
|
||||
|
||||
// Save upsert 缓存的 device_id + accessToken + expire_at。
|
||||
func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64) error {
|
||||
_, err := t.DB.ExecContext(ctx,
|
||||
`INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "")
|
||||
}
|
||||
|
||||
// SaveBound persists an access token together with the page-runtime device ID
|
||||
// and canonical Cookie state from which it was issued.
|
||||
func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error {
|
||||
encryptedDeviceID, err := t.codec.encrypt("device-id", cookieID, deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
encryptedToken, err := t.codec.encrypt("access-token", cookieID, accessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = t.DB.ExecContext(ctx,
|
||||
`INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, cookie_fingerprint, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(t.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"device_id": "excluded.device_id",
|
||||
"access_token": "excluded.access_token",
|
||||
"expire_at": "excluded.expire_at",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
"device_id": "excluded.device_id",
|
||||
"access_token": "excluded.access_token",
|
||||
"expire_at": "excluded.expire_at",
|
||||
"cookie_fingerprint": "excluded.cookie_fingerprint",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cookieID, deviceID, accessToken, expireAt)
|
||||
cookieID, encryptedDeviceID, encryptedToken, expireAt, cookieFingerprint)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存 account_tokens: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear 删除账号的 token 缓存(session 失效 / 短连接可疑失效时调用)。
|
||||
// GetOrCreateDeviceID returns the permanent device ID for an account. The
|
||||
// candidate is persisted only when the account has no identity yet.
|
||||
func (t *AccountTokens) GetOrCreateDeviceID(ctx context.Context, cookieID, candidate string) (string, error) {
|
||||
if candidate == "" {
|
||||
return "", fmt.Errorf("device_id 不能为空")
|
||||
}
|
||||
encryptedCandidate, err := t.codec.encrypt("device-id", cookieID, candidate)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Insert-once makes concurrent account starts converge on the same identity.
|
||||
// A normal upsert can let two starters each observe a different winning ID.
|
||||
if _, err := t.DB.ExecContext(ctx,
|
||||
dialectInsertIgnorePrefix(t.Dialect)+` INTO account_tokens (cookie_id, device_id, access_token, expire_at, updated_at)
|
||||
VALUES (?, ?, '', 0, CURRENT_TIMESTAMP)`+dialectInsertIgnore(t.Dialect, []string{"cookie_id"}),
|
||||
cookieID, encryptedCandidate); err != nil {
|
||||
return "", fmt.Errorf("创建 account_tokens device_id: %w", err)
|
||||
}
|
||||
// Upgrade the only legacy state that had no identity. The conditional update
|
||||
// is also first-writer-wins under concurrent starts.
|
||||
if _, err := t.DB.ExecContext(ctx,
|
||||
`UPDATE account_tokens SET device_id=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND device_id=''`,
|
||||
encryptedCandidate, cookieID); err != nil {
|
||||
return "", fmt.Errorf("补全 account_tokens device_id: %w", err)
|
||||
}
|
||||
tk, err := t.Get(ctx, cookieID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return tk.DeviceID, nil
|
||||
}
|
||||
|
||||
// Clear clears only the expiring access token. The permanent device_id row is
|
||||
// retained across session expiry, login refresh, risk recovery and restarts.
|
||||
func (t *AccountTokens) Clear(ctx context.Context, cookieID string) error {
|
||||
_, err := t.DB.ExecContext(ctx, `DELETE FROM account_tokens WHERE cookie_id=?`, cookieID)
|
||||
encryptedToken, err := t.codec.encrypt("access-token", cookieID, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = t.DB.ExecContext(ctx,
|
||||
`UPDATE account_tokens SET access_token=?, expire_at=0, cookie_fingerprint='', updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
|
||||
encryptedToken, cookieID)
|
||||
return err
|
||||
}
|
||||
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user