完善系统可靠性、登录风控与跨数据库回归
可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。 登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。 安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。 自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。 前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。 测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。 验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。
This commit is contained in:
1 parent
9a5b20d189
commit
16d63dc7c9
211 files changed
+16449
-3408
No files matched your search
@@ -10,6 +10,7 @@
|
||||
|
||||
# Runtime data
|
||||
/data/
|
||||
/browser_data/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
@@ -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"]
|
||||
@@ -1,5 +1,3 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:22-trixie AS frontend
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
|
||||
+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"]
|
||||
@@ -178,6 +178,16 @@ XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
|
||||
外置 MySQL/Postgres 时改用 `DATABASE_URL` 环境变量。
|
||||
|
||||
生产环境建议同时设置稳定且仅由服务进程可读的 `XIANYU_DATA_KEY`。启用后,Cookie、
|
||||
账号登录密码、设备/访问令牌、AI/SMTP 密钥和通知渠道配置会使用 AES-256-GCM 加密
|
||||
后落库;首次启动会自动升级历史明文。该密钥必须随数据卷一同备份,丢失或更换后
|
||||
已有凭证无法解密。
|
||||
|
||||
管理员配置的 OpenAI 兼容 AI Base URL 不限制目标网络,可使用 `0.0.0.0`、loopback、
|
||||
Docker 服务名、RFC1918 私网、Tailscale/CGNAT、IPv6 ULA 或公网地址,便于连接任意部署
|
||||
位置的 Ollama、vLLM、LocalAI 或兼容网关。通知 Webhook、远程图片等非管理员可信目标
|
||||
继续只允许公网地址。
|
||||
|
||||
## 常用参数
|
||||
|
||||
| 参数 | 说明 |
|
||||
@@ -185,6 +195,7 @@ XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
| `-db` | SQLite 数据库路径,默认 `data/xianyu_data.db`(向后兼容) |
|
||||
| `-db-url` | 数据库连接 URL(`sqlite://` / `mysql://` / `postgres://`),优先级高于 `-db` |
|
||||
| `DATABASE_URL` | 环境变量,优先级最高 |
|
||||
| `XIANYU_DATA_KEY` | 敏感字段加密主密钥;生产环境应固定配置并安全备份 |
|
||||
| `-addr` | HTTP 监听地址,默认 `:8080` |
|
||||
| `-web` | 外部前端静态资源目录;不传则用内置前端 |
|
||||
| `-init-admin` | 初始化或重置管理员后退出 |
|
||||
@@ -225,7 +236,7 @@ MySQL 8.4 与 PostgreSQL 17 API 功能及重启持久化):
|
||||
|
||||
测试编排使用命名卷 `mysql8_data`、`postgres17_data` 和 `sqlite_seed`。
|
||||
本地 `data/xianyu_data.db` 只会抽取少量商品、订单和卡密元数据,写入外置库前会替换
|
||||
Cookie、买家 ID 和卡密内容。测试应用分别监听 `18081`(MySQL)与 `18082`
|
||||
Cookie、买家 ID 和卡密内容。测试应用分别监听 `28081`(MySQL)与 `28082`
|
||||
(PostgreSQL),测试账号为 `docker_fixture / docker_fixture_password`。
|
||||
测试管理员为 `docker_admin / docker_admin_password`。
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/server"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -92,6 +93,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) != "" {
|
||||
@@ -125,6 +130,11 @@ func main() {
|
||||
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)
|
||||
}
|
||||
mtop.SetDefaultTokenRequestExecutor(bm)
|
||||
}
|
||||
var mgr *account.Manager
|
||||
ap := adapter.New(store, bm, logger)
|
||||
@@ -132,6 +142,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)
|
||||
@@ -143,6 +154,7 @@ func main() {
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
go srv.RunPublishBatchRecovery(ctx)
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
logger.Error("HTTP 服务退出", "err", err)
|
||||
// 即便出错也尝试清理已启动的账号与浏览器。
|
||||
@@ -157,6 +169,7 @@ func main() {
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
}
|
||||
notifier.Wait()
|
||||
}
|
||||
|
||||
// handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。
|
||||
|
||||
@@ -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:
|
||||
+333
-136
@@ -9,27 +9,30 @@ import {
|
||||
generateQRLogin,
|
||||
checkQRLoginStatus,
|
||||
completeQRVerification,
|
||||
updateAccountRemark,
|
||||
updateAccountAutoConfirm,
|
||||
updateAccountPauseDuration,
|
||||
updateAccountCookie,
|
||||
refreshAccountProfile,
|
||||
updateAccountLoginInfo,
|
||||
updateAccountSettings,
|
||||
passwordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
cancelPasswordLogin,
|
||||
updateAccountAISettings,
|
||||
getAllAISettings,
|
||||
getAccountAISettings,
|
||||
getNotificationChannels,
|
||||
getAccountBindings,
|
||||
setAccountBindings,
|
||||
} 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,10 +44,8 @@ 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);
|
||||
@@ -79,11 +80,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 +116,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 +144,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 +169,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 +281,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 +311,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 || '',
|
||||
@@ -270,10 +332,16 @@ const AccountList: React.FC = () => {
|
||||
};
|
||||
|
||||
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 +350,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 +361,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 +405,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 +440,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 +564,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 +612,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 +622,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 +734,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 +805,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 +824,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 +835,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 +864,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 +947,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>
|
||||
|
||||
{/* 登录信息 */}
|
||||
@@ -859,6 +1023,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 +1115,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 +1149,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 +1252,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}
|
||||
>
|
||||
|
||||
@@ -17,6 +17,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 +43,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);
|
||||
|
||||
// 批量导入
|
||||
@@ -112,7 +120,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,
|
||||
@@ -849,7 +857,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,4 +1,4 @@
|
||||
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';
|
||||
@@ -14,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 = {
|
||||
@@ -23,6 +24,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: '已完成',
|
||||
cancelled: '已取消',
|
||||
refunding: '退款中',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -63,36 +65,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 +128,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 +292,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 +328,7 @@ const Dashboard: React.FC = () => {
|
||||
/>
|
||||
<StatCard
|
||||
title="库存卡密余量"
|
||||
value={stats.total_cards}
|
||||
value={stats.available_card_stock}
|
||||
icon={Package}
|
||||
colorClass="bg-purple-500"
|
||||
/>
|
||||
@@ -498,7 +512,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="搜索订单号/商品/买家..."
|
||||
@@ -628,7 +647,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, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { selectActivePublishBatch } from './itemPublishBatchState';
|
||||
import { Item, AccountDetail, ShippingRule } from '../types';
|
||||
import {
|
||||
getItems,
|
||||
@@ -10,6 +11,8 @@ import {
|
||||
previewItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
getItemPublishBatches,
|
||||
deleteItemPublishBatch,
|
||||
cancelItemPublishBatch,
|
||||
retryFailedItemPublishBatch,
|
||||
updateItem,
|
||||
@@ -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[];
|
||||
}
|
||||
|
||||
@@ -90,6 +95,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 +144,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 +312,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 +380,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 +395,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 +406,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 +474,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 '已完成';
|
||||
@@ -481,12 +551,20 @@ 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>
|
||||
|
||||
@@ -734,7 +812,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>
|
||||
@@ -855,14 +933,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 +1073,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 +1088,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>
|
||||
|
||||
@@ -228,6 +228,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) {
|
||||
@@ -344,8 +346,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 +543,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"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, 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 { 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';
|
||||
|
||||
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
const styles = {
|
||||
@@ -12,6 +13,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 +23,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
|
||||
completed: '已完成',
|
||||
cancelled: '已取消',
|
||||
refunding: '退款中',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -32,11 +35,12 @@ 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 [itemNames, setItemNames] = useState<Record<string, string>>({});
|
||||
const [filter, setFilter] = useState('all');
|
||||
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,66 +55,27 @@ 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(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 => {
|
||||
// 如果订单有 item_title,优先使用
|
||||
@@ -164,16 +129,26 @@ const OrderList: React.FC = () => {
|
||||
setItemNames(namesMap);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setPage(1);
|
||||
setDebouncedSearch(searchText.trim());
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
loadOrders();
|
||||
// 加载商品列表
|
||||
}, [filter, page, debouncedSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
getItems().then((itemsList) => {
|
||||
setItems(itemsList);
|
||||
buildItemNamesMapFrom(itemsList);
|
||||
}).catch((e) => {
|
||||
console.error('加载商品列表失败:', e);
|
||||
});
|
||||
}, [filter, page, searchText]);
|
||||
}, []);
|
||||
|
||||
const handleSync = async () => {
|
||||
setLoading(true);
|
||||
@@ -256,6 +231,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 +246,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 +296,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 +322,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 +341,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}
|
||||
@@ -640,7 +638,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 +658,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 +861,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>
|
||||
);
|
||||
+186
-22
@@ -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">
|
||||
@@ -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">
|
||||
|
||||
@@ -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,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,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);
|
||||
|
||||
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,6 +60,17 @@ describe('frontend navigation routing', () => {
|
||||
expect(settings).toContain('setLoadError');
|
||||
});
|
||||
|
||||
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 uses backend recipient field names', () => {
|
||||
const notifications = readFrontendFile('components/Notifications.tsx');
|
||||
|
||||
@@ -137,11 +148,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');
|
||||
});
|
||||
});
|
||||
+182
-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',
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -137,6 +237,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 +259,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 +272,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 +383,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 +394,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 +404,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 +590,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);
|
||||
|
||||
+146
-103
@@ -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,22 @@ 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 PasswordLoginStartResponse {
|
||||
success: boolean;
|
||||
session_id?: string;
|
||||
@@ -172,8 +188,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 +209,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 +241,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 +275,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 +311,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
|
||||
@@ -465,6 +483,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 +580,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 +594,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 +627,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 +674,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 +690,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 +703,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 +727,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 +774,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 +852,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
|
||||
}
|
||||
|
||||
@@ -332,8 +332,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 +386,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 +416,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 +431,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 {
|
||||
|
||||
+78
-46
@@ -7,6 +7,7 @@ package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
@@ -40,6 +41,10 @@ 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 tokenCaptchaRequester interface {
|
||||
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
|
||||
}
|
||||
@@ -160,14 +165,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 +194,57 @@ 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
|
||||
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, browser.ResolveHeadless(showBrowser), provider,
|
||||
)
|
||||
} else {
|
||||
newCookies, err = br.TokenCaptchaRecover(
|
||||
ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), 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(),
|
||||
})
|
||||
@@ -238,7 +262,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
_ = 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 +275,14 @@ 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}, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
@@ -301,7 +325,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
return nil, err
|
||||
}
|
||||
if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
_ = a.store.Cookies.Save(ctx, cookieID, detail.UpdatedCookies, 0)
|
||||
_ = a.store.Cookies.UpdateValueExisting(ctx, cookieID, detail.UpdatedCookies)
|
||||
}
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
@@ -334,9 +358,9 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if ok, remain := cooldown.TryPasswordLogin(cookieID); !ok {
|
||||
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", "login_cooldown", fmt.Sprintf("密码登录刷新冷却中,还需等待 %s", 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) {
|
||||
@@ -352,10 +376,18 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
return false
|
||||
}
|
||||
|
||||
if a.tryLightRenewBeforePassword(ctx, d) {
|
||||
lightRenewed, lightRenewErr := a.tryLightRenewBeforePassword(ctx, d)
|
||||
if lightRenewed {
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "密码登录前轻量续期成功")
|
||||
return true
|
||||
}
|
||||
if errors.Is(lightRenewErr, browser.ErrSecurityVerification) {
|
||||
cooldown.MarkPasswordError(cookieID)
|
||||
message := "浏览器续期遇到闲鱼安全验证,已停止自动密码登录,请人工完成验证或重新扫码"
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn, "闲鱼要求安全验证", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "verification_required", message)
|
||||
return false
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -394,7 +426,9 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
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 {
|
||||
// 参考实现只在真实密码登录拿到 Cookie 后启动 60 秒冷却。
|
||||
cooldown.MarkPasswordLogin(cookieID)
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, cookieID, cookieStr); err != nil {
|
||||
a.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "cookie_update_failed", err.Error())
|
||||
return false
|
||||
@@ -473,9 +507,9 @@ func truncateMessage(s string, n int) string {
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) bool {
|
||||
func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) (bool, error) {
|
||||
if d == nil {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
current := d.Value
|
||||
api := a.renewSvc
|
||||
@@ -516,21 +550,24 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
|
||||
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)
|
||||
save(renewed)
|
||||
a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
|
||||
return true, nil
|
||||
} else if err != nil {
|
||||
if errors.Is(err, browser.ErrSecurityVerification) {
|
||||
return false, err
|
||||
}
|
||||
a.logger.Warn("密码登录前浏览器续期失败,继续尝试接口续期", "account", d.ID, "err", err)
|
||||
}
|
||||
if res, err := apiRenew(browserCookies); err == nil && res != nil {
|
||||
if res, err := apiRenew(current); err == nil && res != nil {
|
||||
save(res.NewCookies)
|
||||
if res.Success {
|
||||
a.logger.Info("密码登录前浏览器+接口续期成功,跳过密码登录", "account", d.ID)
|
||||
return true
|
||||
a.logger.Info("密码登录前静默续期成功,跳过密码登录", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
|
||||
res, err := apiRenew(current)
|
||||
@@ -538,7 +575,7 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
save(res.NewCookies)
|
||||
if res.Success {
|
||||
a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
|
||||
return true
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
browserInput := current
|
||||
@@ -547,19 +584,14 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
}
|
||||
browserCookies, err := browserRenew(browserInput)
|
||||
if err != nil || browserCookies == "" {
|
||||
return false
|
||||
if errors.Is(err, browser.ErrSecurityVerification) {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
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
|
||||
a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string, err error) {
|
||||
|
||||
@@ -184,15 +184,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 +201,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")
|
||||
@@ -300,6 +301,9 @@ func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
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)
|
||||
@@ -373,8 +377,8 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
|
||||
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)
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did-old" {
|
||||
t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
@@ -435,8 +439,11 @@ 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" {
|
||||
if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "password_error_cooldown" || logs[1].FailureReason != "verification_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)
|
||||
}
|
||||
}
|
||||
+431
-127
@@ -15,6 +15,27 @@ import (
|
||||
"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 +101,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 +218,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 +242,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 +273,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 +330,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 +357,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 +564,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 +581,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 +591,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 +712,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,7 +726,10 @@ 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
|
||||
@@ -460,10 +741,13 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
}
|
||||
ok, ret, updated, err := c.mtop.ConsignContext(ctx, cookieStr, task.OrderID)
|
||||
if err != nil {
|
||||
return err
|
||||
return uncertainAction(err)
|
||||
}
|
||||
var persistenceErrs []error
|
||||
if updated != "" && updated != cookieStr {
|
||||
_ = c.store.Cookies.Save(ctx, task.AccountID, updated, 0)
|
||||
if saveErr := c.store.Cookies.UpdateValueExisting(ctx, task.AccountID, updated); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
|
||||
}
|
||||
if c.senders != nil {
|
||||
if sender, running := c.senders.Sender(task.AccountID); running {
|
||||
sender.UpdateCookie(updated)
|
||||
@@ -471,18 +755,29 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
}
|
||||
}
|
||||
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 +793,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 +807,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 +828,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 +869,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 +905,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 +1021,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,6 +3,7 @@ package automation
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -85,11 +86,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 +110,38 @@ 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")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -9,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -19,17 +22,51 @@ 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
|
||||
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) {}
|
||||
|
||||
@@ -83,6 +120,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 +588,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 +654,48 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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 +836,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 +862,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))
|
||||
}
|
||||
}
|
||||
+172
-104
@@ -2,6 +2,7 @@ package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -17,7 +18,11 @@ 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"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInteractiveLoginRequired = errors.New("浏览器会话已退出登录,需要交互式登录")
|
||||
ErrSecurityVerification = errors.New("闲鱼要求安全验证,需要人工处理")
|
||||
)
|
||||
|
||||
// CookieRenew 用现有 Cookie 打开闲鱼页面,尝试通过“快速进入”刷新浏览器登录态。
|
||||
@@ -32,6 +37,69 @@ func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, h
|
||||
return cookierefresh.ParseCookieString(newCookies), nil
|
||||
}
|
||||
|
||||
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() }
|
||||
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := m.init(); err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, err
|
||||
}
|
||||
userDataDir, err = resolvePersistentUserDataDir(userDataDir)
|
||||
if err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, 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)
|
||||
}
|
||||
if bctx == nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
|
||||
}
|
||||
release := func() {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
unlock()
|
||||
}
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
|
||||
if cookieStr == "" {
|
||||
@@ -58,11 +126,19 @@ func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr str
|
||||
}
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
|
||||
hasQuickEnter := clickQuickEnter(page)
|
||||
if hasQuickEnter {
|
||||
hasQuickEnter := false
|
||||
if err := verifyHomeLoginState(page); err != nil {
|
||||
if errors.Is(err, ErrSecurityVerification) {
|
||||
return "", err
|
||||
}
|
||||
hasQuickEnter = clickQuickEnter(page)
|
||||
if !hasQuickEnter {
|
||||
return "", err
|
||||
}
|
||||
time.Sleep(quickRenewAfterClick)
|
||||
} else if !checkAlreadyLoggedIn(page) {
|
||||
return "", fmt.Errorf("未找到[快速进入]按钮且未检测到登录状态,需要账号密码登录")
|
||||
if err := verifyHomeLoginState(page); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
all, err := bctx.Cookies()
|
||||
@@ -79,12 +155,15 @@ func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr str
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// CookiesRefreshSnapshot 执行定时 COOKIES 续期:打开首页、刷新页面并返回完整 Cookie 快照。
|
||||
// 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, error) {
|
||||
if cookieStr == "" && len(snapshot) == 0 {
|
||||
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
|
||||
}
|
||||
bctx, release, err := m.newEphemeralRefreshContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -102,27 +181,9 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
}); err != nil {
|
||||
m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", 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)
|
||||
}
|
||||
|
||||
if modal, err := page.QuerySelector(".ant-modal-body"); err == nil && modal != nil {
|
||||
text, _ := modal.TextContent()
|
||||
if len(text) > 120 {
|
||||
text = text[:120]
|
||||
}
|
||||
if text != "" {
|
||||
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败: %s", text)
|
||||
}
|
||||
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败")
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
if err := verifyHomeLoginState(page); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
all, err := bctx.Cookies()
|
||||
@@ -176,30 +237,66 @@ 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 checkAlreadyLoggedIn(page playwright.Page) bool {
|
||||
return verifyHomeLoginState(page) == nil
|
||||
}
|
||||
|
||||
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 verifyHomeLoginState(page playwright.Page) error {
|
||||
if pageHasSecurityVerification(page) {
|
||||
return ErrSecurityVerification
|
||||
}
|
||||
bodyText, err := page.TextContent("body")
|
||||
if err == nil && strings.Contains(bodyText, "消息") && (strings.Contains(bodyText, "订单") || strings.Contains(bodyText, "发闲置")) {
|
||||
return true
|
||||
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 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
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -215,7 +312,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 +329,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 +347,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),
|
||||
@@ -264,12 +369,24 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if len(snapshot) > 0 {
|
||||
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 +398,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)
|
||||
}
|
||||
|
||||
+32
-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
|
||||
@@ -127,38 +123,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("同一浏览器配置不应产生漂移的指纹脚本")
|
||||
}
|
||||
}
|
||||
@@ -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,6 +80,10 @@ type Manager struct {
|
||||
// 允许测试注入自定义 playwright / 安装函数。
|
||||
installFn func() error
|
||||
runFn func() (*playwright.Playwright, error)
|
||||
|
||||
// 仅用于隔离 token 风控引擎编排测试;生产环境为 nil,调用真实实现。
|
||||
tokenCaptchaPrimaryFn tokenCaptchaEngineFunc
|
||||
tokenCaptchaFallbackFn tokenCaptchaEngineFunc
|
||||
}
|
||||
|
||||
type poolEntry struct {
|
||||
@@ -169,12 +160,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()
|
||||
@@ -265,7 +315,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,7 +328,9 @@ 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{
|
||||
@@ -368,5 +419,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)
|
||||
}
|
||||
@@ -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,78 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// ExecuteTokenRequest sends the signed token request from a real Chromium page
|
||||
// so TLS, UA, Client Hints, Origin, Referer and the browser cookie jar all agree.
|
||||
func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowserRequest) (*mtop.TokenBrowserResponse, error) {
|
||||
if strings.TrimSpace(req.URL) == "" || strings.TrimSpace(req.Cookies) == "" {
|
||||
return nil, fmt.Errorf("浏览器 token 请求参数不完整")
|
||||
}
|
||||
unb := protocol.TransCookies(req.Cookies)["unb"]
|
||||
if unb == "" {
|
||||
return nil, fmt.Errorf("浏览器 token 请求缺少 unb")
|
||||
}
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, unb, req.Cookies, nil, true, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("浏览器 token 请求新建页面: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(15000),
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("浏览器 token 请求初始化站点: %w", err)
|
||||
}
|
||||
value, err := page.Evaluate(`async ({url, body}) => {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'content-type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
body
|
||||
});
|
||||
return {status: response.status, body: await response.text()};
|
||||
}`, map[string]any{"url": req.URL, "body": req.Body})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("浏览器执行 token fetch: %w", err)
|
||||
}
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result struct {
|
||||
Status int `json:"status"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析浏览器 token 响应: %w", err)
|
||||
}
|
||||
all, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取浏览器 token Cookie: %w", err)
|
||||
}
|
||||
browserCookies := cookierefresh.CookieStringFromSnapshot(cookieSnapshotFromPlaywright(all))
|
||||
return &mtop.TokenBrowserResponse{
|
||||
Status: result.Status,
|
||||
Body: []byte(result.Body),
|
||||
UpdatedCookies: cookierefresh.MergeOriginalFields(req.Cookies, browserCookies),
|
||||
}, nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ type AccountToken struct {
|
||||
type AccountTokens struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Get 取账号缓存的 device_id + accessToken。无记录返回 ErrNotFound。
|
||||
@@ -38,12 +39,35 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
|
||||
}
|
||||
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,
|
||||
// device_id is an account identity, not part of the expiring token cache.
|
||||
// Once stored, token refreshes must never replace it.
|
||||
if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" {
|
||||
deviceID = existing.DeviceID
|
||||
} else if err != nil && !errors.Is(err, ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
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, updated_at)
|
||||
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(t.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
@@ -52,15 +76,54 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke
|
||||
"expire_at": "excluded.expire_at",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cookieID, deviceID, accessToken, expireAt)
|
||||
cookieID, encryptedDeviceID, encryptedToken, expireAt)
|
||||
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, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
|
||||
encryptedToken, cookieID)
|
||||
return err
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -37,21 +39,22 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
t.Fatalf("Get 返回不匹配: %+v", tk)
|
||||
}
|
||||
|
||||
// 再次 Save 覆盖(upsert)。
|
||||
// 再次 Save 更新 token,但永久 device ID 不允许覆盖。
|
||||
if err := store.Tokens.Save(ctx, "cid", "dev-2", "tok-2", expire+1); err != nil {
|
||||
t.Fatalf("Save upsert: %v", err)
|
||||
}
|
||||
tk, _ = store.Tokens.Get(ctx, "cid")
|
||||
if tk.DeviceID != "dev-2" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 {
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 {
|
||||
t.Fatalf("upsert 后字段应更新: %+v", tk)
|
||||
}
|
||||
|
||||
// Clear → 再 Get 应 ErrNotFound。
|
||||
// Clear 只清 token,永久 device ID 必须保留。
|
||||
if err := store.Tokens.Clear(ctx, "cid"); err != nil {
|
||||
t.Fatalf("Clear: %v", err)
|
||||
}
|
||||
if _, err := store.Tokens.Get(ctx, "cid"); err != ErrNotFound {
|
||||
t.Fatalf("Clear 后应 ErrNotFound,got %v", err)
|
||||
tk, err = store.Tokens.Get(ctx, "cid")
|
||||
if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 {
|
||||
t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
|
||||
// Clear 不存在的行不应报错。
|
||||
@@ -59,3 +62,75 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
t.Fatalf("Clear 不存在的行不应报错: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.Users.Create(ctx, "admin", "a@e.com", "pw")
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if err := store.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=t;", admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", "device-first")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Tokens.Save(ctx, "cid", "device-replacement", "token", time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Tokens.Clear(ctx, "cid"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
afterRestart, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", "device-after-restart")
|
||||
if err != nil || first != "device-first" || afterRestart != first {
|
||||
t.Fatalf("device ID changed across token lifecycle: first=%q after=%q err=%v", first, afterRestart, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTokens_ConcurrentDeviceIDCreationConverges(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.Users.Create(ctx, "admin", "a@e.com", "pw")
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if err := store.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=t;", admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const workers = 12
|
||||
results := make(chan string, workers)
|
||||
errs := make(chan error, workers)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
deviceID, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", fmt.Sprintf("device-%d", i))
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
results <- deviceID
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var permanent string
|
||||
for deviceID := range results {
|
||||
if permanent == "" {
|
||||
permanent = deviceID
|
||||
}
|
||||
if deviceID != permanent {
|
||||
t.Fatalf("concurrent device IDs diverged: first=%q got=%q", permanent, deviceID)
|
||||
}
|
||||
}
|
||||
stored, err := store.Tokens.Get(ctx, "cid")
|
||||
if err != nil || stored.DeviceID != permanent {
|
||||
t.Fatalf("stored=%+v permanent=%q err=%v", stored, permanent, err)
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,10 @@ type AIReplySettings struct {
|
||||
}
|
||||
|
||||
// AIReply 操作。
|
||||
type AIReply struct{ DB *sql.DB }
|
||||
type AIReply struct {
|
||||
DB *sql.DB
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Get 取某账号 AI 回复配置。
|
||||
func (a *AIReply) Get(ctx context.Context, cookieID string) (*AIReplySettings, error) {
|
||||
@@ -48,7 +51,10 @@ func (a *AIReply) Get(ctx context.Context, cookieID string) (*AIReplySettings, e
|
||||
return nil, err
|
||||
}
|
||||
s.AIEnabled = enabled != 0
|
||||
s.APIKey = apiKey.String
|
||||
s.APIKey, err = a.codec.decrypt("ai-api-key", cookieID, apiKey.String)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.CustomPrompts = customPrompts.String
|
||||
if s.ModelName == "" {
|
||||
s.ModelName = "qwen-plus"
|
||||
|
||||
+562
-35
@@ -6,8 +6,12 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行")
|
||||
|
||||
// AutomationRules 管理自动化规则、动作和执行记录。
|
||||
//
|
||||
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
|
||||
@@ -52,21 +56,63 @@ type AutomationAction struct {
|
||||
|
||||
// AutomationRun 是一次自动化执行记录。trigger_key 是持久化防重键。
|
||||
type AutomationRun struct {
|
||||
ID int64
|
||||
RuleID int64
|
||||
CookieID string
|
||||
ItemID string
|
||||
OrderID string
|
||||
BuyerID string
|
||||
ChatID string
|
||||
TriggerType string
|
||||
TriggerKey string
|
||||
Status string
|
||||
SentCount int
|
||||
ErrorMessage string
|
||||
RawEventJSON string
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
LeaseExpiresAt int64
|
||||
AttemptCount int
|
||||
NextRetryAt int64
|
||||
ActionCursor int
|
||||
ActionStarted bool
|
||||
}
|
||||
|
||||
// ErrAutomationRunLeaseLost 表示自动化运行已被更高 attempt_count 的 worker 接管。
|
||||
var ErrAutomationRunLeaseLost = errors.New("自动化运行租约已失效")
|
||||
|
||||
type DeferredAutomationTask struct {
|
||||
ID int64
|
||||
RuleID int64
|
||||
TaskKey string
|
||||
CookieID string
|
||||
ItemID string
|
||||
OrderID string
|
||||
BuyerID string
|
||||
ChatID string
|
||||
TriggerType string
|
||||
TriggerKey string
|
||||
Status string
|
||||
SentCount int
|
||||
ErrorMessage string
|
||||
RawEventJSON string
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
TaskJSON string
|
||||
DueAt int64
|
||||
ClaimVersion int
|
||||
}
|
||||
|
||||
var ErrDeferredTaskLeaseLost = errors.New("延迟自动化任务租约已失效")
|
||||
|
||||
type AutomationRunIssue struct {
|
||||
ID int64 `json:"id"`
|
||||
CookieID string `json:"cookie_id"`
|
||||
OrderID string `json:"order_id"`
|
||||
TriggerType string `json:"trigger_type"`
|
||||
ErrorMessage string `json:"error_message"`
|
||||
IssueKind string `json:"issue_kind"`
|
||||
AllowedResolutions []string `json:"allowed_resolutions"`
|
||||
ActionCursor int `json:"action_cursor"`
|
||||
SentCount int `json:"sent_count"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type DeferredAutomationIssue struct {
|
||||
ID int64 `json:"id"`
|
||||
CookieID string `json:"cookie_id"`
|
||||
TriggerType string `json:"trigger_type"`
|
||||
ErrorMessage string `json:"error_message"`
|
||||
AttemptCount int `json:"attempt_count"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AutomationRuleInput 是创建/更新规则的输入。
|
||||
@@ -126,8 +172,47 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Match 查询某事件可触发的规则。商品精确规则优先,其次允许 item_id 为空的账号级规则。
|
||||
// Match 查询某事件可触发的规则。商品级规则存在时只返回商品级规则;
|
||||
// 没有商品级规则时才回退到账号级规则,避免两层规则叠加导致重复发货。
|
||||
func (a *AutomationRules) Match(ctx context.Context, cookieID, itemID, triggerType string) ([]AutomationRule, error) {
|
||||
out, err := a.matchScope(ctx, cookieID, itemID, triggerType)
|
||||
if err != nil || len(out) > 0 || itemID == "" {
|
||||
return highestPriorityRule(out), err
|
||||
}
|
||||
out, err = a.matchScope(ctx, cookieID, "", triggerType)
|
||||
return highestPriorityRule(out), err
|
||||
}
|
||||
|
||||
func highestPriorityRule(rules []AutomationRule) []AutomationRule {
|
||||
if len(rules) <= 1 {
|
||||
return rules
|
||||
}
|
||||
return rules[:1]
|
||||
}
|
||||
|
||||
// Get 返回指定规则及其动作。
|
||||
func (a *AutomationRules) Get(ctx context.Context, ruleID int64) (*AutomationRule, error) {
|
||||
var rule AutomationRule
|
||||
var enabled int
|
||||
err := a.DB.QueryRowContext(ctx, `
|
||||
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
|
||||
r.priority,r.config_json,r.created_at,r.updated_at
|
||||
FROM automation_rules r
|
||||
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
|
||||
WHERE r.id=?`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle,
|
||||
&rule.Name, &rule.TriggerType, &enabled, &rule.Priority, &rule.ConfigJSON, &rule.CreatedAt, &rule.UpdatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rule.Enabled = enabled != 0
|
||||
rule.Actions, err = a.Actions(ctx, rule.ID)
|
||||
return &rule, err
|
||||
}
|
||||
|
||||
func (a *AutomationRules) matchScope(ctx context.Context, cookieID, itemID, triggerType string) ([]AutomationRule, error) {
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
|
||||
r.priority,r.config_json,r.created_at,r.updated_at
|
||||
@@ -136,9 +221,8 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
|
||||
WHERE r.enabled=1
|
||||
AND r.cookie_id=?
|
||||
AND r.trigger_type=?
|
||||
AND (r.item_id=? OR r.item_id='')
|
||||
ORDER BY CASE WHEN r.item_id=? THEN 0 ELSE 1 END, r.priority ASC, r.id ASC`,
|
||||
cookieID, triggerType, itemID, itemID)
|
||||
AND r.item_id=?
|
||||
ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -210,11 +294,21 @@ UPDATE automation_rules
|
||||
|
||||
// Delete 删除规则。
|
||||
func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_rules WHERE id=? AND user_id=?`, ruleID, userID)
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_rules
|
||||
WHERE id=? AND user_id=? AND NOT EXISTS (
|
||||
SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id
|
||||
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
var exists int
|
||||
if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=?`, ruleID, userID).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists > 0 {
|
||||
return ErrAutomationRunActive
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
@@ -251,11 +345,16 @@ SELECT a.id,a.rule_id,a.action_type,COALESCE(a.card_id,0),COALESCE(c.name,''),a.
|
||||
// TryStartRun 以 UNIQUE(rule_id, trigger_key) 作为持久化防重。
|
||||
// 返回 started=false 表示该规则对该触发已执行或正在执行,调用方应直接跳过。
|
||||
func (a *AutomationRules) TryStartRun(ctx context.Context, run AutomationRun) (int64, bool, error) {
|
||||
now := time.Now().UTC().Unix()
|
||||
leaseExpiresAt := run.LeaseExpiresAt
|
||||
if leaseExpiresAt <= now {
|
||||
leaseExpiresAt = now + int64((5*time.Minute)/time.Second)
|
||||
}
|
||||
query := dialectInsertIgnorePrefix(a.Dialect) + ` INTO automation_runs
|
||||
(rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,status,raw_event_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(a.Dialect, []string{"rule_id", "trigger_key"})
|
||||
(rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,status,raw_event_json,lease_expires_at,attempt_count,next_retry_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(a.Dialect, []string{"rule_id", "trigger_key"})
|
||||
args := []any{run.RuleID, run.CookieID, run.ItemID, run.OrderID, run.BuyerID, run.ChatID,
|
||||
run.TriggerType, run.TriggerKey, "running", validJSON(run.RawEventJSON)}
|
||||
run.TriggerType, run.TriggerKey, "running", validJSON(run.RawEventJSON), leaseExpiresAt, 1, 0}
|
||||
|
||||
if a.Dialect == DialectPostgres {
|
||||
// pgx 不支持 LastInsertId;用 RETURNING id。ON CONFLICT DO NOTHING 冲突时无行返回 → 未启动。
|
||||
@@ -263,7 +362,7 @@ VALUES (?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(a.Dialect, []string{"rule_id
|
||||
err := a.DB.QueryRowContext(ctx, query+" RETURNING id", args...).Scan(&id)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, false, nil
|
||||
return a.reclaimRun(ctx, run.RuleID, run.TriggerKey, leaseExpiresAt, now)
|
||||
}
|
||||
return 0, false, err
|
||||
}
|
||||
@@ -275,21 +374,433 @@ VALUES (?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(a.Dialect, []string{"rule_id
|
||||
return 0, false, err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return 0, false, nil
|
||||
return a.reclaimRun(ctx, run.RuleID, run.TriggerKey, leaseExpiresAt, now)
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return id, true, nil
|
||||
}
|
||||
|
||||
// FinishRun 标记执行完成或失败。
|
||||
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, status string, sentCount int, errMsg string) error {
|
||||
_, err := a.DB.ExecContext(ctx, `
|
||||
UPDATE automation_runs
|
||||
SET status=?,sent_count=?,error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, status, sentCount, errMsg, id)
|
||||
func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerKey string, leaseExpiresAt, now int64) (int64, bool, error) {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,
|
||||
attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE rule_id=? AND trigger_key=?
|
||||
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`,
|
||||
leaseExpiresAt, ruleID, triggerKey, now, now)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil || n != 1 {
|
||||
return 0, false, rowsErr
|
||||
}
|
||||
var id int64
|
||||
if err := a.DB.QueryRowContext(ctx,
|
||||
`SELECT id FROM automation_runs WHERE rule_id=? AND trigger_key=?`, ruleID, triggerKey).Scan(&id); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return id, true, nil
|
||||
}
|
||||
|
||||
// GetRun 返回自动化运行及动作检查点。
|
||||
func (a *AutomationRules) GetRun(ctx context.Context, id int64) (*AutomationRun, error) {
|
||||
var run AutomationRun
|
||||
var actionStarted int
|
||||
err := a.DB.QueryRowContext(ctx, `SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,
|
||||
status,sent_count,error_message,raw_event_json,lease_expires_at,attempt_count,next_retry_at,action_cursor,action_started
|
||||
FROM automation_runs WHERE id=?`, id).Scan(&run.ID, &run.RuleID, &run.CookieID, &run.ItemID, &run.OrderID,
|
||||
&run.BuyerID, &run.ChatID, &run.TriggerType, &run.TriggerKey, &run.Status, &run.SentCount,
|
||||
&run.ErrorMessage, &run.RawEventJSON, &run.LeaseExpiresAt, &run.AttemptCount, &run.NextRetryAt,
|
||||
&run.ActionCursor, &actionStarted)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
run.ActionStarted = actionStarted != 0
|
||||
return &run, err
|
||||
}
|
||||
|
||||
// StartRunAction 在外部副作用前持久化 started;崩溃恢复看到 started 时不会盲目重放。
|
||||
func (a *AutomationRules) StartRunAction(ctx context.Context, runID int64, attempt, cursor int, leaseExpiresAt int64) (bool, error) {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET action_started=1,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status='running' AND action_cursor=? AND action_started=0`, leaseExpiresAt, runID, attempt, cursor)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// AdvanceRunAction 在动作明确成功后推进游标并累计已发送数量。
|
||||
func (a *AutomationRules) AdvanceRunAction(ctx context.Context, runID int64, attempt, cursor, sentDelta int) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET action_cursor=?,action_started=0,sent_count=sent_count+?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status='running' AND action_cursor=? AND action_started=1`, cursor+1, sentDelta, runID, attempt, cursor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) AbortRunAction(ctx context.Context, runID int64, attempt, cursor int) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET action_started=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status='running' AND action_cursor=?`, runID, attempt, cursor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) RenewRunLease(ctx context.Context, runID int64, attempt int, leaseExpiresAt int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status='running'`, leaseExpiresAt, runID, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) QuarantineRun(ctx context.Context, runID int64, attempt int, reason string) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='needs_review',error_message=?,lease_expires_at=0,next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status IN ('running','failed')`, reason, runID, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) QuarantineRunResult(ctx context.Context, runID int64, attempt, sentCount int, reason string) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='needs_review',sent_count=?,error_message=?,lease_expires_at=0,next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status IN ('running','failed')`, sentCount, reason, runID, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
// PostponeRecoveryRun 把暂时不能执行的账号移到恢复队列尾部,避免固定的前 100 条饿死后续任务。
|
||||
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID, retryAt int64) error {
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET lease_expires_at=CASE WHEN status='running' THEN ? ELSE lease_expires_at END,
|
||||
next_retry_at=CASE WHEN status='failed' THEN ? ELSE next_retry_at END,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('running','failed')`, retryAt, retryAt, runID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpiresAt int64) (bool, error) {
|
||||
now := time.Now().UTC().Unix()
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`, leaseExpiresAt, runID, now, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinishRun 标记执行完成或失败。
|
||||
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
|
||||
nextRetryAt := int64(0)
|
||||
if status == "failed" && sentCount == 0 {
|
||||
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
|
||||
}
|
||||
res, err := a.DB.ExecContext(ctx, `
|
||||
UPDATE automation_runs
|
||||
SET status=?,sent_count=?,error_message=?,lease_expires_at=0,next_retry_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND status='running'`, status, sentCount, errMsg, nextRetryAt, id, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func requireAutomationRunOwner(res sql.Result) error {
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrAutomationRunLeaseLost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DueRecoveryRuns 返回需要主动恢复的失败运行和租约已过期的运行。
|
||||
// 真正的领取仍由 TryStartRun 完成,多个 scheduler 并发扫描也不会重复执行。
|
||||
func (a *AutomationRules) DueRecoveryRuns(ctx context.Context, limit int) ([]AutomationRun, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
now := time.Now().UTC().Unix()
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,
|
||||
status,sent_count,error_message,raw_event_json,lease_expires_at,attempt_count,next_retry_at,action_cursor,action_started
|
||||
FROM automation_runs
|
||||
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?)
|
||||
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AutomationRun
|
||||
for rows.Next() {
|
||||
var run AutomationRun
|
||||
var actionStarted int
|
||||
if err := rows.Scan(&run.ID, &run.RuleID, &run.CookieID, &run.ItemID, &run.OrderID,
|
||||
&run.BuyerID, &run.ChatID, &run.TriggerType, &run.TriggerKey, &run.Status,
|
||||
&run.SentCount, &run.ErrorMessage, &run.RawEventJSON, &run.LeaseExpiresAt,
|
||||
&run.AttemptCount, &run.NextRetryAt, &run.ActionCursor, &actionStarted); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run.ActionStarted = actionStarted != 0
|
||||
out = append(out, run)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (a *AutomationRules) DeferTask(ctx context.Context, task DeferredAutomationTask) error {
|
||||
_, err := a.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 (?,?,?,?,?,'pending',0,0,'')`+dialectUpsert(a.Dialect, []string{"task_key"}, map[string]string{
|
||||
"cookie_id": "excluded.cookie_id",
|
||||
"trigger_type": "excluded.trigger_type",
|
||||
"task_json": "excluded.task_json",
|
||||
"due_at": "excluded.due_at",
|
||||
"status": "'pending'",
|
||||
"attempt_count": "0",
|
||||
"lease_expires_at": "0",
|
||||
"error_message": "''",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]AutomationRunIssue, []DeferredAutomationIssue, error) {
|
||||
runRows, err := a.DB.QueryContext(ctx, `SELECT ar.id,ar.cookie_id,ar.order_id,ar.trigger_type,ar.error_message,
|
||||
ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0)
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE c.user_id=? AND ar.status='needs_review' ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
runs := []AutomationRunIssue{}
|
||||
for runRows.Next() {
|
||||
var issue AutomationRunIssue
|
||||
var rawEventJSON string
|
||||
var actionStarted, ruleEnabled int
|
||||
if err := runRows.Scan(&issue.ID, &issue.CookieID, &issue.OrderID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.ActionCursor, &issue.SentCount, &issue.UpdatedAt, &rawEventJSON, &actionStarted, &ruleEnabled); err != nil {
|
||||
_ = runRows.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
issue.IssueKind, issue.AllowedResolutions = automationIssuePolicy(
|
||||
rawEventJSON, actionStarted != 0, ruleEnabled != 0, issue.SentCount, issue.ErrorMessage,
|
||||
)
|
||||
runs = append(runs, issue)
|
||||
}
|
||||
if err := runRows.Close(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
taskRows, err := a.DB.QueryContext(ctx, `SELECT apt.id,apt.cookie_id,apt.trigger_type,apt.error_message,
|
||||
apt.attempt_count,apt.updated_at
|
||||
FROM automation_pending_tasks apt JOIN cookies c ON c.id=apt.cookie_id
|
||||
WHERE c.user_id=? AND apt.status='dead_letter' ORDER BY apt.updated_at DESC,apt.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer taskRows.Close()
|
||||
tasks := []DeferredAutomationIssue{}
|
||||
for taskRows.Next() {
|
||||
var issue DeferredAutomationIssue
|
||||
if err := taskRows.Scan(&issue.ID, &issue.CookieID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.AttemptCount, &issue.UpdatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tasks = append(tasks, issue)
|
||||
}
|
||||
return runs, tasks, taskRows.Err()
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error {
|
||||
var rawEventJSON, errorMessage string
|
||||
var actionStarted, ruleEnabled, sentCount int
|
||||
err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=?`, runID, userID).
|
||||
Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, allowed := automationIssuePolicy(rawEventJSON, actionStarted != 0, ruleEnabled != 0, sentCount, errorMessage)
|
||||
if !containsString(allowed, resolution) {
|
||||
return fmt.Errorf("当前异常不允许使用 %s 处理", resolution)
|
||||
}
|
||||
var set string
|
||||
switch resolution {
|
||||
case "continue":
|
||||
set = "status='running',action_cursor=action_cursor+1,action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "retry":
|
||||
set = "status='running',action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "cancel":
|
||||
set = "status='canceled',action_started=0,lease_expires_at=0,next_retry_at=0"
|
||||
default:
|
||||
return errors.New("不支持的人工处理方式")
|
||||
}
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET `+set+`,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='needs_review' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, runID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func automationIssuePolicy(rawEventJSON string, actionStarted, ruleEnabled bool, sentCount int, errorMessage string) (string, []string) {
|
||||
if actionStarted {
|
||||
// 外部接口没有可依赖的幂等键。结果未知时重放当前游标可能重复发卡、
|
||||
// 发消息或确认发货,因此后端也必须拒绝 retry,不能只依赖前端警告。
|
||||
return "external_result_unknown", []string{"continue", "cancel"}
|
||||
}
|
||||
var raw map[string]any
|
||||
if json.Unmarshal([]byte(rawEventJSON), &raw) != nil {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
accountID, _ := raw["AccountID"].(string)
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
accountID, _ = raw["account_id"].(string)
|
||||
}
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
if strings.Contains(errorMessage, "规则不存在或已停用") {
|
||||
if ruleEnabled {
|
||||
return "rule_unavailable", []string{"retry", "cancel"}
|
||||
}
|
||||
return "rule_unavailable", []string{"cancel"}
|
||||
}
|
||||
if sentCount > 0 {
|
||||
return "partial_failure", []string{"continue", "retry", "cancel"}
|
||||
}
|
||||
return "execution_failed", []string{"retry", "cancel"}
|
||||
}
|
||||
|
||||
func containsString(values []string, target string) bool {
|
||||
for _, value := range values {
|
||||
if value == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error {
|
||||
if retry {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='pending',attempt_count=0,due_at=0,lease_expires_at=0,error_message='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ClaimDueDeferredTasks(ctx context.Context, limit int) ([]DeferredAutomationTask, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
now := time.Now().UTC().Unix()
|
||||
rows, err := a.DB.QueryContext(ctx, `SELECT id,task_key,cookie_id,trigger_type,task_json,due_at,attempt_count
|
||||
FROM automation_pending_tasks
|
||||
WHERE ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?)) AND attempt_count<5
|
||||
ORDER BY due_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
candidates := []DeferredAutomationTask{}
|
||||
for rows.Next() {
|
||||
var task DeferredAutomationTask
|
||||
if err := rows.Scan(&task.ID, &task.TaskKey, &task.CookieID, &task.TriggerType, &task.TaskJSON, &task.DueAt, &task.ClaimVersion); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
candidates = append(candidates, task)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claimed := make([]DeferredAutomationTask, 0, len(candidates))
|
||||
for _, task := range candidates {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='running',attempt_count=attempt_count+1,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count<5 AND ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?))`, now+300, task.ID, now, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 1 {
|
||||
task.ClaimVersion++
|
||||
claimed = append(claimed, task)
|
||||
}
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
func (a *AutomationRules) FinishDeferredTask(ctx context.Context, id int64, claimVersion int, success bool, errMsg string) error {
|
||||
if success {
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status=CASE WHEN attempt_count>=5 THEN 'dead_letter' ELSE 'pending' END,
|
||||
due_at=?,lease_expires_at=0,error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(time.Minute).Unix(), errMsg, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) RenewDeferredTaskLease(ctx context.Context, id int64, claimVersion int, leaseExpiresAt int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, leaseExpiresAt, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
func requireDeferredTaskOwner(res sql.Result, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrDeferredTaskLeaseLost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkOrderEventTime 更新订单事件时间字段。字段名由调用方控制白名单。
|
||||
func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field string) error {
|
||||
switch field {
|
||||
@@ -297,7 +808,7 @@ func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field
|
||||
default:
|
||||
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
|
||||
}
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE order_id=?", orderID)
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CASE WHEN COALESCE("+field+",'')='' THEN CURRENT_TIMESTAMP ELSE "+field+" END, updated_at=CURRENT_TIMESTAMP WHERE order_id=?", orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -314,21 +825,37 @@ UPDATE orders
|
||||
|
||||
// DueReviewRequestOrders 返回到期但尚未评价的订单。调度器会再按规则配置做精确判断。
|
||||
func (a *AutomationRules) DueReviewRequestOrders(ctx context.Context, limit int) ([]Order, error) {
|
||||
return a.DueReviewRequestOrdersAfter(ctx, "", limit)
|
||||
}
|
||||
|
||||
// DueReviewRequestOrdersAfter 用不可变的订单 ID 作为稳定游标分页扫描,避免固定 LIMIT
|
||||
// 让旧订单饿死后续订单。不能使用 updated_at:执行求评价动作本身会修改该字段。
|
||||
func (a *AutomationRules) DueReviewRequestOrdersAfter(ctx context.Context, afterOrderID string, limit int) ([]Order, error) {
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
cursorSQL := ""
|
||||
args := []any{}
|
||||
if afterOrderID != "" {
|
||||
cursorSQL = " AND o.order_id>?"
|
||||
args = append(args, afterOrderID)
|
||||
}
|
||||
args = append(args, limit)
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_status,cookie_id,is_bargain,
|
||||
receiver_name,receiver_phone,receiver_address,receiver_city,version,chat_id,system_shipped,
|
||||
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
|
||||
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
|
||||
created_at,updated_at
|
||||
FROM orders
|
||||
WHERE system_shipped=1
|
||||
AND COALESCE(buyer_reviewed_at,'')=''
|
||||
AND COALESCE(chat_id,'')<>''
|
||||
ORDER BY updated_at ASC
|
||||
LIMIT ?`, limit)
|
||||
FROM orders o
|
||||
WHERE o.system_shipped=1
|
||||
AND COALESCE(o.buyer_reviewed_at,'')=''
|
||||
AND COALESCE(o.chat_id,'')<>''
|
||||
AND EXISTS (SELECT 1 FROM automation_rules r
|
||||
WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout'
|
||||
AND r.enabled=1 AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
|
||||
ORDER BY o.order_id ASC
|
||||
LIMIT ?`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- automation.go ---
|
||||
@@ -117,13 +119,17 @@ func TestAutomation_MatchPriority(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Match: %v", err)
|
||||
}
|
||||
if len(matched) != 2 {
|
||||
t.Fatalf("Match len=%d want 2(商品级 + 账号级,禁用不匹配)", len(matched))
|
||||
if len(matched) != 1 {
|
||||
t.Fatalf("Match len=%d want 1(商品级存在时不叠加账号级)", len(matched))
|
||||
}
|
||||
// 商品级规则应排第一(CASE WHEN item_id=? THEN 0 ELSE 1 END)。
|
||||
if matched[0].ID != itemRuleID {
|
||||
t.Fatalf("Match 顺序: first id=%d want item rule %d", matched[0].ID, itemRuleID)
|
||||
}
|
||||
fallback, err := s.Automation.Match(ctx, cid, "other-item", "paid")
|
||||
if err != nil || len(fallback) != 1 || fallback[0].ItemID != "" {
|
||||
t.Fatalf("无商品级规则时应回退账号级: %#v err=%v", fallback, err)
|
||||
}
|
||||
|
||||
// 不匹配的 trigger_type → 空。
|
||||
none, err := s.Automation.Match(ctx, cid, "i1", "shipped")
|
||||
@@ -132,6 +138,24 @@ func TestAutomation_MatchPriority(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationMatchReturnsOnlyHighestPriorityRule(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
first, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "i1", "paid", true, 50))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "i1", "paid", true, 100)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
matched, err := s.Automation.Match(ctx, cid, "i1", "paid")
|
||||
if err != nil || len(matched) != 1 || matched[0].ID != first {
|
||||
t.Fatalf("matched=%+v err=%v", matched, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomation_UpdateDelete Update 替换动作 + Delete 路径。
|
||||
func TestAutomation_UpdateDelete(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
@@ -205,6 +229,17 @@ func TestAutomation_MarkOrderEventTime(t *testing.T) {
|
||||
t.Fatalf("MarkOrderEventTime(%s): %v", f, err)
|
||||
}
|
||||
}
|
||||
const originalPaidAt = "2020-01-02 03:04:05"
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE orders SET paid_at=? WHERE order_id='o1'`, originalPaidAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, "o1", "paid_at"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var paidAt string
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT paid_at FROM orders WHERE order_id='o1'`).Scan(&paidAt); err != nil || paidAt != originalPaidAt {
|
||||
t.Fatalf("event timestamp overwritten: %q err=%v", paidAt, err)
|
||||
}
|
||||
// 非法字段拒绝。
|
||||
err := s.Automation.MarkOrderEventTime(ctx, "o1", "order_status")
|
||||
if err == nil || !strings.Contains(err.Error(), "不允许") {
|
||||
@@ -221,7 +256,11 @@ func TestAutomation_ReviewRequest(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
uid, cid := seedAccount(t, s)
|
||||
if _, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "", "review_missing_timeout", true, 100,
|
||||
AutomationActionInput{ActionType: "send_text", MessageTemplate: "review", Enabled: true})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 建一条已发货、有 chat_id、未评价的订单 → 应被 DueReviewRequestOrders 取到。
|
||||
s.Orders.Upsert(ctx, "o1", OrderUpsertOpts{
|
||||
@@ -315,11 +354,118 @@ func TestAutomation_TryStartRunAndFinishRun(t *testing.T) {
|
||||
t.Fatalf("TryStartRun: id=%d started=%v err=%v", id, started, err)
|
||||
}
|
||||
// FinishRun。
|
||||
if err := s.Automation.FinishRun(ctx, id, "done", 1, ""); err != nil {
|
||||
if err := s.Automation.FinishRun(ctx, id, 1, "done", 1, ""); err != nil {
|
||||
t.Fatalf("FinishRun: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomation_TryStartRunRecoversStaleAndUnsentFailedRuns(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, _ := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "i1", "paid", true, 100))
|
||||
run := AutomationRun{
|
||||
RuleID: ruleID, CookieID: cid, ItemID: "i1", OrderID: "o-retry",
|
||||
TriggerType: "paid", TriggerKey: "paid:o-retry",
|
||||
}
|
||||
id, started, err := s.Automation.TryStartRun(ctx, run)
|
||||
if err != nil || !started {
|
||||
t.Fatalf("first start: id=%d started=%v err=%v", id, started, err)
|
||||
}
|
||||
if _, started, err = s.Automation.TryStartRun(ctx, run); err != nil || started {
|
||||
t.Fatalf("active lease must deduplicate: started=%v err=%v", started, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recoveredID, started, err := s.Automation.TryStartRun(ctx, run)
|
||||
if err != nil || !started || recoveredID != id {
|
||||
t.Fatalf("legacy/stale running row should recover: id=%d started=%v err=%v", recoveredID, started, err)
|
||||
}
|
||||
recoveredRun, err := s.Automation.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.FinishRun(ctx, id, recoveredRun.AttemptCount, "failed", 0, "temporary"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, started, err = s.Automation.TryStartRun(ctx, run); err != nil || started {
|
||||
t.Fatalf("failed run must honor retry delay: started=%v err=%v", started, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE id=?`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, started, err = s.Automation.TryStartRun(ctx, run); err != nil || !started {
|
||||
t.Fatalf("unsent failed run should retry: started=%v err=%v", started, err)
|
||||
}
|
||||
retriedRun, err := s.Automation.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.FinishRun(ctx, id, retriedRun.AttemptCount, "failed", 1, "partial"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, started, err = s.Automation.TryStartRun(ctx, run); err != nil || started {
|
||||
t.Fatalf("partially sent run must never retry automatically: started=%v err=%v", started, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "i1", "paid", true, 100,
|
||||
AutomationActionInput{ActionType: "send_text", MessageTemplate: "x", Enabled: true}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
|
||||
RuleID: ruleID, CookieID: cid, TriggerType: "paid", TriggerKey: "attempt-fence", LeaseExpiresAt: 1,
|
||||
})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start=%v err=%v", started, err)
|
||||
}
|
||||
stale, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil || stale.AttemptCount != 1 {
|
||||
t.Fatalf("stale run=%+v err=%v", stale, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, time.Now().UTC().Add(time.Minute).Unix())
|
||||
if err != nil || !claimed {
|
||||
t.Fatalf("claim recovery=%v err=%v", claimed, err)
|
||||
}
|
||||
current, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil || current.AttemptCount != 2 {
|
||||
t.Fatalf("current run=%+v err=%v", current, err)
|
||||
}
|
||||
if ok, err := s.Automation.StartRunAction(ctx, runID, stale.AttemptCount, 0, time.Now().Add(time.Minute).Unix()); err != nil || ok {
|
||||
t.Fatalf("stale worker must not start action: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if ok, err := s.Automation.StartRunAction(ctx, runID, current.AttemptCount, 0, time.Now().Add(time.Minute).Unix()); err != nil || !ok {
|
||||
t.Fatalf("current worker start: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if err := s.Automation.FinishRun(ctx, runID, stale.AttemptCount, "failed", 0, "stale"); !errors.Is(err, ErrAutomationRunLeaseLost) {
|
||||
t.Fatalf("stale finish err=%v", err)
|
||||
}
|
||||
if err := s.Automation.QuarantineRun(ctx, runID, stale.AttemptCount, "stale"); !errors.Is(err, ErrAutomationRunLeaseLost) {
|
||||
t.Fatalf("stale quarantine err=%v", err)
|
||||
}
|
||||
afterStale, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil || afterStale.Status != "running" || !afterStale.ActionStarted || afterStale.AttemptCount != current.AttemptCount {
|
||||
t.Fatalf("stale worker changed current run: %+v err=%v", afterStale, err)
|
||||
}
|
||||
if err := s.Automation.AdvanceRunAction(ctx, runID, current.AttemptCount, 0, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.FinishRun(ctx, runID, current.AttemptCount, "success", 1, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidJSON validJSON 的非法 JSON 兜底为 {}。
|
||||
func TestValidJSON(t *testing.T) {
|
||||
if got := validJSON(""); got != "{}" {
|
||||
@@ -333,6 +479,193 @@ func TestValidJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationIssuesCanBeListedAndResolved(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "", "buyer_reviewed", true, 100,
|
||||
AutomationActionInput{ActionType: "send_text", MessageTemplate: "x", Enabled: true}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid, OrderID: "issue-order",
|
||||
TriggerType: "buyer_reviewed", TriggerKey: "issue-key", RawEventJSON: `{}`, LeaseExpiresAt: 1})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start=%v err=%v", started, err)
|
||||
}
|
||||
if ok, err := s.Automation.StartRunAction(ctx, runID, 1, 0, 1); err != nil || !ok {
|
||||
t.Fatalf("action start=%v err=%v", ok, err)
|
||||
}
|
||||
if err := s.Automation.QuarantineRunResult(ctx, runID, 1, 1, "unknown"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "dead", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = s.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET status='dead_letter',attempt_count=5,error_message='bad' WHERE task_key='dead'`)
|
||||
runs, tasks, err := s.Automation.ListIssues(ctx, uid)
|
||||
if err != nil || len(runs) != 1 || len(tasks) != 1 {
|
||||
t.Fatalf("runs=%+v tasks=%+v err=%v", runs, tasks, err)
|
||||
}
|
||||
if runs[0].IssueKind != "external_result_unknown" || !containsString(runs[0].AllowedResolutions, "continue") {
|
||||
t.Fatalf("unexpected issue policy: %+v", runs[0])
|
||||
}
|
||||
if containsString(runs[0].AllowedResolutions, "retry") {
|
||||
t.Fatalf("unknown external result must not allow retry: %+v", runs[0])
|
||||
}
|
||||
if err := s.Automation.ResolveRunIssue(ctx, uid, runID, "retry"); err == nil {
|
||||
t.Fatal("unknown external result must reject retry")
|
||||
}
|
||||
if err := s.Automation.ResolveRunIssue(ctx, uid, runID, "continue"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ := s.Automation.GetRun(ctx, runID)
|
||||
if run.Status != "running" || run.ActionStarted || run.ActionCursor != 1 {
|
||||
t.Fatalf("resolved run=%+v", run)
|
||||
}
|
||||
if err := s.Automation.PostponeRecoveryRun(ctx, runID, 4102444800); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
|
||||
if err != nil || len(due) != 0 {
|
||||
t.Fatalf("postponed run must leave the due queue: %+v err=%v", due, err)
|
||||
}
|
||||
if err := s.Automation.ResolveDeferredIssue(ctx, uid, tasks[0].ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var status string
|
||||
var attempts int
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT status,attempt_count FROM automation_pending_tasks WHERE id=?`, tasks[0].ID).Scan(&status, &attempts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "pending" || attempts != 0 {
|
||||
t.Fatalf("status=%s attempts=%d", status, attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidAutomationSnapshotCanOnlyBeCanceled(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, err := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "", "buyer_reviewed", true, 100,
|
||||
AutomationActionInput{ActionType: "send_text", MessageTemplate: "x", Enabled: true}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid,
|
||||
TriggerType: "buyer_reviewed", TriggerKey: "invalid-snapshot", RawEventJSON: `{}`, LeaseExpiresAt: 1})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start=%v err=%v", started, err)
|
||||
}
|
||||
if err := s.Automation.QuarantineRun(ctx, runID, 1, "历史运行数据无法安全解析,已移入人工检查"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, _, err := s.Automation.ListIssues(ctx, uid)
|
||||
if err != nil || len(runs) != 1 {
|
||||
t.Fatalf("runs=%+v err=%v", runs, err)
|
||||
}
|
||||
if runs[0].IssueKind != "invalid_snapshot" || len(runs[0].AllowedResolutions) != 1 || runs[0].AllowedResolutions[0] != "cancel" {
|
||||
t.Fatalf("policy=%+v", runs[0])
|
||||
}
|
||||
if err := s.Automation.ResolveRunIssue(ctx, uid, runID, "retry"); err == nil {
|
||||
t.Fatal("invalid snapshot must reject retry")
|
||||
}
|
||||
run, _ := s.Automation.GetRun(ctx, runID)
|
||||
if run.Status != "needs_review" {
|
||||
t.Fatalf("rejected resolution changed run: %+v", run)
|
||||
}
|
||||
if err := s.Automation.ResolveRunIssue(ctx, uid, runID, "cancel"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationIssuePolicyForDisabledRuleRequiresReenableBeforeRetry(t *testing.T) {
|
||||
rawBytes, err := json.Marshal(struct{ AccountID string }{AccountID: "acc1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := string(rawBytes)
|
||||
kind, allowed := automationIssuePolicy(raw, false, false, 0, "自动化规则不存在或已停用,无法恢复")
|
||||
if kind != "rule_unavailable" || containsString(allowed, "retry") || !containsString(allowed, "cancel") {
|
||||
t.Fatalf("disabled policy kind=%q allowed=%v", kind, allowed)
|
||||
}
|
||||
kind, allowed = automationIssuePolicy(raw, false, true, 0, "自动化规则不存在或已停用,无法恢复")
|
||||
if kind != "rule_unavailable" || !containsString(allowed, "retry") || containsString(allowed, "continue") {
|
||||
t.Fatalf("reenabled policy kind=%q allowed=%v", kind, allowed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferTaskRevivesDeadLetterWithFreshAttemptBudget(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
task := DeferredAutomationTask{TaskKey: "same", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{"v":1}`, DueAt: 0}
|
||||
if err := s.Automation.DeferTask(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = s.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET status='dead_letter',attempt_count=5 WHERE task_key='same'`)
|
||||
task.TaskJSON = `{"v":2}`
|
||||
if err := s.Automation.DeferTask(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimDueDeferredTasks(ctx, 10)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claimed=%+v err=%v", claimed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredTaskFencingRejectsStaleWorker(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{
|
||||
TaskKey: "fenced-task", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: 0,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(first) != 1 {
|
||||
t.Fatalf("first claim=%+v err=%v", first, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET lease_expires_at=0 WHERE id=?`, first[0].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(second) != 1 {
|
||||
t.Fatalf("second claim=%+v err=%v", second, err)
|
||||
}
|
||||
if second[0].ClaimVersion <= first[0].ClaimVersion {
|
||||
t.Fatalf("claim versions first=%d second=%d", first[0].ClaimVersion, second[0].ClaimVersion)
|
||||
}
|
||||
if err := s.Automation.FinishDeferredTask(ctx, first[0].ID, first[0].ClaimVersion, true, ""); !errors.Is(err, ErrDeferredTaskLeaseLost) {
|
||||
t.Fatalf("stale finish err=%v want ErrDeferredTaskLeaseLost", err)
|
||||
}
|
||||
if err := s.Automation.RenewDeferredTaskLease(ctx, second[0].ID, second[0].ClaimVersion, time.Now().Add(time.Minute).Unix()); err != nil {
|
||||
t.Fatalf("current renew: %v", err)
|
||||
}
|
||||
if err := s.Automation.FinishDeferredTask(ctx, second[0].ID, second[0].ClaimVersion, true, ""); err != nil {
|
||||
t.Fatalf("current finish: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRuleDeleteRejectsActiveRun(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, _ := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "", "buyer_reviewed", true, 100,
|
||||
AutomationActionInput{ActionType: "send_text", MessageTemplate: "x", Enabled: true}))
|
||||
_, _, _ = s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid, TriggerType: "buyer_reviewed",
|
||||
TriggerKey: "active", RawEventJSON: `{}`, LeaseExpiresAt: 1})
|
||||
if err := s.Automation.Delete(ctx, uid, ruleID); !errors.Is(err, ErrAutomationRunActive) {
|
||||
t.Fatalf("delete err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNullInt64 nullInt64 的 <=0 → nil。
|
||||
func TestNullInt64(t *testing.T) {
|
||||
if nullInt64(0) != nil {
|
||||
|
||||
+336
-43
@@ -5,64 +5,290 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const DisableReasonManual = "manual"
|
||||
|
||||
// ErrAlreadyExists 表示创建资源时主键已经存在。调用方不得把它解释为可覆盖。
|
||||
var ErrAlreadyExists = errors.New("记录已存在")
|
||||
|
||||
// Cookies 闲鱼账号(cookie)相关操作。
|
||||
type Cookies struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Save 保存/更新 cookie。user_id 为 0 时:复用现有记录的 user_id,若无则报错
|
||||
// 系统未初始化时不兜底到默认用户。
|
||||
// AccountSettingsUpdate 表示账号编辑弹窗的一次原子保存。nil 字段保持原值;
|
||||
// ChannelIDs 非 nil 时覆盖通知绑定(空切片表示明确解绑全部)。
|
||||
type AccountSettingsUpdate struct {
|
||||
UserID int64
|
||||
Value *string
|
||||
Remark *string
|
||||
AutoConfirm *bool
|
||||
PauseDuration *int
|
||||
Username *string
|
||||
Password *string
|
||||
ShowBrowser *bool
|
||||
ChannelIDs *[]int64
|
||||
}
|
||||
|
||||
// UpdateSettings 在一个事务中更新账号字段及通知绑定,避免前端并行请求只成功一部分。
|
||||
func (c *Cookies) UpdateSettings(ctx context.Context, cookieID string, input AccountSettingsUpdate) (int64, error) {
|
||||
tx, err := c.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var ownerID int64
|
||||
if err := tx.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&ownerID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if ownerID != input.UserID {
|
||||
return 0, ErrForbidden
|
||||
}
|
||||
|
||||
assignments := make([]string, 0, 8)
|
||||
args := make([]any, 0, 9)
|
||||
if input.Value != nil {
|
||||
encrypted, err := c.codec.encrypt("cookie", cookieID, *input.Value)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
assignments = append(assignments, "value=?")
|
||||
args = append(args, encrypted)
|
||||
}
|
||||
if input.Remark != nil {
|
||||
assignments = append(assignments, "remark=?")
|
||||
args = append(args, *input.Remark)
|
||||
}
|
||||
if input.AutoConfirm != nil {
|
||||
assignments = append(assignments, "auto_confirm=?")
|
||||
args = append(args, boolToInt(*input.AutoConfirm))
|
||||
}
|
||||
pausedUntil := int64(0)
|
||||
if input.PauseDuration != nil {
|
||||
if *input.PauseDuration < 0 || *input.PauseDuration > 1440 {
|
||||
return 0, fmt.Errorf("暂停时长必须在 0 到 1440 分钟之间")
|
||||
}
|
||||
if *input.PauseDuration > 0 {
|
||||
pausedUntil = time.Now().UTC().Add(time.Duration(*input.PauseDuration) * time.Minute).Unix()
|
||||
}
|
||||
assignments = append(assignments, "pause_duration=?", "paused_until=?")
|
||||
args = append(args, *input.PauseDuration, pausedUntil)
|
||||
}
|
||||
if input.Username != nil {
|
||||
assignments = append(assignments, "username=?")
|
||||
args = append(args, *input.Username)
|
||||
}
|
||||
if input.Password != nil {
|
||||
encrypted, err := c.codec.encrypt("login-password", cookieID, *input.Password)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
assignments = append(assignments, "password=?")
|
||||
args = append(args, encrypted)
|
||||
}
|
||||
if input.ShowBrowser != nil {
|
||||
assignments = append(assignments, "show_browser=?")
|
||||
args = append(args, boolToInt(*input.ShowBrowser))
|
||||
}
|
||||
if len(assignments) > 0 {
|
||||
args = append(args, cookieID, input.UserID)
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cookies SET `+strings.Join(assignments, ",")+`,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`, args...); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if input.PauseDuration != nil && *input.PauseDuration == 0 {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0,updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND status='pending'`, cookieID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if input.ChannelIDs != nil {
|
||||
if len(*input.ChannelIDs) > 100 {
|
||||
return 0, fmt.Errorf("单个账号最多绑定 100 个通知渠道")
|
||||
}
|
||||
seen := make(map[int64]struct{}, len(*input.ChannelIDs))
|
||||
for _, channelID := range *input.ChannelIDs {
|
||||
if _, duplicate := seen[channelID]; duplicate {
|
||||
continue
|
||||
}
|
||||
seen[channelID] = struct{}{}
|
||||
var exists bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`, channelID, input.UserID).Scan(&exists); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !exists {
|
||||
return 0, ErrForbidden
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=?`, cookieID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for channelID := range seen {
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES (?,?,1)`, cookieID, channelID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pausedUntil, nil
|
||||
}
|
||||
|
||||
// CreateOwned 创建归属于 userID 的账号。冲突时绝不修改既有账号的 owner 或 cookie。
|
||||
func (c *Cookies) CreateOwned(ctx context.Context, cookieID, cookieValue string, userID int64) error {
|
||||
if cookieID == "" || userID <= 0 {
|
||||
return errors.New("账号 ID 和 user_id 不能为空")
|
||||
}
|
||||
encrypted, err := c.codec.encrypt("cookie", cookieID, cookieValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
dialectInsertIgnorePrefix(c.Dialect)+` INTO cookies (id, value, user_id, updated_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)`+dialectInsertIgnore(c.Dialect, []string{"id"}),
|
||||
cookieID, encrypted, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
|
||||
return rowsErr
|
||||
} else if n == 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var existingOwner int64
|
||||
if err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existingOwner); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("查询 cookie user_id: %w", err)
|
||||
}
|
||||
if existingOwner != userID {
|
||||
return ErrForbidden
|
||||
}
|
||||
return ErrAlreadyExists
|
||||
}
|
||||
|
||||
// UpdateValueOwned 只更新属于 userID 的既有账号,不能创建或转移账号归属。
|
||||
func (c *Cookies) UpdateValueOwned(ctx context.Context, cookieID, cookieValue string, userID int64) error {
|
||||
if cookieID == "" || userID <= 0 {
|
||||
return errors.New("账号 ID 和 user_id 不能为空")
|
||||
}
|
||||
encrypted, err := c.codec.encrypt("cookie", cookieID, cookieValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
|
||||
encrypted, cookieID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
|
||||
return rowsErr
|
||||
} else if n == 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var existingOwner int64
|
||||
if err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existingOwner); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("查询 cookie user_id: %w", err)
|
||||
}
|
||||
if existingOwner != userID {
|
||||
return ErrForbidden
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
// UpdateValueExisting 供续期和运行时写回使用,只能更新现存账号。
|
||||
// owner 由数据库中的记录决定;账号在任务期间被删除时返回 ErrNotFound,禁止复活。
|
||||
func (c *Cookies) UpdateValueExisting(ctx context.Context, cookieID, cookieValue string) error {
|
||||
if cookieID == "" {
|
||||
return errors.New("账号 ID 不能为空")
|
||||
}
|
||||
encrypted, err := c.codec.encrypt("cookie", cookieID, cookieValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, encrypted, cookieID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save 保留给历史调用和测试夹具使用。新业务代码应选择 CreateOwned、
|
||||
// UpdateValueOwned 或 UpdateValueExisting,避免把创建和后台写回混为一谈。
|
||||
func (c *Cookies) Save(ctx context.Context, cookieID, cookieValue string, userID int64) error {
|
||||
if userID != 0 {
|
||||
var existing int64
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existing)
|
||||
if err == nil && existing != userID {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("查询 cookie user_id: %w", err)
|
||||
}
|
||||
}
|
||||
if userID == 0 {
|
||||
var existing int64
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existing)
|
||||
if err == nil {
|
||||
userID = existing
|
||||
} else if errors.Is(err, sql.ErrNoRows) {
|
||||
return errors.New("系统未初始化:admin 用户不存在,请先执行 init-admin 初始化管理员")
|
||||
} else {
|
||||
return fmt.Errorf("查询 cookie user_id: %w", err)
|
||||
}
|
||||
return c.UpdateValueExisting(ctx, cookieID, cookieValue)
|
||||
}
|
||||
if err := c.UpdateValueOwned(ctx, cookieID, cookieValue, userID); err == nil {
|
||||
return nil
|
||||
} else if !errors.Is(err, ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
if err := c.CreateOwned(ctx, cookieID, cookieValue, userID); errors.Is(err, ErrAlreadyExists) {
|
||||
// 同一 owner 并发创建时,让最后一次写入拥有和历史 Save 相同的更新语义。
|
||||
return c.UpdateValueOwned(ctx, cookieID, cookieValue, userID)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
`INSERT INTO cookies (id, value, user_id, updated_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(c.Dialect, []string{"id"}, map[string]string{
|
||||
"value": "excluded.value",
|
||||
"user_id": "excluded.user_id",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cookieID, cookieValue, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete 删除 cookie 及其关联关键字(级联由外键处理,keywords 显式删以兼容未开外键的库)。
|
||||
// Delete 删除 cookie 及无法通过外键级联清理的关联数据。
|
||||
func (c *Cookies) Delete(ctx context.Context, cookieID string) error {
|
||||
tx, err := c.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := deleteCookieTx(ctx, tx, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// deleteCookieTx 清理一个账号的全部按 cookie_id 关联数据。这里同时处理历史上
|
||||
// 没有外键的表,确保账号 ID 被复用时不会继承前一个 owner 的数据。
|
||||
func deleteCookieTx(ctx context.Context, tx *sql.Tx, cookieID string) error {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM keywords WHERE cookie_id=?`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, table := range []string{
|
||||
"item_replay",
|
||||
"scheduled_cookies_refresh_log",
|
||||
"scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log",
|
||||
"account_login_logs",
|
||||
} {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE cookie_id=?`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM cookies WHERE id=?`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetValue 取 cookie 明文值。不存在返回 ErrNotFound。
|
||||
@@ -75,7 +301,7 @@ func (c *Cookies) GetValue(ctx context.Context, cookieID string) (string, error)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return v, nil
|
||||
return c.codec.decrypt("cookie", cookieID, v)
|
||||
}
|
||||
|
||||
// AllForUser 取某用户的所有 cookie(id→value)。userID 为 0 时取全部(管理员视图)。
|
||||
@@ -97,7 +323,11 @@ func (c *Cookies) AllForUser(ctx context.Context, userID int64) (map[string]stri
|
||||
if err := rows.Scan(&id, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[id] = v
|
||||
plain, err := c.codec.decrypt("cookie", id, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[id] = plain
|
||||
}
|
||||
return m, rows.Err()
|
||||
}
|
||||
@@ -108,13 +338,13 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
|
||||
var autoConfirm, showBrowser int
|
||||
var pauseDuration sql.NullInt64
|
||||
err := c.DB.QueryRowContext(ctx,
|
||||
`SELECT id, value, user_id, auto_confirm, COALESCE(remark,''), pause_duration,
|
||||
`SELECT id, value, user_id, auto_confirm, COALESCE(remark,''), pause_duration, COALESCE(paused_until,0),
|
||||
COALESCE(username,''), COALESCE(password,''),
|
||||
show_browser, COALESCE(nickname,''), COALESCE(avatar_url,''),
|
||||
COALESCE(metadata_json,''), COALESCE(last_refresh_at,0),
|
||||
COALESCE(login_method,''), COALESCE(last_login_at,0), created_at
|
||||
FROM cookies WHERE id=?`, cookieID).Scan(
|
||||
&d.ID, &d.Value, &d.UserID, &autoConfirm, &d.Remark, &pauseDuration,
|
||||
&d.ID, &d.Value, &d.UserID, &autoConfirm, &d.Remark, &pauseDuration, &d.PausedUntil,
|
||||
&d.Username, &d.Password, &showBrowser, &d.Nickname, &d.AvatarURL,
|
||||
&d.MetadataJSON, &d.LastRefreshAt, &d.LoginMethod, &d.LastLoginAt, &d.CreatedAt)
|
||||
if err != nil {
|
||||
@@ -130,6 +360,14 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
|
||||
// 0 是有效值,表示不暂停。
|
||||
d.PauseDuration = int(pauseDuration.Int64)
|
||||
}
|
||||
d.Value, err = c.codec.decrypt("cookie", d.ID, d.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Password, err = c.codec.decrypt("login-password", d.ID, d.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
@@ -139,11 +377,15 @@ func (c *Cookies) UpdateLoginInfo(ctx context.Context, cookieID, username, passw
|
||||
if showBrowser {
|
||||
v = 1
|
||||
}
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
encrypted, err := c.codec.encrypt("login-password", cookieID, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.DB.ExecContext(ctx,
|
||||
`UPDATE cookies
|
||||
SET username=?, password=?, show_browser=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`,
|
||||
username, password, v, cookieID)
|
||||
username, encrypted, v, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -177,6 +419,38 @@ func (c *Cookies) GetPauseDuration(ctx context.Context, cookieID string) int {
|
||||
return int(pd.Int64) // 0 有效
|
||||
}
|
||||
|
||||
// SetPause 设置账号暂停截止时间。minutes=0 立即取消暂停。
|
||||
func (c *Cookies) SetPause(ctx context.Context, cookieID string, minutes int) (int64, error) {
|
||||
if minutes < 0 || minutes > 1440 {
|
||||
return 0, fmt.Errorf("暂停时长必须在 0 到 1440 分钟之间")
|
||||
}
|
||||
pausedUntil := int64(0)
|
||||
if minutes > 0 {
|
||||
pausedUntil = time.Now().UTC().Add(time.Duration(minutes) * time.Minute).Unix()
|
||||
}
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cookies SET pause_duration=?,paused_until=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
minutes, pausedUntil, cookieID)
|
||||
if err == nil && minutes == 0 {
|
||||
// 用户主动恢复时无需等待原 paused_until;让持久化事件在下一轮调度立即可认领。
|
||||
_, err = c.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0,updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND status='pending'`, cookieID)
|
||||
}
|
||||
return pausedUntil, err
|
||||
}
|
||||
|
||||
// IsPaused 返回账号当前是否暂停以及暂停截止 Unix 秒。
|
||||
func (c *Cookies) IsPaused(ctx context.Context, cookieID string) (bool, int64, error) {
|
||||
var pausedUntil int64
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT COALESCE(paused_until,0) FROM cookies WHERE id=?`, cookieID).Scan(&pausedUntil)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, 0, ErrNotFound
|
||||
}
|
||||
return false, 0, err
|
||||
}
|
||||
return pausedUntil > time.Now().UTC().Unix(), pausedUntil, nil
|
||||
}
|
||||
|
||||
// GetAutoConfirm 读取账号是否自动将订单确认成已发货状态。
|
||||
func (c *Cookies) GetAutoConfirm(ctx context.Context, cookieID string) (bool, error) {
|
||||
var enabled int
|
||||
@@ -212,12 +486,31 @@ func (c *Cookies) SetStatusWithReason(ctx context.Context, cookieID string, enab
|
||||
return err
|
||||
}
|
||||
|
||||
// GetStatus 取启用状态,默认 true(出错或无记录时)。
|
||||
// GetStatus 取启用状态。无状态记录仍按启用处理;数据库错误则安全地按停用处理。
|
||||
func (c *Cookies) GetStatus(ctx context.Context, cookieID string) bool {
|
||||
enabled, err := c.Status(ctx, cookieID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return enabled
|
||||
}
|
||||
|
||||
// Status 返回账号启用状态;没有 cookie_status 记录时按启用处理,数据库错误不再静默放行。
|
||||
func (c *Cookies) Status(ctx context.Context, cookieID string) (bool, error) {
|
||||
var exists bool
|
||||
if err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cookies WHERE id=?)`, cookieID).Scan(&exists); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !exists {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
var enabled int
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT enabled FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled)
|
||||
if err != nil {
|
||||
return true
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return true, nil
|
||||
}
|
||||
return enabled != 0
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return enabled != 0, nil
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCreateOwnedConcurrentUsersNeverTransfersOwner(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "owner-a", "owner-a@example.com", "pw"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Users.Create(ctx, "owner-b", "owner-b@example.com", "pw"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, _ := store.Users.GetByUsername(ctx, "owner-a")
|
||||
b, _ := store.Users.GetByUsername(ctx, "owner-b")
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for _, input := range []struct {
|
||||
userID int64
|
||||
value string
|
||||
}{{a.ID, "cookie-a"}, {b.ID, "cookie-b"}} {
|
||||
input := input
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
results <- store.Cookies.CreateOwned(ctx, "shared-account", input.value, input.userID)
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
successes := 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
successes++
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, ErrForbidden) && !errors.Is(err, ErrAlreadyExists) {
|
||||
t.Fatalf("unexpected create error: %v", err)
|
||||
}
|
||||
}
|
||||
if successes != 1 {
|
||||
t.Fatalf("successful creates=%d want 1", successes)
|
||||
}
|
||||
var owner int64
|
||||
var value string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT user_id,value FROM cookies WHERE id=?`, "shared-account").Scan(&owner, &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if owner == a.ID && value != "cookie-a" {
|
||||
t.Fatalf("owner A received other user's cookie: %q", value)
|
||||
}
|
||||
if owner == b.ID && value != "cookie-b" {
|
||||
t.Fatalf("owner B received other user's cookie: %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateValueExistingCannotResurrectDeletedAccount(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "delete-race-owner", "delete-race-owner@example.com", "pw"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admin, _ := store.Users.GetByUsername(ctx, "delete-race-owner")
|
||||
if err := store.Cookies.CreateOwned(ctx, "deleted-account", "old", admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Cookies.Delete(ctx, "deleted-account"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Cookies.UpdateValueExisting(ctx, "deleted-account", "new"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("update deleted account err=%v want ErrNotFound", err)
|
||||
}
|
||||
var count int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM cookies WHERE id=?`, "deleted-account").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("deleted account resurrected: count=%d err=%v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteUserCleansNonForeignKeyAccountData(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "delete-owner", "delete-owner@example.com", "pw"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(ctx, "delete-owner")
|
||||
if err := store.Cookies.CreateOwned(ctx, "delete-owned-account", "cookie", owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, query := range []string{
|
||||
`INSERT INTO item_replay (item_id,cookie_id,reply_content) VALUES ('item','delete-owned-account','secret reply')`,
|
||||
`INSERT INTO scheduled_cookies_refresh_log (cookie_id,status) VALUES ('delete-owned-account','failed')`,
|
||||
`INSERT INTO scheduled_login_renew_log (cookie_id,status) VALUES ('delete-owned-account','failed')`,
|
||||
`INSERT INTO scheduled_api_cookie_renew_log (cookie_id,status) VALUES ('delete-owned-account','failed')`,
|
||||
`INSERT INTO account_login_logs (cookie_id,user_id,method,status,created_at) VALUES ('delete-owned-account',0,'password','failed',1)`,
|
||||
} {
|
||||
if _, err := store.DB.ExecContext(ctx, query); err != nil {
|
||||
t.Fatalf("seed orphan candidate: %v", err)
|
||||
}
|
||||
}
|
||||
if err := store.Users.Delete(ctx, owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, table := range []string{
|
||||
"cookies", "item_replay", "scheduled_cookies_refresh_log", "scheduled_login_renew_log",
|
||||
"scheduled_api_cookie_renew_log", "account_login_logs",
|
||||
} {
|
||||
var count int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM `+table+` WHERE cookie_id=?`, "delete-owned-account").Scan(&count); err != nil {
|
||||
if table == "cookies" {
|
||||
err = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM cookies WHERE id=?`, "delete-owned-account").Scan(&count)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("count %s: %v", table, err)
|
||||
}
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("%s retained %d rows", table, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdateAccountSettingsIsAtomic(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
for _, user := range []struct{ name, email string }{{"settings-owner", "settings-owner@example.com"}, {"settings-other", "settings-other@example.com"}} {
|
||||
if ok, err := store.Users.Create(ctx, user.name, user.email, "pw"); err != nil || !ok {
|
||||
t.Fatalf("create %s: ok=%v err=%v", user.name, ok, err)
|
||||
}
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(ctx, "settings-owner")
|
||||
other, _ := store.Users.GetByUsername(ctx, "settings-other")
|
||||
if err := store.Cookies.CreateOwned(ctx, "settings-cookie", "old-cookie", owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channelResult, err := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,1,?)`, "other", "webhook", `{}`, other.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherChannelID, _ := channelResult.LastInsertId()
|
||||
newCookie, remark := "new-cookie", "new remark"
|
||||
autoConfirm := false
|
||||
badChannels := []int64{otherChannelID}
|
||||
_, err = store.Cookies.UpdateSettings(ctx, "settings-cookie", AccountSettingsUpdate{
|
||||
UserID: owner.ID, Value: &newCookie, Remark: &remark, AutoConfirm: &autoConfirm, ChannelIDs: &badChannels,
|
||||
})
|
||||
if !errors.Is(err, ErrForbidden) {
|
||||
t.Fatalf("expected forbidden channel, got %v", err)
|
||||
}
|
||||
detail, _ := store.Cookies.GetDetails(ctx, "settings-cookie")
|
||||
if detail.Value != "old-cookie" || detail.Remark != "" || !detail.AutoConfirm {
|
||||
t.Fatalf("failed aggregate update partially committed: %+v", detail)
|
||||
}
|
||||
|
||||
channelResult, err = store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,1,?)`, "owned", "webhook", `{}`, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ownedChannelID, _ := channelResult.LastInsertId()
|
||||
channels := []int64{ownedChannelID, ownedChannelID}
|
||||
pause := 5
|
||||
if _, err := store.Cookies.UpdateSettings(ctx, "settings-cookie", AccountSettingsUpdate{
|
||||
UserID: owner.ID, Value: &newCookie, Remark: &remark, AutoConfirm: &autoConfirm, PauseDuration: &pause, ChannelIDs: &channels,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, _ = store.Cookies.GetDetails(ctx, "settings-cookie")
|
||||
bindings, _ := store.Notifications.AccountBindings(ctx, "settings-cookie")
|
||||
if detail.Value != newCookie || detail.Remark != remark || detail.AutoConfirm || detail.PauseDuration != pause || detail.PausedUntil == 0 {
|
||||
t.Fatalf("aggregate settings not applied: %+v", detail)
|
||||
}
|
||||
if len(bindings) != 1 || bindings[0] != ownedChannelID {
|
||||
t.Fatalf("bindings=%v", bindings)
|
||||
}
|
||||
}
|
||||
+39
-17
@@ -18,9 +18,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
@@ -40,10 +40,10 @@ const (
|
||||
type driverName string
|
||||
|
||||
const (
|
||||
driverSQLite driverName = "sqlite"
|
||||
driverMySQL driverName = "mysql"
|
||||
driverSQLite driverName = "sqlite"
|
||||
driverMySQL driverName = "mysql"
|
||||
// driverPgx 走 pgx_compat driver(见 pgx_compat.go),把 ? 占位符重写成 $N。
|
||||
driverPgx driverName = pgxCompatDriverName
|
||||
driverPgx driverName = pgxCompatDriverName
|
||||
)
|
||||
|
||||
// Open 打开/创建数据库并执行迁移。dbURL 形如:
|
||||
@@ -109,12 +109,11 @@ func parseDBURL(raw string) (driverName, Dialect, string, error) {
|
||||
return driverMySQL, DialectMySQL, mysqlDSN(rest), nil
|
||||
case "postgres", "postgresql", "pgx":
|
||||
// pgx 接受完整 postgres:// URL;也接受 libpq key=value DSN。
|
||||
// 若是 URL 形式(含 @),保留 scheme 还原完整 URL;
|
||||
// 若是 key=value 形式(含 = 且不含 @),原样透传。
|
||||
if strings.Contains(rest, "@") {
|
||||
return driverPgx, DialectPostgres, scheme + "://" + rest, nil
|
||||
// 只有明确的 key=value 形式才去掉伪 scheme;URL 即便省略用户名也必须保留 scheme。
|
||||
if strings.Contains(rest, "=") && !strings.Contains(rest, "/") {
|
||||
return driverPgx, DialectPostgres, rest, nil
|
||||
}
|
||||
return driverPgx, DialectPostgres, rest, nil
|
||||
return driverPgx, DialectPostgres, scheme + "://" + rest, nil
|
||||
default:
|
||||
return "", "", "", fmt.Errorf("不支持的数据库 scheme: %s(支持 sqlite/mysql/postgres)", scheme)
|
||||
}
|
||||
@@ -125,17 +124,40 @@ func sqliteDSN(path string) string {
|
||||
return fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)", path)
|
||||
}
|
||||
|
||||
// mysqlDSN 确保 DSN 含 multiStatements=true(goose 多语句迁移需要,缺失会静默只执行首条语句)。
|
||||
// 已显式设置则不覆盖;其余参数原样保留。不强制 parseTime——本仓库时间列按 string/int64 扫描。
|
||||
// mysqlDSN 强制启用应用依赖的两个连接选项:
|
||||
// - multiStatements:goose 多语句迁移需要,缺失会静默只执行首条语句;
|
||||
// - clientFoundRows:RowsAffected 返回匹配行数,使“保存未变化内容”的语义与 SQLite/Postgres 一致。
|
||||
//
|
||||
// 其余参数原样保留。不强制 parseTime——本仓库时间列按 string/int64 扫描。
|
||||
func mysqlDSN(dsn string) string {
|
||||
if strings.Contains(dsn, "multiStatements=") {
|
||||
return dsn
|
||||
dsn = forceMySQLBoolParam(dsn, "multiStatements")
|
||||
return forceMySQLBoolParam(dsn, "clientFoundRows")
|
||||
}
|
||||
|
||||
func forceMySQLBoolParam(dsn, key string) string {
|
||||
base, rawQuery, hasQuery := strings.Cut(dsn, "?")
|
||||
parts := make([]string, 0, 4)
|
||||
found := false
|
||||
if hasQuery {
|
||||
for _, part := range strings.Split(rawQuery, "&") {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
name, _, _ := strings.Cut(part, "=")
|
||||
if name == key {
|
||||
if !found {
|
||||
parts = append(parts, key+"=true")
|
||||
found = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
parts = append(parts, part)
|
||||
}
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(dsn, "?") {
|
||||
sep = "&"
|
||||
if !found {
|
||||
parts = append(parts, key+"=true")
|
||||
}
|
||||
return dsn + sep + "multiStatements=true"
|
||||
return base + "?" + strings.Join(parts, "&")
|
||||
}
|
||||
|
||||
// Migrate 执行嵌入式 goose 迁移,按方言选择子目录。
|
||||
|
||||
+12
-10
@@ -21,8 +21,9 @@ func TestParseDBURL(t *testing.T) {
|
||||
{name: "sqlite path (no scheme)", url: "/tmp/x.db", driver: driverSQLite, dialect: DialectSQLite, dsnHas: "file:/tmp/x.db"},
|
||||
{name: "sqlite scheme", url: "sqlite://rel/path.db", driver: driverSQLite, dialect: DialectSQLite, dsnHas: "file:rel/path.db"},
|
||||
{name: "sqlite3 scheme", url: "sqlite3://x.db", driver: driverSQLite, dialect: DialectSQLite, dsnHas: "file:x.db"},
|
||||
{name: "mysql scheme", url: "mysql://user:pass@tcp(h:3306)/db", driver: driverMySQL, dialect: DialectMySQL, dsnHas: "multiStatements=true"},
|
||||
{name: "mysql scheme", url: "mysql://user:pass@tcp(h:3306)/db", driver: driverMySQL, dialect: DialectMySQL, dsnHas: "clientFoundRows=true"},
|
||||
{name: "postgres url scheme", url: "postgres://u:p@h:5432/db", driver: driverPgx, dialect: DialectPostgres, dsnHas: "postgres://u:p@h:5432/db"},
|
||||
{name: "postgres url without user", url: "postgres://localhost:5432/db?sslmode=disable", driver: driverPgx, dialect: DialectPostgres, dsnHas: "postgres://localhost:5432/db?sslmode=disable"},
|
||||
{name: "pgx alias", url: "pgx://u:p@h:5432/db", driver: driverPgx, dialect: DialectPostgres, dsnHas: "pgx://u:p@h:5432/db"},
|
||||
{name: "postgres kv dsn", url: "postgres://host=localhost port=5432", driver: driverPgx, dialect: DialectPostgres, dsnHas: "host=localhost"},
|
||||
{name: "postgresql alias", url: "postgresql://u:p@h:5432/db", driver: driverPgx, dialect: DialectPostgres, dsnHas: "postgresql://u:p@h:5432/db"},
|
||||
@@ -58,22 +59,23 @@ func TestParseDBURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMysqlDSN mysqlDSN 缺省 multiStatements 已存在则不覆盖。
|
||||
// TestMysqlDSN mysqlDSN 强制启用迁移和匹配行计数所需参数。
|
||||
func TestMysqlDSN(t *testing.T) {
|
||||
// 无 query → 追加 ?multiStatements=true。
|
||||
// 无 query → 追加两个参数。
|
||||
got := mysqlDSN("u:p@tcp(h:3306)/db")
|
||||
if !strings.Contains(got, "multiStatements=true") || !strings.HasPrefix(got, "u:p@tcp(h:3306)/db?") {
|
||||
if !strings.Contains(got, "multiStatements=true") || !strings.Contains(got, "clientFoundRows=true") || !strings.HasPrefix(got, "u:p@tcp(h:3306)/db?") {
|
||||
t.Fatalf("无 query: %q", got)
|
||||
}
|
||||
// 已有 query → 用 & 拼接。
|
||||
// 已有 query → 保留原参数。
|
||||
got = mysqlDSN("u:p@tcp(h:3306)/db?parseTime=true")
|
||||
if !strings.Contains(got, "&multiStatements=true") {
|
||||
if !strings.Contains(got, "parseTime=true") || !strings.Contains(got, "multiStatements=true") || !strings.Contains(got, "clientFoundRows=true") {
|
||||
t.Fatalf("已有 query: %q", got)
|
||||
}
|
||||
// 已显式含 multiStatements → 不重复追加。
|
||||
got = mysqlDSN("u:p@tcp(h:3306)/db?multiStatements=true")
|
||||
if strings.Count(got, "multiStatements=") != 1 {
|
||||
t.Fatalf("重复追加: %q", got)
|
||||
// 即使调用方显式关闭也要覆盖,否则 no-op UPDATE 会被误判为不存在。
|
||||
got = mysqlDSN("u:p@tcp(h:3306)/db?multiStatements=false&clientFoundRows=false&loc=UTC")
|
||||
if strings.Count(got, "multiStatements=") != 1 || strings.Count(got, "clientFoundRows=") != 1 ||
|
||||
strings.Contains(got, "multiStatements=false") || strings.Contains(got, "clientFoundRows=false") || !strings.Contains(got, "loc=UTC") {
|
||||
t.Fatalf("未正确强制参数: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+83
-48
@@ -98,44 +98,72 @@ type Cards struct {
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// ConsumeBatchData 消费一条批量数据卡券(data 类型),返回内容。
|
||||
// ConsumeBatchData 取 data_content 第一行,删除已消费行,发完置空。
|
||||
// ConsumeBatchData 原子预留一条批量数据卡券(data 类型),返回内容。
|
||||
// 通过快照条件更新处理并发追加/消费;调用方发送失败时应调用 RestoreBatchData。
|
||||
func (c *Cards) ConsumeBatchData(ctx context.Context, cardID int64) (string, error) {
|
||||
tx, err := c.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var dataContent sql.NullString
|
||||
err = tx.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&dataContent)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
for attempts := 0; attempts < 20; attempts++ {
|
||||
var dataContent sql.NullString
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&dataContent)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if !dataContent.Valid || dataContent.String == "" {
|
||||
return "", errors.New("卡券批量数据为空")
|
||||
}
|
||||
lines := splitLines(dataContent.String)
|
||||
if len(lines) == 0 {
|
||||
return "", errors.New("卡券批量数据无有效行")
|
||||
}
|
||||
remaining := ""
|
||||
if len(lines) > 1 {
|
||||
remaining = joinLines(lines[1:])
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET data_content=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND data_content=?`,
|
||||
remaining, cardID, dataContent.String)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if affected, err := res.RowsAffected(); err == nil && affected == 1 {
|
||||
return lines[0], nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if !dataContent.Valid || dataContent.String == "" {
|
||||
return "", errors.New("卡券批量数据为空")
|
||||
}
|
||||
return "", errors.New("卡券库存并发修改过于频繁,请稍后重试")
|
||||
}
|
||||
|
||||
// 按行分割,取第一行非空作为发货内容,其余回写。
|
||||
lines := splitLines(dataContent.String)
|
||||
if len(lines) == 0 {
|
||||
return "", errors.New("卡券批量数据无有效行")
|
||||
// RestoreBatchData 把发送失败的预留卡密放回库存头部。恢复失败时宁可进入人工处理,
|
||||
// 也不能把一个已成功发送但响应不确定的卡密自动重复发给下一位买家。
|
||||
func (c *Cards) RestoreBatchData(ctx context.Context, cardID int64, content string) error {
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" {
|
||||
return errors.New("恢复卡密内容为空")
|
||||
}
|
||||
content := lines[0]
|
||||
remaining := ""
|
||||
if len(lines) > 1 {
|
||||
remaining = joinLines(lines[1:])
|
||||
for attempts := 0; attempts < 20; attempts++ {
|
||||
var current sql.NullString
|
||||
if err := c.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(¤t); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
merged := content
|
||||
if current.Valid && strings.TrimSpace(current.String) != "" {
|
||||
merged += "\n" + current.String
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET data_content=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND COALESCE(data_content,'')=?`,
|
||||
merged, cardID, current.String)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, err := res.RowsAffected(); err == nil && affected == 1 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cards SET data_content=? WHERE id=?`, remaining, cardID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return content, nil
|
||||
return errors.New("恢复卡密时库存并发修改过于频繁")
|
||||
}
|
||||
|
||||
// FirstBatchData 返回 data 类型卡券当前第一条有效内容和原始快照。
|
||||
@@ -194,23 +222,30 @@ func (c *Cards) AppendBatchData(ctx context.Context, cardID int64, content strin
|
||||
if valid == 0 {
|
||||
return 0, errors.New("无有效卡密行")
|
||||
}
|
||||
var existing sql.NullString
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&existing)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrNotFound
|
||||
for attempts := 0; attempts < 20; attempts++ {
|
||||
var existing sql.NullString
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&existing)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
merged := content
|
||||
if existing.Valid && existing.String != "" {
|
||||
merged = existing.String + "\n" + content
|
||||
}
|
||||
res, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET data_content=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND COALESCE(data_content,'')=?`,
|
||||
merged, cardID, existing.String)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if affected, err := res.RowsAffected(); err == nil && affected == 1 {
|
||||
return valid, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
merged := content
|
||||
if existing.Valid && existing.String != "" {
|
||||
merged = existing.String + "\n" + content
|
||||
}
|
||||
if _, err := c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET data_content=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, merged, cardID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return valid, nil
|
||||
return 0, errors.New("追加卡密时库存并发修改过于频繁")
|
||||
}
|
||||
|
||||
// splitLines / joinLines 统一处理多行库存内容。
|
||||
@@ -236,7 +271,7 @@ func splitLines(s string) []string {
|
||||
// 过滤空行。
|
||||
res := out[:0]
|
||||
for _, l := range out {
|
||||
if l != "" {
|
||||
if strings.TrimSpace(l) != "" {
|
||||
res = append(res, l)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
// DialectUpsert 生成 UPSERT 子句,处理三种数据库的语法差异。
|
||||
//
|
||||
// SQLite/Postgres: ON CONFLICT (conflictCols) DO UPDATE SET col=expr, ...
|
||||
//
|
||||
// MySQL: ON DUPLICATE KEY UPDATE col=expr, ...
|
||||
//
|
||||
// updateAssignments 是 列名 -> SQL表达式 的映射。表达式里用 "EXCLUDED.col"
|
||||
|
||||
+122
-8
@@ -4,13 +4,14 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ---- 关键字 CRUD ----
|
||||
|
||||
// KeywordRow keywords 表完整行(含自增 id,用于按索引删除)。
|
||||
type KeywordRow struct {
|
||||
ID int64
|
||||
ID int64 `json:"id"`
|
||||
CookieID string
|
||||
Keyword string
|
||||
Reply string
|
||||
@@ -19,6 +20,35 @@ type KeywordRow struct {
|
||||
ImageURL string
|
||||
}
|
||||
|
||||
func (k *Keywords) UpdateByID(ctx context.Context, row KeywordRow) error {
|
||||
kwType := row.Type
|
||||
if kwType == "" {
|
||||
kwType = "text"
|
||||
}
|
||||
res, err := k.DB.ExecContext(ctx, `UPDATE keywords
|
||||
SET keyword=?,reply=?,item_id=?,type=?,image_url=?
|
||||
WHERE id=? AND cookie_id=?`,
|
||||
row.Keyword, row.Reply, nullable(row.ItemID), kwType, nullable(row.ImageURL), row.ID, row.CookieID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, err := res.RowsAffected(); err == nil && affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *Keywords) DeleteByID(ctx context.Context, cookieID string, id int64) error {
|
||||
res, err := k.DB.ExecContext(ctx, `DELETE FROM keywords WHERE id=? AND cookie_id=?`, id, cookieID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, err := res.RowsAffected(); err == nil && affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AllRows 取某账号所有关键字(含 id)。
|
||||
func (k *Keywords) AllRows(ctx context.Context, cookieID string) ([]KeywordRow, error) {
|
||||
rows, err := k.DB.QueryContext(ctx,
|
||||
@@ -175,6 +205,10 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &enabled, &c.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Config, err = n.codec.decrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
out = append(out, c)
|
||||
}
|
||||
@@ -183,16 +217,29 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([
|
||||
|
||||
// CreateChannel 创建通知渠道。
|
||||
func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) {
|
||||
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return insertReturningID(ctx, n.DB, n.Dialect,
|
||||
`INSERT INTO notification_channels (name, type, config, event_types, enabled, user_id) VALUES (?,?,?,?,?,?)`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.UserID)
|
||||
c.Name, c.Type, config, c.EventTypes, boolToInt(c.Enabled), c.UserID)
|
||||
}
|
||||
|
||||
// UpdateChannel 更新通知渠道。
|
||||
func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChannelRow) error {
|
||||
_, err := n.DB.ExecContext(ctx,
|
||||
if c.UserID == 0 {
|
||||
if err := n.DB.QueryRowContext(ctx, `SELECT COALESCE(user_id,1) FROM notification_channels WHERE id=?`, c.ID).Scan(&c.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID)
|
||||
c.Name, c.Type, config, c.EventTypes, boolToInt(c.Enabled), c.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -210,16 +257,25 @@ func (n *Notifications) GetChannelRowForUser(ctx context.Context, id, userID int
|
||||
return nil, err
|
||||
}
|
||||
c.Enabled = enabled != 0
|
||||
config, err := n.codec.decrypt("notification-config", strconv.FormatInt(c.UserID, 10), c.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Config = config
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpdateChannelForUser 更新指定用户拥有的通知渠道。
|
||||
func (n *Notifications) UpdateChannelForUser(ctx context.Context, c *NotificationChannelRow, userID int64) error {
|
||||
config, err := n.codec.encrypt("notification-config", strconv.FormatInt(userID, 10), c.Config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := n.DB.ExecContext(ctx,
|
||||
`UPDATE notification_channels
|
||||
SET name=?, type=?, config=?, event_types=?, enabled=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND user_id=?`,
|
||||
c.Name, c.Type, c.Config, c.EventTypes, boolToInt(c.Enabled), c.ID, userID)
|
||||
c.Name, c.Type, config, c.EventTypes, boolToInt(c.Enabled), c.ID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -252,14 +308,20 @@ func (n *Notifications) DeleteChannelForUser(ctx context.Context, id, userID int
|
||||
// GetChannel 按 ID 取单个通知渠道(含 config)。未找到返回 nil。
|
||||
func (n *Notifications) GetChannel(ctx context.Context, id int64) (*NotificationChannel, error) {
|
||||
row := n.DB.QueryRowContext(ctx,
|
||||
`SELECT id, name, type, config, COALESCE(event_types,'') FROM notification_channels WHERE id=?`, id)
|
||||
`SELECT id, name, type, config, COALESCE(event_types,''), COALESCE(user_id,1) FROM notification_channels WHERE id=?`, id)
|
||||
var c NotificationChannel
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes); err != nil {
|
||||
var userID int64
|
||||
if err := row.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &c.EventTypes, &userID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
config, err := n.codec.decrypt("notification-config", strconv.FormatInt(userID, 10), c.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Config = config
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
@@ -330,6 +392,7 @@ func (n *Notifications) SetBindings(ctx context.Context, cookieID string, channe
|
||||
type SystemSettings struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Get 取单项设置。
|
||||
@@ -343,6 +406,9 @@ func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) {
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if isSensitiveSettingKey(key) {
|
||||
return s.codec.decrypt("system-setting", key, v)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
@@ -360,6 +426,12 @@ func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) {
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isSensitiveSettingKey(k) {
|
||||
v, err = s.codec.decrypt("system-setting", k, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
m[k] = v
|
||||
}
|
||||
return m, rows.Err()
|
||||
@@ -367,6 +439,13 @@ func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) {
|
||||
|
||||
// Set 设置单项。
|
||||
func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
|
||||
if isSensitiveSettingKey(key) {
|
||||
encrypted, err := s.codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value = encrypted
|
||||
}
|
||||
keyCol := dialectQuote(s.Dialect, "key")
|
||||
_, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO system_settings (`+keyCol+`, value, updated_at) VALUES (?,?,CURRENT_TIMESTAMP)`+
|
||||
@@ -378,6 +457,33 @@ func (s *SystemSettings) Set(ctx context.Context, key, value string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// SetMany 在单个事务中原子保存多项设置。
|
||||
func (s *SystemSettings) SetMany(ctx context.Context, values map[string]string) error {
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
keyCol := dialectQuote(s.Dialect, "key")
|
||||
query := `INSERT INTO system_settings (` + keyCol + `, value, updated_at) VALUES (?,?,CURRENT_TIMESTAMP)` +
|
||||
dialectUpsert(s.Dialect, []string{keyCol}, map[string]string{
|
||||
"value": "EXCLUDED.value", "updated_at": "CURRENT_TIMESTAMP",
|
||||
})
|
||||
for key, value := range values {
|
||||
if isSensitiveSettingKey(key) {
|
||||
encrypted, err := s.codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value = encrypted
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, query, key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// PublicSystemKeys 是公开设置键白名单(前端登录页等无需登录可读)。
|
||||
var PublicSystemKeys = map[string]bool{
|
||||
"theme_color": true,
|
||||
@@ -464,6 +570,14 @@ func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
|
||||
|
||||
// UpsertBasic 插入或补全商品基础信息,不覆盖已有的多规格/多数量发货设置。
|
||||
func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, i.DB, r)
|
||||
}
|
||||
|
||||
func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, tx, r)
|
||||
}
|
||||
|
||||
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
|
||||
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
|
||||
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
|
||||
var conflictClause string
|
||||
@@ -485,7 +599,7 @@ func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error {
|
||||
item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END,
|
||||
updated_at=CURRENT_TIMESTAMP`
|
||||
}
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
_, err := execer.ExecContext(ctx,
|
||||
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
|
||||
item_category, item_price, item_detail, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+conflictClause,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- extras.go ---
|
||||
@@ -24,12 +25,18 @@ func TestKeywords_AllWithType(t *testing.T) {
|
||||
if _, err := s.Keywords.Add(ctx, cid, "图", "[img]", "item1", "image", "http://img"); err != nil {
|
||||
t.Fatalf("Add image: %v", err)
|
||||
}
|
||||
if _, err := s.Keywords.Add(ctx, cid, "你好呀", "更精确", "", "text", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kws, err := s.Keywords.AllWithType(ctx, cid)
|
||||
if err != nil {
|
||||
t.Fatalf("AllWithType: %v", err)
|
||||
}
|
||||
if len(kws) != 2 {
|
||||
t.Fatalf("len=%d want 2", len(kws))
|
||||
if len(kws) != 3 {
|
||||
t.Fatalf("len=%d want 3", len(kws))
|
||||
}
|
||||
if kws[0].Keyword != "你好呀" {
|
||||
t.Fatalf("longest keyword must win deterministically: %#v", kws)
|
||||
}
|
||||
// 验证默认 type=text 兜底(第一条)。
|
||||
var foundText, foundImage bool
|
||||
@@ -339,9 +346,9 @@ func TestCookies_DeleteAndStatuses(t *testing.T) {
|
||||
if !s.Cookies.GetStatus(ctx, cid) {
|
||||
t.Fatal("GetStatus 应 true")
|
||||
}
|
||||
// GetStatus 不存在记录 → 默认 true。
|
||||
if !s.Cookies.GetStatus(ctx, "no-such-cookie") {
|
||||
t.Fatal("不存在记录 GetStatus 应默认 true")
|
||||
// 不存在的账号和数据库错误都必须安全地按停用处理。
|
||||
if s.Cookies.GetStatus(ctx, "no-such-cookie") {
|
||||
t.Fatal("不存在账号 GetStatus 应返回 false")
|
||||
}
|
||||
|
||||
// UpdateProfile。
|
||||
@@ -359,13 +366,20 @@ func TestCookies_DeleteAndStatuses(t *testing.T) {
|
||||
t.Fatalf("AllForUser(0): %#v err=%v", all, err)
|
||||
}
|
||||
|
||||
// Delete cookie → 关联关键字也删(虽然这里没关键字,但走事务路径)。
|
||||
if _, err := s.DB.ExecContext(ctx, `INSERT INTO item_replay (item_id,cookie_id,reply_content) VALUES ('item-stale',?,'不应残留')`, cid); err != nil {
|
||||
t.Fatalf("seed item_replay: %v", err)
|
||||
}
|
||||
// Delete cookie → 无外键的 item_replay 也必须显式清理。
|
||||
if err := s.Cookies.Delete(ctx, cid); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if _, err := s.Cookies.GetValue(ctx, cid); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("Delete 后 GetValue 应 ErrNotFound, got %v", err)
|
||||
}
|
||||
var stale int
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM item_replay WHERE cookie_id=?`, cid).Scan(&stale); err != nil || stale != 0 {
|
||||
t.Fatalf("Delete 后 item_replay count=%d err=%v", stale, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookies_SaveReuseUserID Save 在 userID=0 且 cookie 已存在时复用 user_id。
|
||||
@@ -411,3 +425,39 @@ func TestCookies_GetPauseDurationExplicit(t *testing.T) {
|
||||
t.Fatalf("GetPauseDuration 不存在=%d want 10", pd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookies_SetPauseAndAutomaticExpiry(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
|
||||
pausedUntil, err := s.Cookies.SetPause(ctx, cid, 15)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paused, storedUntil, err := s.Cookies.IsPaused(ctx, cid)
|
||||
if err != nil || !paused || storedUntil != pausedUntil || pausedUntil <= time.Now().UTC().Unix() {
|
||||
t.Fatalf("pause state: paused=%v until=%d stored=%d err=%v", paused, pausedUntil, storedUntil, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE cookies SET paused_until=? WHERE id=?`, time.Now().UTC().Add(-time.Second).Unix(), cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if paused, _, err = s.Cookies.IsPaused(ctx, cid); err != nil || paused {
|
||||
t.Fatalf("expired pause must be inactive: paused=%v err=%v", paused, err)
|
||||
}
|
||||
if until, err := s.Cookies.SetPause(ctx, cid, 0); err != nil || until != 0 {
|
||||
t.Fatalf("cancel pause: until=%d err=%v", until, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookiesGetStatusFailsClosedOnDatabaseError(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
if err := s.DB.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Cookies.GetStatus(context.Background(), "cid") {
|
||||
t.Fatal("database error must not silently enable an account")
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ItemPublishBatches 管理商品批量发布批次及其明细行的持久化。
|
||||
@@ -13,6 +15,9 @@ import (
|
||||
// 跟踪进度,支持失败重置(ResetFailed)和实时计数(Recount)。
|
||||
type ItemPublishBatches struct{ DB *sql.DB }
|
||||
|
||||
// ErrPublishBatchChanged 表示批次在读取与状态切换之间被其他 worker 更新,调用方可安全重试。
|
||||
var ErrPublishBatchChanged = errors.New("批量发布任务状态已变化")
|
||||
|
||||
// ItemPublishBatch 是一个发布批次的元信息(不含明细行)。
|
||||
type ItemPublishBatch struct {
|
||||
ID string // 批次 ID(上传时生成,UUID 形式)
|
||||
@@ -24,6 +29,8 @@ type ItemPublishBatch struct {
|
||||
TotalCount int // 明细行总数(Recount 维护)
|
||||
SuccessCount int // 成功数(Recount 维护)
|
||||
FailedCount int // 失败数(Recount 维护)
|
||||
WorkerToken string
|
||||
LeaseExpiresAt int64
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
}
|
||||
@@ -47,6 +54,8 @@ type ItemPublishBatchRow struct {
|
||||
ItemID string // 发布成功后回填的闲鱼商品 ID
|
||||
ItemURL string // 发布成功后回填的商品 URL
|
||||
ErrorMessage string // 失败原因
|
||||
FailureKind string // validation/publish/interrupted
|
||||
WorkerToken string
|
||||
RawJSON string // 发布接口原始返回 JSON
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
@@ -91,11 +100,11 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO item_publish_batch_rows
|
||||
(batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,automation_json,status,error_message,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
images_json,automation_json,status,item_id,item_url,error_message,failure_kind,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
batch.ID, row.RowNo, row.CookieID, row.Title, row.Description, row.Price, row.OriginalPrice,
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, row.AutomationJSON,
|
||||
row.Status, row.ErrorMessage, row.RawJSON); err != nil {
|
||||
row.Status, row.ItemID, row.ItemURL, row.ErrorMessage, row.FailureKind, row.RawJSON); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -107,10 +116,12 @@ func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (
|
||||
var out ItemPublishBatch
|
||||
err := b.DB.QueryRowContext(ctx,
|
||||
`SELECT id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count,
|
||||
COALESCE(worker_token,''),COALESCE(lease_expires_at,0),
|
||||
created_at,updated_at
|
||||
FROM item_publish_batches WHERE id=? AND user_id=?`, id, userID).Scan(
|
||||
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.Status,
|
||||
&out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.CreatedAt, &out.UpdatedAt)
|
||||
&out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.WorkerToken, &out.LeaseExpiresAt,
|
||||
&out.CreatedAt, &out.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
@@ -120,11 +131,66 @@ func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// ListForUser 返回用户最近的批量任务,供页面重载后重新发现运行记录。
|
||||
func (b *ItemPublishBatches) ListForUser(ctx context.Context, userID int64, limit int) ([]ItemPublishBatch, error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches WHERE user_id=? ORDER BY created_at DESC,id DESC LIMIT ?`, userID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
var batch ItemPublishBatch
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, batch)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Recoverable 返回租约过期或因进程退出中断、可安全自动续跑的任务。
|
||||
func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit int) ([]ItemPublishBatch, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches b
|
||||
WHERE (b.status IN ('running','canceling') AND (b.lease_expires_at=0 OR b.lease_expires_at<?))
|
||||
OR (b.status IN ('failed','partially_failed') AND EXISTS (
|
||||
SELECT 1 FROM item_publish_batch_rows r WHERE r.batch_id=b.id AND r.status='failed' AND r.failure_kind='interrupted'))
|
||||
ORDER BY b.updated_at,b.id LIMIT ?`, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
var batch ItemPublishBatch
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, batch)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Rows 取批次全部明细行,按 row_no 升序。
|
||||
func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPublishBatchRow, error) {
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID)
|
||||
if err != nil {
|
||||
@@ -136,7 +202,8 @@ func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPu
|
||||
var r ItemPublishBatchRow
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -154,6 +221,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID)
|
||||
if err != nil {
|
||||
@@ -165,7 +233,8 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
var r ItemPublishBatchRow
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -177,10 +246,382 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
// SetBatchStatus 更新批次状态(如 running/completed/failed)。
|
||||
func (b *ItemPublishBatches) SetBatchStatus(ctx context.Context, batchID, status string) error {
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batches SET status=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, status, batchID)
|
||||
`UPDATE item_publish_batches SET status=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP WHERE id=?`, status, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// RequestCancel 进入两阶段取消。运行中的批次保留 worker token,允许 worker
|
||||
// 把已经获得的远端商品 ID 落库后再结束;未运行批次可直接取消。
|
||||
func (b *ItemPublishBatches) RequestCancel(ctx context.Context, batchID string) (string, bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var status, token string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT status,worker_token FROM item_publish_batches WHERE id=?`, batchID).Scan(&status, &token); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", false, ErrNotFound
|
||||
}
|
||||
return "", false, err
|
||||
}
|
||||
running := (status == "running" || status == "canceling") && token != ""
|
||||
if running {
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches SET status='canceling',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status=? AND worker_token=?`, batchID, status, token)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
|
||||
return "", false, rowsErr
|
||||
} else if n != 1 {
|
||||
return "", false, ErrPublishBatchChanged
|
||||
}
|
||||
} else {
|
||||
// 先用读取到的状态和 token 把批次切到事务内不可领取的状态;CAS 失败时绝不触碰明细行。
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='finalizing_cancel',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status=? AND worker_token=?`, batchID, status, token)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
|
||||
return "", false, rowsErr
|
||||
} else if n != 1 {
|
||||
return "", false, ErrPublishBatchChanged
|
||||
}
|
||||
if err := markUnfinishedFailedTx(ctx, tx, batchID, "任务已取消"); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := recountBatchTx(ctx, tx, batchID); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
res, err = tx.ExecContext(ctx, `UPDATE item_publish_batches SET status='canceled',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='finalizing_cancel' AND worker_token=?`, batchID, token)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
|
||||
return "", false, rowsErr
|
||||
} else if n != 1 {
|
||||
return "", false, ErrPublishBatchChanged
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return token, running, nil
|
||||
}
|
||||
|
||||
func (b *ItemPublishBatches) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// 必须先取得当前 worker 的所有权并阻止租约接管,再修改任何明细行。
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='finalizing_cancel',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='canceling' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
if err := markUnfinishedFailedTx(ctx, tx, batchID, "任务已取消"); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := recountBatchTx(ctx, tx, batchID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
res, err = tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='canceled',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='finalizing_cancel' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err = res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit()
|
||||
}
|
||||
|
||||
// FinalizeInterrupted 只允许当前 worker 在一个事务内把未完成行标记为中断并结束批次。
|
||||
// 先切换到事务内的 finalizing_interrupted 状态,避免 token 检查与明细更新之间发生租约接管。
|
||||
func (b *ItemPublishBatches) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='finalizing_interrupted',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return "", false, err
|
||||
}
|
||||
if err := markUnfinishedFailedTx(ctx, tx, batchID, message); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
var total, success, failed, unfinished int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status NOT IN ('success','failed') THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).Scan(&total, &success, &failed, &unfinished); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if unfinished != 0 || total != success+failed {
|
||||
return "", false, errors.New("中断批次仍有未完成行")
|
||||
}
|
||||
status := finalBatchStatus(success, failed)
|
||||
res, err = tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,total_count=?,success_count=?,failed_count=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='finalizing_interrupted' AND worker_token=?`, status, total, success, failed, batchID, workerToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
n, err = res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return status, true, nil
|
||||
}
|
||||
|
||||
func finalBatchStatus(success, failed int) string {
|
||||
if failed == 0 {
|
||||
return "completed"
|
||||
}
|
||||
if success > 0 {
|
||||
return "partially_failed"
|
||||
}
|
||||
return "failed"
|
||||
}
|
||||
|
||||
// FinalizeExpiredCancellation 接管租约已过期的两阶段取消任务。远端调用已经开始但
|
||||
// 结果尚未落库的行必须保持为 uncertain_remote,其余未完成行统一标记为已取消。
|
||||
func (b *ItemPublishBatches) FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='canceled',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='canceling' AND (lease_expires_at=0 OR lease_expires_at<?)`, batchID, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
if err := markUnfinishedFailedTx(ctx, tx, batchID, "任务已取消"); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := recountBatchTx(ctx, tx, batchID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit()
|
||||
}
|
||||
|
||||
func markUnfinishedFailedTx(ctx context.Context, tx *sql.Tx, batchID, message string) error {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='任务取消时远端发布结果未知,请人工核对闲鱼商品列表',
|
||||
failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status IN ('pending','running')`, message, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
func recountBatchTx(ctx context.Context, tx *sql.Tx, batchID string) error {
|
||||
var total, success, failed int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).Scan(&total, &success, &failed); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET total_count=?,success_count=?,failed_count=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
total, success, failed, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *ItemPublishBatches) Delete(ctx context.Context, userID int64, batchID string) error {
|
||||
res, err := b.DB.ExecContext(ctx, `DELETE FROM item_publish_batches WHERE id=? AND user_id=? AND status NOT IN ('running','canceling')`, batchID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *ItemPublishBatches) ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]ItemPublishBatch, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
total_count,success_count,failed_count,worker_token,lease_expires_at,created_at,updated_at
|
||||
FROM item_publish_batches
|
||||
WHERE upload_dir<>'' AND status NOT IN ('running','canceling') AND updated_at<?
|
||||
ORDER BY updated_at LIMIT ?`, cutoff, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
var batch ItemPublishBatch
|
||||
if err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, batch)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (b *ItemPublishBatches) ClearUploadDir(ctx context.Context, batchID string) error {
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches SET upload_dir='',updated_at=CURRENT_TIMESTAMP WHERE id=?`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetInterrupted 只重置确认由进程中断造成的失败行,不自动重试业务失败或远端状态不确定的行。
|
||||
func (b *ItemPublishBatches) ResetInterrupted(ctx context.Context, batchID string) error {
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed' AND failure_kind='interrupted'`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimBatch 原子领取一个非运行批次。并发请求中只有一个 worker 能成功。
|
||||
func (b *ItemPublishBatches) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='running',worker_token=?,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND (status IN ('preview','pending','failed','partially_failed','completed','canceled')
|
||||
OR (status='running' AND (lease_expires_at=0 OR lease_expires_at<?)))`,
|
||||
workerToken, leaseExpiresAt, batchID, time.Now().UTC().Unix())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
// 远端发布已经开始但尚未保存商品 ID 的行结果未知,绝不能自动重放。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',worker_token='',error_message='上次任务在远端发布期间中断;结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>? AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 仅把确定尚未进入远端副作用,或已经保存远端商品 ID 的行重新放回队列。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',worker_token='',error_message='上次任务租约已过期,等待重试',failure_kind='interrupted',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>?`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RenewBatchLease 仅允许当前 worker 延长租约,长批次不会因固定截止时间被并发接管。
|
||||
func (b *ItemPublishBatches) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, leaseExpiresAt, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FailClaimedBatch 释放初始化阶段失败的批次租约。worker token 防止旧 worker
|
||||
// 覆盖已经被新 worker 接管的状态。
|
||||
func (b *ItemPublishBatches) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='failed',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinishBatchStatus 只允许当前持有租约的 worker 结束批次。
|
||||
func (b *ItemPublishBatches) FinishBatchStatus(ctx context.Context, batchID, workerToken, status string) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinalizeBatch 在单个事务内重算计数,并且只在所有行都进入终态后结束批次。
|
||||
func (b *ItemPublishBatches) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var total, success, failed, unfinished int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status NOT IN ('success','failed') THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).
|
||||
Scan(&total, &success, &failed, &unfinished); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if unfinished != 0 || total != success+failed {
|
||||
return "", false, errors.New("批次仍有未完成行,不能进入终态")
|
||||
}
|
||||
status := finalBatchStatus(success, failed)
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,total_count=?,success_count=?,failed_count=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, total, success, failed, batchID, workerToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return status, true, nil
|
||||
}
|
||||
|
||||
// BatchStatus 取批次状态。未找到返回 ErrNotFound。
|
||||
func (b *ItemPublishBatches) BatchStatus(ctx context.Context, batchID string) (string, error) {
|
||||
var status string
|
||||
@@ -197,10 +638,84 @@ func (b *ItemPublishBatches) BatchStatus(ctx context.Context, batchID string) (s
|
||||
// MarkRowRunning 将明细行置为 running 并清空历史错误信息(发布 worker 开始处理时调用)。
|
||||
func (b *ItemPublishBatches) MarkRowRunning(ctx context.Context, rowID int64) error {
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='running',error_message='',updated_at=CURRENT_TIMESTAMP WHERE id=?`, rowID)
|
||||
`UPDATE item_publish_batch_rows SET status='running',error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP WHERE id=? AND status='pending'`, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimRow 原子领取单行,防止多个 worker 重复发布同一商品。
|
||||
func (b *ItemPublishBatches) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='running',worker_token=?,error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='pending'
|
||||
AND EXISTS (SELECT 1 FROM item_publish_batches b
|
||||
WHERE b.id=item_publish_batch_rows.batch_id AND b.status='running' AND b.worker_token=?)`,
|
||||
workerToken, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRemoteStarted 在调用闲鱼发布接口前落盘。进程若在远端返回前硬退出,
|
||||
// 租约接管方会把该行隔离为 uncertain_remote,而不是再次发布。
|
||||
func (b *ItemPublishBatches) MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET failure_kind='remote_started',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(item_id,'')=''`, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowSuccess 只允许领取该行的 worker 写入成功结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// SaveClaimedRemoteResult 在闲鱼发布成功后第一时间保存远端商品标识。
|
||||
// 后续本地商品/自动化规则写入失败时,重试会从该断点继续而不会再次调用发布接口。
|
||||
func (b *ItemPublishBatches) SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if strings.TrimSpace(itemID) == "" {
|
||||
return false, errors.New("远端发布结果缺少商品ID")
|
||||
}
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET item_id=?,item_url=?,raw_json=?,failure_kind='post_publish',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowFailed 只允许领取该行的 worker 写入失败结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, message, kind, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkRowSuccess 标记明细行发布成功,回填闲鱼商品 ID、URL 与原始返回 JSON。
|
||||
func (b *ItemPublishBatches) MarkRowSuccess(ctx context.Context, rowID int64, itemID, itemURL, rawJSON string) error {
|
||||
if rawJSON == "" {
|
||||
@@ -208,24 +723,33 @@ func (b *ItemPublishBatches) MarkRowSuccess(ctx context.Context, rowID int64, it
|
||||
}
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, itemID, itemURL, rawJSON, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRowFailed 标记明细行发布失败并记录错误原因。
|
||||
func (b *ItemPublishBatches) MarkRowFailed(ctx context.Context, rowID int64, message string) error {
|
||||
return b.MarkRowFailedKind(ctx, rowID, message, "publish")
|
||||
}
|
||||
|
||||
func (b *ItemPublishBatches) MarkRowFailedKind(ctx context.Context, rowID int64, message, kind string) error {
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
message, rowID)
|
||||
`UPDATE item_publish_batch_rows SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
message, kind, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRunningFailed 将批次内仍在 running 的行标为失败。
|
||||
func (b *ItemPublishBatches) MarkRunningFailed(ctx context.Context, batchID, message string) error {
|
||||
if _, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running'`,
|
||||
message, batchID)
|
||||
return err
|
||||
@@ -233,9 +757,14 @@ func (b *ItemPublishBatches) MarkRunningFailed(ctx context.Context, batchID, mes
|
||||
|
||||
// MarkUnfinishedFailed 将批次内 pending/running 行标为失败。
|
||||
func (b *ItemPublishBatches) MarkUnfinishedFailed(ctx context.Context, batchID, message string) error {
|
||||
if _, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status IN ('pending','running')`,
|
||||
message, batchID)
|
||||
return err
|
||||
@@ -245,8 +774,9 @@ func (b *ItemPublishBatches) MarkUnfinishedFailed(ctx context.Context, batchID,
|
||||
func (b *ItemPublishBatches) ResetFailed(ctx context.Context, batchID string) error {
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed'`, batchID)
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed'
|
||||
AND COALESCE(failure_kind,'') NOT IN ('validation','uncertain_remote')`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFailClaimedBatchRequiresCurrentWorker(t *testing.T) {
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if ok, err := store.Users.Create(ctx, "lease-owner", "lease-owner@example.com", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create owner: ok=%v err=%v", ok, err)
|
||||
}
|
||||
owner, err := store.Users.GetByUsername(ctx, "lease-owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.PublishBatches.Create(ctx, &ItemPublishBatch{
|
||||
ID: "lease-failure", UserID: owner.ID, Filename: "test.csv", Status: "pending",
|
||||
}, []ItemPublishBatchRow{{RowNo: 1, Title: "item", Price: "1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := store.PublishBatches.ClaimBatch(ctx, "lease-failure", "current", time.Now().Add(time.Minute).Unix()); err != nil || !claimed {
|
||||
t.Fatalf("claim: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if released, err := store.PublishBatches.FailClaimedBatch(ctx, "lease-failure", "stale"); err != nil || released {
|
||||
t.Fatalf("stale release: released=%v err=%v", released, err)
|
||||
}
|
||||
if released, err := store.PublishBatches.FailClaimedBatch(ctx, "lease-failure", "current"); err != nil || !released {
|
||||
t.Fatalf("current release: released=%v err=%v", released, err)
|
||||
}
|
||||
batch, err := store.PublishBatches.Get(ctx, owner.ID, "lease-failure")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if batch.Status != "failed" || batch.WorkerToken != "" || batch.LeaseExpiresAt != 0 {
|
||||
t.Fatalf("unexpected released batch: %+v", batch)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
{"default_replies", "reply_once"},
|
||||
{"default_reply_records", "status"},
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"automation_runs", "action_cursor"},
|
||||
{"automation_runs", "action_started"},
|
||||
{"default_reply_records", "image_sent"},
|
||||
{"users", "is_admin"},
|
||||
{"sessions", "session_id"},
|
||||
@@ -52,6 +54,7 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
{"scheduled_api_cookie_renew_log", "request_count"},
|
||||
{"risk_control_logs", "processing_status"},
|
||||
{"risk_control_logs", "duration_ms"},
|
||||
{"notification_outbox", "worker_token"},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if !columnExists(t, db, c.table, c.col) {
|
||||
@@ -122,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚 16(回复投递状态)、15(AI 索引)、14(通知/日志),再整体升级。
|
||||
for i := 0; i < 3; i++ {
|
||||
// 依次回滚 21 到 14,再整体升级。
|
||||
for i := 0; i < 8; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE default_reply_records ADD COLUMN lease_expires_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE cookies ADD COLUMN paused_until BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE item_publish_batches
|
||||
ADD COLUMN worker_token VARCHAR(64) NOT NULL DEFAULT '',
|
||||
ADD COLUMN lease_expires_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE item_publish_batch_rows
|
||||
ADD COLUMN worker_token VARCHAR(64) NOT NULL DEFAULT '',
|
||||
ADD COLUMN failure_kind VARCHAR(32) NOT NULL DEFAULT '';
|
||||
|
||||
CREATE INDEX idx_publish_batches_lease
|
||||
ON item_publish_batches(status, lease_expires_at);
|
||||
CREATE INDEX idx_publish_rows_claim
|
||||
ON item_publish_batch_rows(batch_id, status, id);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_publish_rows_claim ON item_publish_batch_rows;
|
||||
DROP INDEX idx_publish_batches_lease ON item_publish_batches;
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN failure_kind, DROP COLUMN worker_token;
|
||||
ALTER TABLE item_publish_batches DROP COLUMN lease_expires_at, DROP COLUMN worker_token;
|
||||
ALTER TABLE cookies DROP COLUMN paused_until;
|
||||
ALTER TABLE default_reply_records DROP COLUMN lease_expires_at;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE automation_runs
|
||||
ADD COLUMN lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN attempt_count INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN next_retry_at BIGINT NOT NULL DEFAULT 0;
|
||||
CREATE INDEX idx_automation_runs_recovery
|
||||
ON automation_runs(status, lease_expires_at, next_retry_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_automation_runs_recovery ON automation_runs;
|
||||
ALTER TABLE automation_runs
|
||||
DROP COLUMN next_retry_at,
|
||||
DROP COLUMN attempt_count,
|
||||
DROP COLUMN lease_expires_at;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE automation_pending_tasks (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
task_key VARCHAR(512) NOT NULL UNIQUE,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
trigger_type VARCHAR(64) NOT NULL,
|
||||
task_json LONGTEXT NOT NULL,
|
||||
due_at BIGINT NOT NULL DEFAULT 0,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
attempt_count INTEGER NOT NULL DEFAULT 0,
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
error_message TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_pending_automation_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_automation_pending_due ON automation_pending_tasks(status, due_at, lease_expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS automation_pending_tasks;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE automation_runs ADD COLUMN action_cursor INT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE automation_runs ADD COLUMN action_started TINYINT(1) NOT NULL DEFAULT 0;
|
||||
CREATE INDEX idx_automation_runs_action_state ON automation_runs(status, action_started, lease_expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_automation_runs_action_state ON automation_runs;
|
||||
ALTER TABLE automation_runs DROP COLUMN action_started;
|
||||
ALTER TABLE automation_runs DROP COLUMN action_cursor;
|
||||
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user