Compare commits
291
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b64e588332 | ||
|
|
15019b524a | ||
|
|
441781dc8e | ||
|
|
cfc9508ee9 | ||
|
|
74d08748da | ||
|
|
c23a5a18b8 | ||
|
|
5f8d999ab0 | ||
|
|
5241a07e47 | ||
|
|
e92549da48 | ||
|
|
4227e3dd56 | ||
|
|
3cbe73b560 | ||
|
|
649af6499f | ||
|
|
2eeb37fd77 | ||
|
|
d2d8e02a39 | ||
|
|
9da450d940 | ||
|
|
3c46dd910b | ||
|
|
cad43780af | ||
|
|
be080e1500 | ||
|
|
6f2941d298 | ||
|
|
a90c9422c1 | ||
|
|
ee228381cf | ||
|
|
9eb6be2875 | ||
|
|
55904cc409 | ||
|
|
3fdace9492 | ||
|
|
a6c0d36ee9 | ||
|
|
1a228dc35c | ||
|
|
ecfe43b5a4 | ||
|
|
375e84d663 | ||
|
|
1185551018 | ||
|
|
19a7d5f924 | ||
|
|
a0ce23e9cf | ||
|
|
358a8e8553 | ||
|
|
550aee8aae | ||
|
|
25531c05cb | ||
|
|
3fdd0fe267 | ||
|
|
0a756c408e | ||
|
|
417723d2c0 | ||
|
|
e53177ccd1 | ||
|
|
bcdc163306 | ||
|
|
2cd3c946fc | ||
|
|
6d9f842244 | ||
|
|
46e3b2b40d | ||
|
|
73460ed6b1 | ||
|
|
fdc67bf938 | ||
|
|
48a0a2c4bd | ||
|
|
cd65334fec | ||
|
|
6a79710255 | ||
|
|
b2580e317f | ||
|
|
fae27a482b | ||
|
|
d3271e357a | ||
|
|
010e77be91 | ||
|
|
dbd337a508 | ||
|
|
627fd838e6 | ||
|
|
371bd9d17e | ||
|
|
afb7e2f0d9 | ||
|
|
eff4143fd6 | ||
|
|
90c3b4e76a | ||
|
|
e0c37524d9 | ||
|
|
599be84c65 | ||
|
|
1af2a8fea7 | ||
|
|
2fb6df13af | ||
|
|
0d0ab2aabb | ||
|
|
607d5a4003 | ||
|
|
b1e62b7bef | ||
|
|
67a12ff53a | ||
|
|
10371fa74a | ||
|
|
e609f7b39a | ||
|
|
c1c065e023 | ||
|
|
5b30551694 | ||
|
|
6bc29829ba | ||
|
|
8dbe2d6616 | ||
|
|
ac57a354ee | ||
|
|
c30029557c | ||
|
|
c27db2381b | ||
|
|
6375eecf8f | ||
|
|
d264b5bee3 | ||
|
|
44aa43c299 | ||
|
|
4c0dd4a748 | ||
|
|
1561f1e19d | ||
|
|
ef2234420b | ||
|
|
8559ac7108 | ||
|
|
70378afd23 | ||
|
|
12a79d4f62 | ||
|
|
e953464df9 | ||
|
|
1857a7c6ef | ||
|
|
7deee4a023 | ||
|
|
5c70b9ea6a | ||
|
|
d74d7ea521 | ||
|
|
2ff4d195a6 | ||
|
|
4d8d3240cc | ||
|
|
dd2c403e10 | ||
|
|
21eb7e1a8c | ||
|
|
f85f785246 | ||
|
|
456880f1a6 | ||
|
|
d851d42cd3 | ||
|
|
cec9c13217 | ||
|
|
c2503645e0 | ||
|
|
0a45fd4a8b | ||
|
|
5d4f2d3a5f | ||
|
|
eb1b92b853 | ||
|
|
a63292daa2 | ||
|
|
6b5215ddf3 | ||
|
|
850b66e155 | ||
|
|
afeb159bf1 | ||
|
|
558b6a3bb1 | ||
|
|
ba36babbfc | ||
|
|
2e4601f977 | ||
|
|
c423b53a3b | ||
|
|
e7ab04c0fc | ||
|
|
f62f43c97c | ||
|
|
b014291090 | ||
|
|
fdb90b1a0d | ||
|
|
8222adc73d | ||
|
|
620a565c44 | ||
|
|
2c626413a5 | ||
|
|
092ba6ecbe | ||
|
|
d0b24b7a2c | ||
|
|
0b172202cb | ||
|
|
a711613726 | ||
|
|
00641c3882 | ||
|
|
a2576f288a | ||
|
|
7af60232e5 | ||
|
|
7b85e8d8cc | ||
|
|
032a114fc8 | ||
|
|
fa7f2590a9 | ||
|
|
45dc3f079a | ||
|
|
0eeaf57e5b | ||
|
|
c698b4df5e | ||
|
|
f9debf687f | ||
|
|
6cd5e68636 | ||
|
|
eca9995c52 | ||
|
|
028309da5d | ||
|
|
2c94fddab5 | ||
|
|
2a018eb6dc | ||
|
|
f74750ba3a | ||
|
|
aa3e532700 | ||
|
|
8fd4c78d4b | ||
|
|
7c7a164be7 | ||
|
|
dac12619f7 | ||
|
|
aac307093a | ||
|
|
53b507755b | ||
|
|
beb8235a16 | ||
|
|
7165476aa3 | ||
|
|
624d2b66ab | ||
|
|
623624235e | ||
|
|
30762d4121 | ||
|
|
121fbe7f48 | ||
|
|
53dc0d95fe | ||
|
|
eb9dbd27cc | ||
|
|
f4f51a8d3c | ||
|
|
63c34cbcea | ||
|
|
a9d840a8c5 | ||
|
|
82d76f9fcc | ||
|
|
6116428bf6 | ||
|
|
03db39019b | ||
|
|
9665341f18 | ||
|
|
893785ad96 | ||
|
|
b47db9470d | ||
|
|
e0aab1af2e | ||
|
|
f30a1f68f8 | ||
|
|
d1a165f897 | ||
|
|
ea1f2ec430 | ||
|
|
393c45a1e3 | ||
|
|
a45a82a149 | ||
|
|
c9ac336547 | ||
|
|
4daef77117 | ||
|
|
85369484d6 | ||
|
|
73a63eecce | ||
|
|
8c16e7810c | ||
|
|
64e7868444 | ||
|
|
9255c233aa | ||
|
|
668a4ed3f3 | ||
|
|
c47271ae9c | ||
|
|
6257fad453 | ||
|
|
c90461226b | ||
|
|
e1b06933df | ||
|
|
0853a107a2 | ||
|
|
190dc80cc0 | ||
|
|
e5d4998e61 | ||
|
|
2110d6c431 | ||
|
|
0e8cea087b | ||
|
|
a1bf5078d8 | ||
|
|
98023744fa | ||
|
|
a2a22ad3e3 | ||
|
|
2ca4ac9f2b | ||
|
|
6f8356ba4c | ||
|
|
f613bb4eb8 | ||
|
|
f46bdd1c8e | ||
|
|
0fc7f1b433 | ||
|
|
3638d702d0 | ||
|
|
22656c20f1 | ||
|
|
448713735f | ||
|
|
867ced6849 | ||
|
|
c6da6d96c1 | ||
|
|
d388d76851 | ||
|
|
56b20507f3 | ||
|
|
2ec7bec05f | ||
|
|
b128ce60db | ||
|
|
66ac84b32d | ||
|
|
03f108639d | ||
|
|
c7c7023ad4 | ||
|
|
e79d76dcdf | ||
|
|
6b4bbed9a2 | ||
|
|
b831f2d7c8 | ||
|
|
e5df708e4a | ||
|
|
9255eb3132 | ||
|
|
885a5760de | ||
|
|
176ecb7b59 | ||
|
|
84ad707abe | ||
|
|
70ff5d6078 | ||
|
|
d38f8d7aaa | ||
|
|
10ba79c292 | ||
|
|
e81c003601 | ||
|
|
67e245d143 | ||
|
|
d0546d4392 | ||
|
|
df914fc0f7 | ||
|
|
de723ee306 | ||
|
|
06ca978a32 | ||
|
|
4a1546f2aa | ||
|
|
1e6b0593b3 | ||
|
|
8d103b1cc0 | ||
|
|
caecc09c79 | ||
|
|
a204876400 | ||
|
|
acd9470d51 | ||
|
|
d3648e9985 | ||
|
|
42e37f7898 | ||
|
|
78a256c51e | ||
|
|
e90a0b08d6 | ||
|
|
bc97f35fda | ||
|
|
50a135fc29 | ||
|
|
3d493ce2d4 | ||
|
|
eb8a54698c | ||
|
|
415a3adc5f | ||
|
|
42cc9ce675 | ||
|
|
6ff3499ca9 | ||
|
|
929b3fd8a9 | ||
|
|
f76fb08cbe | ||
|
|
fe6fc3adb9 | ||
|
|
0ca52e43ad | ||
|
|
ebce42f9dc | ||
|
|
1a14f18b07 | ||
|
|
82da4d8bb5 | ||
|
|
4d92e8e919 | ||
|
|
1efe44e921 | ||
|
|
4e7abf61be | ||
|
|
9f99f2b78a | ||
|
|
337038adcf | ||
|
|
bae1b0a0fd | ||
|
|
e1ce75b7f8 | ||
|
|
9e324b490b | ||
|
|
4d92358dfa | ||
|
|
b27367a564 | ||
|
|
5fe2b92bdc | ||
|
|
b65cb8b0ba | ||
|
|
70b5e39566 | ||
|
|
ccfc630fd7 | ||
|
|
72f341eab8 | ||
|
|
aec7e1186b | ||
|
|
0cd4109014 | ||
|
|
04e1aab2e8 | ||
|
|
8936988c7a | ||
|
|
106a88f346 | ||
|
|
eb840da41c | ||
|
|
c4d2d341d4 | ||
|
|
129358b52f | ||
|
|
9ce092960a | ||
|
|
d54377d2ef | ||
|
|
5bb60cabcd | ||
|
|
b32f0a1173 | ||
|
|
aa3003ceda | ||
|
|
f78c8da49a | ||
|
|
1b60d161ee | ||
|
|
a642b02ec3 | ||
|
|
2d8b319f53 | ||
|
|
8215cc0e95 | ||
|
|
3f77cdba3d | ||
|
|
782bea1115 | ||
|
|
1833020caf | ||
|
|
36798dcced | ||
|
|
1a9be54355 | ||
|
|
17deffcfb5 | ||
|
|
e3a9404d0d | ||
|
|
59b1061ec5 | ||
|
|
ca00c159f0 | ||
|
|
96aa8f1ced | ||
|
|
1c8e2ab163 | ||
|
|
ac85ac8a0a | ||
|
|
65bcb8f15c | ||
|
|
7ec0b4a078 | ||
|
|
d36c357bab | ||
|
|
70e03a8523 |
No files matched your search
@@ -0,0 +1,142 @@
|
|||||||
|
name: Pull Request 质量门禁
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- dev
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
go:
|
||||||
|
name: Go 检查
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: 配置 Go
|
||||||
|
uses: actions/setup-go@v7
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: 检查格式
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
if [ -n "$(gofmt -l .)" ]; then
|
||||||
|
echo "发现未格式化的 Go 文件,请先运行 gofmt -w。" >&2
|
||||||
|
gofmt -l .
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: 检查中文注释
|
||||||
|
run: go run ./tools/commentlint -mode check -root .
|
||||||
|
|
||||||
|
- name: 检查架构依赖
|
||||||
|
run: go run ./tools/architecturecheck
|
||||||
|
|
||||||
|
- name: 运行 go vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: 运行 golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v9
|
||||||
|
with:
|
||||||
|
version: v2.12.2
|
||||||
|
args: ./...
|
||||||
|
|
||||||
|
- name: 运行 Go 测试
|
||||||
|
run: go test ./...
|
||||||
|
|
||||||
|
- name: 运行 server 并发 smoke race
|
||||||
|
run: make test-server-race
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
name: React 前端检查
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: 配置 Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
|
- name: 安装前端依赖
|
||||||
|
run: npm ci --prefix frontend
|
||||||
|
|
||||||
|
- name: 检查中文注释
|
||||||
|
run: npm run comments:check --prefix frontend
|
||||||
|
|
||||||
|
- name: 检查 TypeScript 类型
|
||||||
|
run: npm run typecheck --prefix frontend
|
||||||
|
|
||||||
|
- name: 运行前端测试
|
||||||
|
run: npm test --prefix frontend
|
||||||
|
|
||||||
|
- name: 构建并校验嵌入式前端产物
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
npm run build --prefix frontend
|
||||||
|
git diff --exit-code -- internal/webui/static
|
||||||
|
|
||||||
|
multidb:
|
||||||
|
name: MySQL/PostgreSQL 多数据库回归
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 20
|
||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:8.4
|
||||||
|
env:
|
||||||
|
MYSQL_ROOT_PASSWORD: test-root-password
|
||||||
|
MYSQL_ROOT_HOST: "%"
|
||||||
|
MYSQL_DATABASE: xianyu
|
||||||
|
TZ: UTC
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
options: >-
|
||||||
|
--health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -ptest-root-password --silent"
|
||||||
|
--health-interval=5s
|
||||||
|
--health-timeout=5s
|
||||||
|
--health-retries=30
|
||||||
|
postgres:
|
||||||
|
image: postgres:17
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: xianyu
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: test-postgres-password
|
||||||
|
TZ: UTC
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
options: >-
|
||||||
|
--health-cmd="pg_isready -U postgres -d xianyu"
|
||||||
|
--health-interval=5s
|
||||||
|
--health-timeout=5s
|
||||||
|
--health-retries=30
|
||||||
|
env:
|
||||||
|
TEST_MYSQL_URL: "mysql://root:test-root-password@tcp(127.0.0.1:3306)/xianyu?parseTime=true&loc=UTC"
|
||||||
|
TEST_POSTGRES_URL: "postgres://postgres:test-postgres-password@127.0.0.1:5432/xianyu?sslmode=disable&timezone=UTC"
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: 配置 Go
|
||||||
|
uses: actions/setup-go@v7
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: 执行三方言实测回归
|
||||||
|
run: make test-multidb
|
||||||
@@ -4,8 +4,14 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
- codex/desktop-packaging
|
- dev
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
app_version:
|
||||||
|
description: 正式发布版本号(不含 v)
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -14,14 +20,43 @@ concurrency:
|
|||||||
group: desktop-cd-${{ github.ref }}
|
group: desktop-cd-${{ github.ref }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
|
||||||
APP_VERSION: 0.0.0-${{ github.run_number }}
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
prepare:
|
||||||
|
name: 准备发布版本
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
outputs:
|
||||||
|
app_version: ${{ steps.version.outputs.app_version }}
|
||||||
|
build_version: ${{ steps.version.outputs.build_version }}
|
||||||
|
build_time: ${{ steps.version.outputs.build_time }}
|
||||||
|
steps:
|
||||||
|
- name: 解析并校验版本号
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
if [ -n "${{ inputs.app_version }}" ]; then
|
||||||
|
app_version="${{ inputs.app_version }}"
|
||||||
|
build_version="$app_version"
|
||||||
|
else
|
||||||
|
app_version="0.0.${GITHUB_RUN_NUMBER}"
|
||||||
|
build_version="${GITHUB_REF_NAME}-${GITHUB_SHA::12}"
|
||||||
|
fi
|
||||||
|
if [[ ! "$app_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "安装包版本必须符合 1.2.3 格式:$app_version" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "app_version=$app_version" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "build_version=$build_version" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
linux:
|
linux:
|
||||||
name: Linux 安装包 (${{ matrix.arch }})
|
name: Linux 安装包 (${{ matrix.arch }})
|
||||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
needs: prepare
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
|
env:
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||||
|
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -45,7 +80,7 @@ jobs:
|
|||||||
- name: 配置 Node.js
|
- name: 配置 Node.js
|
||||||
uses: actions/setup-node@v6
|
uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 24
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
@@ -60,15 +95,16 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}"
|
package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}"
|
||||||
mkdir -p "$package_dir"
|
mkdir -p "$package_dir"
|
||||||
go build -trimpath -ldflags='-s -w' -o "$package_dir/xianyu-server" ./cmd/server
|
version_ldflags="-s -w -X xianyu-go/internal/version.Version=$BUILD_VERSION -X xianyu-go/internal/version.Commit=$GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$BUILD_TIME"
|
||||||
|
go build -trimpath -ldflags="$version_ldflags" -o "$package_dir/xianyu-server" ./cmd/server
|
||||||
go build -trimpath -ldflags='-s -w' -o "$package_dir/browser-install" ./cmd/browser-install
|
go build -trimpath -ldflags='-s -w' -o "$package_dir/browser-install" ./cmd/browser-install
|
||||||
|
|
||||||
- name: 缓存 Linux Chromium runtime
|
- name: 恢复 Linux Chromium runtime 缓存
|
||||||
id: cache-linux-playwright
|
id: cache-linux-playwright
|
||||||
uses: actions/cache@v5
|
uses: actions/cache/restore@v5
|
||||||
with:
|
with:
|
||||||
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
||||||
key: ydisks-playwright-runtime-v6-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
|
key: ydisks-playwright-runtime-v6-linux-${{ matrix.arch }}-${{ matrix.playwright_platform }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||||
|
|
||||||
- name: 在原生架构 runner 预下载 Linux Chromium runtime
|
- name: 在原生架构 runner 预下载 Linux Chromium runtime
|
||||||
if: steps.cache-linux-playwright.outputs.cache-hit != 'true'
|
if: steps.cache-linux-playwright.outputs.cache-hit != 'true'
|
||||||
@@ -111,8 +147,8 @@ jobs:
|
|||||||
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
||||||
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
||||||
test -n "$chromium_path"
|
test -n "$chromium_path"
|
||||||
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
chromium_revision="$(RUNTIME_SPEC="$PWD/$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||||
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
headless_revision="$(RUNTIME_SPEC="$PWD/$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
||||||
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
||||||
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
||||||
chromium_type="$(file -b "$chromium_path")"
|
chromium_type="$(file -b "$chromium_path")"
|
||||||
@@ -122,6 +158,13 @@ jobs:
|
|||||||
*) echo "Chromium 架构错误:$chromium_type" >&2; exit 1 ;;
|
*) echo "Chromium 架构错误:$chromium_type" >&2; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
- name: 保存 Linux Chromium runtime 缓存
|
||||||
|
if: steps.cache-linux-playwright.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v5
|
||||||
|
with:
|
||||||
|
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
||||||
|
key: ${{ steps.cache-linux-playwright.outputs.cache-primary-key }}
|
||||||
|
|
||||||
- name: 组装 Linux 安装目录
|
- name: 组装 Linux 安装目录
|
||||||
run: |
|
run: |
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
@@ -140,8 +183,12 @@ jobs:
|
|||||||
|
|
||||||
windows:
|
windows:
|
||||||
name: Windows 安装包
|
name: Windows 安装包
|
||||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
needs: prepare
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
|
env:
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||||
|
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||||
steps:
|
steps:
|
||||||
- name: 检出代码
|
- name: 检出代码
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -155,7 +202,7 @@ jobs:
|
|||||||
- name: 配置 Node.js
|
- name: 配置 Node.js
|
||||||
uses: actions/setup-node@v6
|
uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 24
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
@@ -167,32 +214,42 @@ jobs:
|
|||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
go test ./cmd/tray
|
go test ./cmd/tray
|
||||||
|
$serviceScript = (Resolve-Path 'packaging/windows/service-control.ps1').Path
|
||||||
$tokens = $null
|
$tokens = $null
|
||||||
$parseErrors = $null
|
$parseErrors = $null
|
||||||
[void][System.Management.Automation.Language.Parser]::ParseFile(
|
[void][System.Management.Automation.Language.Parser]::ParseFile(
|
||||||
(Resolve-Path 'packaging/windows/service-control.ps1'),
|
$serviceScript,
|
||||||
[ref]$tokens,
|
[ref]$tokens,
|
||||||
[ref]$parseErrors
|
[ref]$parseErrors
|
||||||
)
|
)
|
||||||
if ($parseErrors.Count -gt 0) {
|
if ($parseErrors.Count -gt 0) {
|
||||||
$parseErrors | ForEach-Object { Write-Error $_.Message }
|
$parseErrors | ForEach-Object { Write-Error $_.Message }
|
||||||
throw 'Windows 服务安装脚本语法检查失败'
|
throw 'Windows 服务安装脚本在 PowerShell 7 下语法检查失败'
|
||||||
|
}
|
||||||
|
|
||||||
|
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||||
|
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||||
|
-File $serviceScript -Mode stop -ServiceName "YdisksSyntaxCheck-$PID"
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Windows 服务安装脚本在 Windows PowerShell 5.1 下检查失败,错误码: $LASTEXITCODE"
|
||||||
}
|
}
|
||||||
|
|
||||||
- name: 编译 Windows 桌面程序
|
- name: 编译 Windows 桌面程序
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
|
& packaging/windows/build-resources.ps1
|
||||||
New-Item -ItemType Directory -Force -Path dist/windows | Out-Null
|
New-Item -ItemType Directory -Force -Path dist/windows | Out-Null
|
||||||
go build -trimpath -ldflags "-s -w" -o dist/windows/xianyu-server.exe ./cmd/server
|
$versionLdflags = "-s -w -X xianyu-go/internal/version.Version=$env:BUILD_VERSION -X xianyu-go/internal/version.Commit=$env:GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$env:BUILD_TIME"
|
||||||
|
go build -trimpath -ldflags $versionLdflags -o dist/windows/xianyu-server.exe ./cmd/server
|
||||||
go build -trimpath -ldflags "-s -w" -o dist/windows/browser-install.exe ./cmd/browser-install
|
go build -trimpath -ldflags "-s -w" -o dist/windows/browser-install.exe ./cmd/browser-install
|
||||||
go build -trimpath -ldflags "-s -w -H=windowsgui" -o dist/windows/xianyu-tray.exe ./cmd/tray
|
go build -trimpath -ldflags "-s -w -H=windowsgui" -o dist/windows/xianyu-tray.exe ./cmd/tray
|
||||||
|
|
||||||
- name: 缓存 Windows Chromium runtime
|
- name: 恢复 Windows Chromium runtime 缓存
|
||||||
id: cache-windows-playwright
|
id: cache-windows-playwright
|
||||||
uses: actions/cache@v5
|
uses: actions/cache/restore@v5
|
||||||
with:
|
with:
|
||||||
path: dist/windows/playwright-runtime/amd64
|
path: dist/windows/playwright-runtime/amd64
|
||||||
key: ydisks-playwright-runtime-v6-windows-amd64-${{ hashFiles('go.mod', 'go.sum') }}
|
key: ydisks-playwright-runtime-v6-windows-amd64-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||||
|
|
||||||
- name: 预下载 Windows Chromium runtime
|
- name: 预下载 Windows Chromium runtime
|
||||||
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
||||||
@@ -223,6 +280,98 @@ jobs:
|
|||||||
Select-Object -First 1
|
Select-Object -First 1
|
||||||
if ($null -eq $chromium) { throw 'Windows Chromium runtime 缺少 Chromium 可执行文件' }
|
if ($null -eq $chromium) { throw 'Windows Chromium runtime 缺少 Chromium 可执行文件' }
|
||||||
|
|
||||||
|
- name: 实际验证 Windows 服务注册
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$serviceName = 'YdisksXianyuHelper'
|
||||||
|
$workDir = Join-Path $env:RUNNER_TEMP $serviceName
|
||||||
|
$runtimeRoot = (Resolve-Path 'dist/windows/playwright-runtime/amd64').Path
|
||||||
|
$serviceScript = (Resolve-Path 'packaging/windows/service-control.ps1').Path
|
||||||
|
$serverPath = (Resolve-Path 'dist/windows/xianyu-server.exe').Path
|
||||||
|
try {
|
||||||
|
foreach ($registerAttempt in 1..2) {
|
||||||
|
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||||
|
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||||
|
-File $serviceScript -Mode register -ServiceName $serviceName `
|
||||||
|
-ExePath $serverPath -WorkDir $workDir -RuntimeRoot $runtimeRoot
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Windows 服务第 $registerAttempt 次注册失败,错误码: $LASTEXITCODE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||||
|
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||||
|
-File $serviceScript -Mode start -ServiceName $serviceName
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Windows 服务启动失败,错误码: $LASTEXITCODE" }
|
||||||
|
|
||||||
|
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||||
|
$serviceStatus = $service.Status
|
||||||
|
$service.Dispose()
|
||||||
|
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||||
|
throw "Windows 服务未进入运行状态: $serviceStatus"
|
||||||
|
}
|
||||||
|
|
||||||
|
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||||
|
if ($null -eq $serviceConfig) { throw 'Windows 服务注册后无法读取配置' }
|
||||||
|
# Win32_Service.PathName 可能会省略不含空格路径两侧的引号,比较前统一去掉引号。
|
||||||
|
$actualServiceCommand = $serviceConfig.PathName.Replace('"', '')
|
||||||
|
$requiredServiceArguments = @(
|
||||||
|
$serverPath,
|
||||||
|
'-service',
|
||||||
|
"-workdir $workDir",
|
||||||
|
"-playwright-runtime-root $runtimeRoot"
|
||||||
|
)
|
||||||
|
$invalidServiceArgument = $requiredServiceArguments |
|
||||||
|
Where-Object {
|
||||||
|
$actualServiceCommand.IndexOf($_, [StringComparison]::OrdinalIgnoreCase) -lt 0
|
||||||
|
} |
|
||||||
|
Select-Object -First 1
|
||||||
|
if ($null -ne $invalidServiceArgument) {
|
||||||
|
throw "Windows 服务命令行不正确: $($serviceConfig.PathName)"
|
||||||
|
}
|
||||||
|
$delayedStart = Get-ItemPropertyValue `
|
||||||
|
-LiteralPath "Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\$serviceName" `
|
||||||
|
-Name DelayedAutostart -ErrorAction Stop
|
||||||
|
if ($delayedStart -ne 1) { throw "Windows 服务未配置延迟自动启动: $delayedStart" }
|
||||||
|
$sddl = (& "$env:SystemRoot\System32\sc.exe" sdshow $serviceName 2>&1) -join ''
|
||||||
|
if ($LASTEXITCODE -ne 0 -or -not $sddl.Contains('(A;;LCRPWP;;;IU)')) {
|
||||||
|
throw "Windows 服务未授予交互用户启停权限: $sddl"
|
||||||
|
}
|
||||||
|
|
||||||
|
$health = $null
|
||||||
|
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||||
|
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||||
|
try {
|
||||||
|
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||||
|
} catch {
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||||
|
throw "Windows 服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
$serverLog = Join-Path $workDir 'logs\server.log'
|
||||||
|
if (Test-Path -LiteralPath $serverLog) {
|
||||||
|
Get-Content -LiteralPath $serverLog -Tail 200
|
||||||
|
}
|
||||||
|
throw
|
||||||
|
} finally {
|
||||||
|
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||||
|
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||||
|
-File $serviceScript -Mode uninstall -ServiceName $serviceName
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Windows 服务清理失败,错误码: $LASTEXITCODE" }
|
||||||
|
if ($null -ne (Get-Service -Name $serviceName -ErrorAction SilentlyContinue)) {
|
||||||
|
throw 'Windows 服务卸载后仍然存在'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: 保存 Windows Chromium runtime 缓存
|
||||||
|
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v5
|
||||||
|
with:
|
||||||
|
path: dist/windows/playwright-runtime/amd64
|
||||||
|
key: ${{ steps.cache-windows-playwright.outputs.cache-primary-key }}
|
||||||
|
|
||||||
- name: 导入 Windows 签名证书
|
- name: 导入 Windows 签名证书
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
env:
|
env:
|
||||||
@@ -254,11 +403,59 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
APP_VERSION: ${{ env.APP_VERSION }}
|
APP_VERSION: ${{ env.APP_VERSION }}
|
||||||
run: |
|
run: |
|
||||||
& 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' /Qp /O"dist\windows" packaging\windows\installer.iss
|
$shortDrive = 'R:'
|
||||||
|
if (Test-Path -LiteralPath "$shortDrive\") {
|
||||||
|
throw "短路径盘符已被占用: $shortDrive"
|
||||||
|
}
|
||||||
|
& "$env:SystemRoot\System32\subst.exe" $shortDrive $env:GITHUB_WORKSPACE
|
||||||
|
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath "$shortDrive\")) {
|
||||||
|
throw "无法创建 Windows 安装器短路径盘符: $shortDrive"
|
||||||
|
}
|
||||||
|
$locationPushed = $false
|
||||||
|
try {
|
||||||
|
Push-Location "$shortDrive\"
|
||||||
|
$locationPushed = $true
|
||||||
|
$requiredSources = @(
|
||||||
|
'dist/windows/xianyu-server.exe',
|
||||||
|
'dist/windows/xianyu-tray.exe',
|
||||||
|
'dist/windows/playwright-runtime/amd64',
|
||||||
|
'icon/windows/icon.ico',
|
||||||
|
'packaging/windows/languages/ChineseSimplified.isl',
|
||||||
|
'packaging/windows/languages/ChineseTraditional.isl',
|
||||||
|
'packaging/windows/service-control.ps1'
|
||||||
|
)
|
||||||
|
foreach ($source in $requiredSources) {
|
||||||
|
if (-not (Test-Path -LiteralPath $source)) {
|
||||||
|
throw "Windows 安装器源文件或目录不存在: $source"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$runtimeFiles = Get-ChildItem -LiteralPath 'dist/windows/playwright-runtime/amd64' -Recurse -File
|
||||||
|
if ($null -eq ($runtimeFiles | Select-Object -First 1)) {
|
||||||
|
throw 'Windows 安装器 Playwright runtime 为空'
|
||||||
|
}
|
||||||
|
$longestRuntimeFile = $runtimeFiles |
|
||||||
|
Sort-Object { $_.FullName.Length } -Descending |
|
||||||
|
Select-Object -First 1
|
||||||
|
Write-Host "Windows runtime 最长源路径长度: $($longestRuntimeFile.FullName.Length)"
|
||||||
|
Write-Host "Windows runtime 最长源路径: $($longestRuntimeFile.FullName)"
|
||||||
|
|
||||||
|
$compiler = 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe'
|
||||||
|
$scriptPath = (Resolve-Path 'packaging/windows/installer.iss').Path
|
||||||
|
$outputDir = (Resolve-Path 'dist/windows').Path
|
||||||
|
& $compiler /Qp "/O$outputDir" $scriptPath
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Inno Setup 编译失败,错误码: $LASTEXITCODE"
|
||||||
|
}
|
||||||
$installer = Get-ChildItem -Path dist/windows -Filter 'Ydisks-Xianyu-Helper-Setup.exe' -Recurse | Select-Object -First 1
|
$installer = Get-ChildItem -Path dist/windows -Filter 'Ydisks-Xianyu-Helper-Setup.exe' -Recurse | Select-Object -First 1
|
||||||
if ($null -eq $installer) { throw 'Inno Setup 未生成安装器' }
|
if ($null -eq $installer) { throw 'Inno Setup 未生成安装器' }
|
||||||
$target = Join-Path (Resolve-Path dist/windows) 'Ydisks-Xianyu-Helper-Setup.exe'
|
$target = Join-Path (Resolve-Path dist/windows) 'Ydisks-Xianyu-Helper-Setup.exe'
|
||||||
if ($installer.FullName -ne $target) { Copy-Item $installer.FullName $target -Force }
|
if ($installer.FullName -ne $target) { Copy-Item $installer.FullName $target -Force }
|
||||||
|
} finally {
|
||||||
|
if ($locationPushed) {
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
|
& "$env:SystemRoot\System32\subst.exe" $shortDrive /D | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
- name: 签名 Windows 安装器
|
- name: 签名 Windows 安装器
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
@@ -270,26 +467,140 @@ jobs:
|
|||||||
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
|
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
|
||||||
-Files 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe'
|
-Files 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe'
|
||||||
|
|
||||||
- name: 打包 Windows 二进制归档
|
- name: 使用安装器验证服务安装与卸载
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
env:
|
|
||||||
APP_VERSION: ${{ env.APP_VERSION }}
|
|
||||||
run: |
|
run: |
|
||||||
Compress-Archive -Path dist/windows/xianyu-server.exe,dist/windows/xianyu-tray.exe,dist/windows/playwright-runtime -DestinationPath "dist/windows/Ydisks-Xianyu-Helper-${env:APP_VERSION}-binaries.zip"
|
$serviceName = 'YdisksXianyuHelper'
|
||||||
|
$installer = (Resolve-Path 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe').Path
|
||||||
|
$installLog = Join-Path $env:RUNNER_TEMP 'ydisks-windows-installer.log'
|
||||||
|
$installDir = Join-Path $env:ProgramFiles 'Ydisks Xianyu Helper'
|
||||||
|
$uninstaller = Join-Path $installDir 'unins000.exe'
|
||||||
|
try {
|
||||||
|
$installerProcess = Start-Process -FilePath $installer `
|
||||||
|
-ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', "/LOG=$installLog") `
|
||||||
|
-Wait -PassThru
|
||||||
|
$installerExitCode = $installerProcess.ExitCode
|
||||||
|
if ($installerExitCode -ne 0) {
|
||||||
|
if (Test-Path -LiteralPath $installLog) {
|
||||||
|
Get-Content -LiteralPath $installLog -Tail 200
|
||||||
|
}
|
||||||
|
throw "Windows 安装器执行失败,错误码: $installerExitCode"
|
||||||
|
}
|
||||||
|
|
||||||
|
$service = Get-Service -Name $serviceName -ErrorAction Stop
|
||||||
|
$serviceStatus = $service.Status
|
||||||
|
$service.Dispose()
|
||||||
|
if ($serviceStatus -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {
|
||||||
|
throw "安装器未启动 Windows 服务: $serviceStatus"
|
||||||
|
}
|
||||||
|
|
||||||
|
$expectedServer = Join-Path $installDir 'xianyu-server.exe'
|
||||||
|
$expectedRuntime = Join-Path $installDir 'playwright-runtime'
|
||||||
|
$serviceConfig = Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction Stop
|
||||||
|
$actualServiceCommand = if ($null -eq $serviceConfig) { '' } else { $serviceConfig.PathName.Replace('"', '') }
|
||||||
|
$requiredServiceArguments = @(
|
||||||
|
$expectedServer,
|
||||||
|
'-service',
|
||||||
|
"-playwright-runtime-root $expectedRuntime"
|
||||||
|
)
|
||||||
|
$invalidServiceArgument = $requiredServiceArguments |
|
||||||
|
Where-Object {
|
||||||
|
$actualServiceCommand.IndexOf($_, [StringComparison]::OrdinalIgnoreCase) -lt 0
|
||||||
|
} |
|
||||||
|
Select-Object -First 1
|
||||||
|
if ($null -ne $invalidServiceArgument) {
|
||||||
|
throw "安装器注册的服务命令行不正确: $($serviceConfig.PathName)"
|
||||||
|
}
|
||||||
|
|
||||||
|
$health = $null
|
||||||
|
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||||
|
while ([DateTime]::UtcNow -lt $deadline -and $null -eq $health) {
|
||||||
|
try {
|
||||||
|
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:59188/health' -TimeoutSec 2
|
||||||
|
} catch {
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($null -eq $health -or $health.status -ne 'ok' -or $health.database -ne 'ok') {
|
||||||
|
throw "安装器服务健康检查失败: $($health | ConvertTo-Json -Compress)"
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $uninstaller -PathType Leaf)) {
|
||||||
|
throw "Windows 卸载器不存在: $uninstaller"
|
||||||
|
}
|
||||||
|
$expectedTray = Join-Path $installDir 'xianyu-tray.exe'
|
||||||
|
$startMenuRoots = @(
|
||||||
|
(Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs'),
|
||||||
|
(Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')
|
||||||
|
)
|
||||||
|
$startMenuShortcut = $startMenuRoots |
|
||||||
|
Where-Object { Test-Path -LiteralPath $_ -PathType Container } |
|
||||||
|
ForEach-Object {
|
||||||
|
Get-ChildItem -LiteralPath $_ -Filter '*.lnk' -Recurse -File -ErrorAction SilentlyContinue
|
||||||
|
} |
|
||||||
|
Where-Object {
|
||||||
|
$shortcutShell = New-Object -ComObject WScript.Shell
|
||||||
|
$shortcutTarget = $shortcutShell.CreateShortcut($_.FullName).TargetPath
|
||||||
|
[StringComparer]::OrdinalIgnoreCase.Equals($shortcutTarget, $expectedTray)
|
||||||
|
} |
|
||||||
|
Select-Object -First 1
|
||||||
|
if ($null -eq $startMenuShortcut) {
|
||||||
|
throw '安装器未创建开始菜单快捷方式'
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (Test-Path -LiteralPath $installLog) {
|
||||||
|
Get-Content -LiteralPath $installLog -Tail 200
|
||||||
|
}
|
||||||
|
$serverLog = Join-Path $env:ProgramData 'YdisksXianyuHelper\logs\server.log'
|
||||||
|
if (Test-Path -LiteralPath $serverLog) {
|
||||||
|
Get-Content -LiteralPath $serverLog -Tail 200
|
||||||
|
}
|
||||||
|
throw
|
||||||
|
} finally {
|
||||||
|
if (Test-Path -LiteralPath $uninstaller -PathType Leaf) {
|
||||||
|
$uninstallerProcess = Start-Process -FilePath $uninstaller `
|
||||||
|
-ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART') `
|
||||||
|
-Wait -PassThru
|
||||||
|
if ($uninstallerProcess.ExitCode -ne 0) {
|
||||||
|
throw "Windows 卸载器执行失败,错误码: $($uninstallerProcess.ExitCode)"
|
||||||
|
}
|
||||||
|
} elseif ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||||
|
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
|
||||||
|
-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `
|
||||||
|
-File (Resolve-Path 'packaging/windows/service-control.ps1') `
|
||||||
|
-Mode uninstall -ServiceName $serviceName
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Windows 服务兜底清理失败,错误码: $LASTEXITCODE" }
|
||||||
|
}
|
||||||
|
if ($null -ne (Get-CimInstance -ClassName Win32_Service -Filter "Name='$serviceName'" -ErrorAction SilentlyContinue)) {
|
||||||
|
throw 'Windows 安装器卸载后服务仍然存在'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: 准备唯一 Windows 构建产物
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$artifactDir = 'dist/windows-artifact'
|
||||||
|
New-Item -ItemType Directory -Force -Path $artifactDir | Out-Null
|
||||||
|
Copy-Item -LiteralPath 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe' -Destination $artifactDir
|
||||||
|
$artifactFiles = @(Get-ChildItem -LiteralPath $artifactDir -Recurse -File)
|
||||||
|
if ($artifactFiles.Count -ne 1 -or $artifactFiles[0].Name -ne 'Ydisks-Xianyu-Helper-Setup.exe') {
|
||||||
|
throw "Windows 构建产物必须且只能包含安装器: $($artifactFiles.FullName -join ', ')"
|
||||||
|
}
|
||||||
|
|
||||||
- name: 上传 Windows 安装包
|
- name: 上传 Windows 安装包
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
|
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
|
||||||
path: |
|
path: dist/windows-artifact/Ydisks-Xianyu-Helper-Setup.exe
|
||||||
dist/windows/Ydisks-Xianyu-Helper-Setup.exe
|
|
||||||
dist/windows/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-binaries.zip
|
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
macos:
|
macos:
|
||||||
name: macOS 安装包
|
name: macOS 安装包
|
||||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
needs: prepare
|
||||||
runs-on: macos-14
|
runs-on: macos-14
|
||||||
|
env:
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
BUILD_VERSION: ${{ needs.prepare.outputs.build_version }}
|
||||||
|
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
|
||||||
steps:
|
steps:
|
||||||
- name: 检出代码
|
- name: 检出代码
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -303,7 +614,7 @@ jobs:
|
|||||||
- name: 配置 Node.js
|
- name: 配置 Node.js
|
||||||
uses: actions/setup-node@v6
|
uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 24
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
@@ -316,8 +627,9 @@ jobs:
|
|||||||
- name: 编译 macOS 桌面程序
|
- name: 编译 macOS 桌面程序
|
||||||
run: |
|
run: |
|
||||||
mkdir -p dist/macos/arm64 dist/macos/amd64
|
mkdir -p dist/macos/arm64 dist/macos/amd64
|
||||||
|
version_ldflags="-s -w -X xianyu-go/internal/version.Version=$BUILD_VERSION -X xianyu-go/internal/version.Commit=$GITHUB_SHA -X xianyu-go/internal/version.BuildTime=$BUILD_TIME"
|
||||||
for arch in arm64 amd64; do
|
for arch in arm64 amd64; do
|
||||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-server" ./cmd/server
|
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags="$version_ldflags" -o "dist/macos/$arch/xianyu-server" ./cmd/server
|
||||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/browser-install" ./cmd/browser-install
|
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/browser-install" ./cmd/browser-install
|
||||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-tray" ./cmd/tray
|
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-tray" ./cmd/tray
|
||||||
done
|
done
|
||||||
@@ -329,7 +641,7 @@ jobs:
|
|||||||
path: |
|
path: |
|
||||||
dist/macos/playwright-runtime/arm64
|
dist/macos/playwright-runtime/arm64
|
||||||
dist/macos/playwright-runtime/amd64
|
dist/macos/playwright-runtime/amd64
|
||||||
key: ydisks-playwright-runtime-v6-macos-universal-${{ hashFiles('go.mod', 'go.sum') }}
|
key: ydisks-playwright-runtime-v6-macos-mac14-universal-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||||
|
|
||||||
- name: 预下载 macOS Chromium runtime
|
- name: 预下载 macOS Chromium runtime
|
||||||
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
||||||
@@ -348,6 +660,34 @@ jobs:
|
|||||||
-driver-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-driver" \
|
-driver-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-driver" \
|
||||||
-browser-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-browsers"
|
-browser-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-browsers"
|
||||||
|
|
||||||
|
- name: 校验 macOS Chromium runtime
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
for runtime_arch in arm64 amd64; do
|
||||||
|
runtime_dir="dist/macos/playwright-runtime/$runtime_arch"
|
||||||
|
node_path="$runtime_dir/playwright-driver/node"
|
||||||
|
spec_path="$PWD/$runtime_dir/playwright-driver/package/browsers.json"
|
||||||
|
test -x "$node_path"
|
||||||
|
test -f "$runtime_dir/playwright-driver/package/cli.js"
|
||||||
|
test -f "$spec_path"
|
||||||
|
chromium_revision="$(RUNTIME_SPEC="$spec_path" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||||
|
headless_revision="$(RUNTIME_SPEC="$spec_path" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
||||||
|
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
||||||
|
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
||||||
|
chromium_path="$(find "$runtime_dir/playwright-browsers/chromium-$chromium_revision" -type f -path '*/Contents/MacOS/Google Chrome for Testing' -print -quit)"
|
||||||
|
headless_path="$(find "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision" -type f -name chrome-headless-shell -print -quit)"
|
||||||
|
test -n "$chromium_path"
|
||||||
|
test -n "$headless_path"
|
||||||
|
node_type="$(file -b "$node_path")"
|
||||||
|
chromium_type="$(file -b "$chromium_path")"
|
||||||
|
headless_type="$(file -b "$headless_path")"
|
||||||
|
case "$runtime_arch:$node_type:$chromium_type:$headless_type" in
|
||||||
|
arm64:*arm64*:*arm64*:*arm64*) ;;
|
||||||
|
amd64:*x86_64*:*x86_64*:*x86_64*) ;;
|
||||||
|
*) echo "macOS Playwright runtime 架构错误:$runtime_arch / $node_type / $chromium_type / $headless_type" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
- name: 保存 macOS Chromium runtime 缓存
|
- name: 保存 macOS Chromium runtime 缓存
|
||||||
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
||||||
uses: actions/cache/save@v5
|
uses: actions/cache/save@v5
|
||||||
|
|||||||
@@ -4,8 +4,14 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
- codex/desktop-packaging
|
- dev
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
app_version:
|
||||||
|
description: 正式发布版本号(不含 v)
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -16,8 +22,62 @@ concurrency:
|
|||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
verify:
|
||||||
|
name: Docker 发布测试门禁
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
outputs:
|
||||||
|
app_version: ${{ steps.version.outputs.app_version }}
|
||||||
|
build_time: ${{ steps.version.outputs.build_time }}
|
||||||
|
steps:
|
||||||
|
- name: 准备构建版本
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
if [ -n "${{ inputs.app_version }}" ]; then
|
||||||
|
app_version="${{ inputs.app_version }}"
|
||||||
|
else
|
||||||
|
app_version="${GITHUB_REF_NAME}-${GITHUB_SHA::12}"
|
||||||
|
fi
|
||||||
|
if [ -n "${{ inputs.app_version }}" ] && [[ ! "$app_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "正式版本必须符合 1.2.3 格式:$app_version" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "app_version=$app_version" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: 配置 Go
|
||||||
|
uses: actions/setup-go@v7
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: 配置 Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
|
- name: 验证前端
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
npm ci --prefix frontend
|
||||||
|
npm run typecheck --prefix frontend
|
||||||
|
npm test --prefix frontend
|
||||||
|
npm run build --prefix frontend
|
||||||
|
|
||||||
|
- name: 验证 Go 服务
|
||||||
|
run: |
|
||||||
|
go vet ./...
|
||||||
|
go test ./...
|
||||||
|
|
||||||
build:
|
build:
|
||||||
name: 构建镜像 (${{ matrix.arch }})
|
name: 构建镜像 (${{ matrix.arch }})
|
||||||
|
needs: verify
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
@@ -57,12 +117,17 @@ jobs:
|
|||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
- name: 缓存 Docker Chromium runtime
|
- name: 配置 Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
|
||||||
|
- name: 恢复 Docker Chromium runtime 缓存
|
||||||
id: cache-docker-playwright
|
id: cache-docker-playwright
|
||||||
uses: actions/cache@v5
|
uses: actions/cache/restore@v5
|
||||||
with:
|
with:
|
||||||
path: .docker/playwright-runtime/${{ matrix.arch }}
|
path: .docker/playwright-runtime/${{ matrix.arch }}
|
||||||
key: ydisks-playwright-runtime-v6-docker-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
|
key: ydisks-playwright-runtime-v6-docker-${{ matrix.arch }}-${{ matrix.playwright_platform }}-${{ hashFiles('go.mod', 'go.sum', 'cmd/browser-install/**') }}
|
||||||
|
|
||||||
- name: 准备 Docker Chromium runtime
|
- name: 准备 Docker Chromium runtime
|
||||||
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
|
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
|
||||||
@@ -92,11 +157,18 @@ jobs:
|
|||||||
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
||||||
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
||||||
test -n "$chromium_path"
|
test -n "$chromium_path"
|
||||||
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
chromium_revision="$(RUNTIME_SPEC="$PWD/$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||||
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
headless_revision="$(RUNTIME_SPEC="$PWD/$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
||||||
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
||||||
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
||||||
|
|
||||||
|
- name: 保存 Docker Chromium runtime 缓存
|
||||||
|
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
|
||||||
|
uses: actions/cache/save@v5
|
||||||
|
with:
|
||||||
|
path: .docker/playwright-runtime/${{ matrix.arch }}
|
||||||
|
key: ${{ steps.cache-docker-playwright.outputs.cache-primary-key }}
|
||||||
|
|
||||||
- name: 配置 Docker Buildx
|
- name: 配置 Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v4
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
@@ -119,12 +191,58 @@ jobs:
|
|||||||
context: .
|
context: .
|
||||||
file: Dockerfile.debian13
|
file: Dockerfile.debian13
|
||||||
platforms: ${{ matrix.platform }}
|
platforms: ${{ matrix.platform }}
|
||||||
|
build-args: |
|
||||||
|
APP_VERSION=${{ needs.verify.outputs.app_version }}
|
||||||
|
VCS_REF=${{ github.sha }}
|
||||||
|
BUILD_TIME=${{ needs.verify.outputs.build_time }}
|
||||||
outputs: type=image,name=${{ steps.image.outputs.name }},push-by-digest=true,name-canonical=true,push=true
|
outputs: type=image,name=${{ steps.image.outputs.name }},push-by-digest=true,name-canonical=true,push=true
|
||||||
cache-from: type=gha,scope=ydisks-docker-${{ matrix.arch }}
|
cache-from: type=gha,scope=ydisks-docker-${{ matrix.arch }}
|
||||||
cache-to: type=gha,mode=max,scope=ydisks-docker-${{ matrix.arch }}
|
cache-to: type=gha,mode=max,scope=ydisks-docker-${{ matrix.arch }}
|
||||||
provenance: mode=max
|
provenance: mode=max
|
||||||
sbom: true
|
sbom: true
|
||||||
|
|
||||||
|
- name: 验证待发布镜像中的 Chromium 与服务
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
IMAGE_NAME: ${{ steps.image.outputs.name }}
|
||||||
|
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
image_ref="$IMAGE_NAME@$IMAGE_DIGEST"
|
||||||
|
docker pull "$image_ref"
|
||||||
|
|
||||||
|
docker run --rm --entrypoint sh "$image_ref" -ec '
|
||||||
|
chromium_path="$(find /ms-playwright/chromium-* -type f \
|
||||||
|
-name chrome -perm -111 -print -quit)"
|
||||||
|
test -n "$chromium_path"
|
||||||
|
timeout 45 "$chromium_path" \
|
||||||
|
--headless --no-sandbox --disable-gpu --disable-dev-shm-usage \
|
||||||
|
--dump-dom about:blank | grep -q "<html"
|
||||||
|
'
|
||||||
|
|
||||||
|
container_id="$(docker run -d -p 127.0.0.1::59188 "$image_ref")"
|
||||||
|
cleanup() {
|
||||||
|
docker logs "$container_id" || true
|
||||||
|
docker rm -f "$container_id" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
host_port="$(docker port "$container_id" 59188/tcp | sed -n 's/.*://p' | head -n 1)"
|
||||||
|
test -n "$host_port"
|
||||||
|
for attempt in $(seq 1 60); do
|
||||||
|
if health="$(curl --fail --silent --show-error "http://127.0.0.1:$host_port/health" 2>/dev/null)"; then
|
||||||
|
printf '%s' "$health" | grep -q '"status":"ok"'
|
||||||
|
printf '%s' "$health" | grep -q '"database":"ok"'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
if ! docker inspect -f '{{.State.Running}}' "$container_id" | grep -q true; then
|
||||||
|
echo '待发布镜像中的服务提前退出。' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
echo '待发布镜像未能在 60 秒内通过健康检查。' >&2
|
||||||
|
exit 1
|
||||||
|
|
||||||
- name: 保存镜像摘要
|
- name: 保存镜像摘要
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
@@ -140,10 +258,11 @@ jobs:
|
|||||||
name: ydisks-docker-digest-${{ matrix.arch }}
|
name: ydisks-docker-digest-${{ matrix.arch }}
|
||||||
path: dist/digests/*
|
path: dist/digests/*
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 1
|
retention-days: 30
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
name: 合并多架构镜像
|
name: 合并多架构镜像
|
||||||
|
if: inputs.app_version == ''
|
||||||
needs: build
|
needs: build
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
steps:
|
steps:
|
||||||
@@ -175,13 +294,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
images: ${{ steps.image.outputs.name }}
|
images: ${{ steps.image.outputs.name }}
|
||||||
tags: |
|
tags: |
|
||||||
type=semver,pattern={{version}}
|
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
|
||||||
type=sha,format=long
|
type=sha,format=long
|
||||||
type=raw,value=main,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=main,enable=${{ github.ref == 'refs/heads/main' }}
|
||||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }}
|
||||||
type=raw,value=desktop-packaging,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
|
|
||||||
type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
|
|
||||||
|
|
||||||
- name: 创建并推送多架构 manifest
|
- name: 创建并推送多架构 manifest
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
name: 发布正式版本
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*.*.*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: release-${{ github.ref }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
prepare:
|
||||||
|
name: 校验正式版本
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
outputs:
|
||||||
|
app_version: ${{ steps.version.outputs.app_version }}
|
||||||
|
steps:
|
||||||
|
- name: 检出完整 Git 历史
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: 校验标签、来源与版本顺序
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
if [[ ! "$GITHUB_REF_NAME" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||||
|
echo "正式版本标签必须符合 v1.2.3 格式:$GITHUB_REF_NAME" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
git fetch origin main --no-tags
|
||||||
|
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
|
||||||
|
echo "正式版本标签必须指向 main 已包含的提交。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
newest_tag="$(git tag --list | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
|
||||||
|
if [ "$newest_tag" != "$GITHUB_REF_NAME" ]; then
|
||||||
|
echo "拒绝用旧版本 $GITHUB_REF_NAME 覆盖 latest;当前最高版本是 $newest_tag。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "app_version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
desktop:
|
||||||
|
name: 构建桌面端安装包
|
||||||
|
needs: prepare
|
||||||
|
uses: ./.github/workflows/desktop-cd.yml
|
||||||
|
with:
|
||||||
|
app_version: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
docker:
|
||||||
|
name: 构建 Docker 镜像
|
||||||
|
needs: prepare
|
||||||
|
uses: ./.github/workflows/docker-publish.yml
|
||||||
|
with:
|
||||||
|
app_version: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
publish:
|
||||||
|
name: 审批并发布正式版本
|
||||||
|
needs:
|
||||||
|
- prepare
|
||||||
|
- desktop
|
||||||
|
- docker
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
environment:
|
||||||
|
name: production-release
|
||||||
|
steps:
|
||||||
|
- name: 检出正式版本代码
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: 下载全部构建产物
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
pattern: ydisks-*
|
||||||
|
path: dist/artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: 校验桌面产物并生成校验和
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
mkdir -p dist/release dist/digests
|
||||||
|
|
||||||
|
echo "下载后的构建产物:"
|
||||||
|
find dist/artifacts -maxdepth 2 -type f -printf '%P\n' | sort
|
||||||
|
|
||||||
|
expected_release_files=(
|
||||||
|
"ydisks-xianyu-helper-linux-amd64-$APP_VERSION.tar.gz"
|
||||||
|
"ydisks-xianyu-helper-linux-arm64-$APP_VERSION.tar.gz"
|
||||||
|
"Ydisks-Xianyu-Helper-Setup.exe"
|
||||||
|
"Ydisks-Xianyu-Helper-$APP_VERSION-arm64.pkg"
|
||||||
|
"Ydisks-Xianyu-Helper-$APP_VERSION-amd64.pkg"
|
||||||
|
)
|
||||||
|
for release_file in "${expected_release_files[@]}"; do
|
||||||
|
source_file="dist/artifacts/$release_file"
|
||||||
|
if [ ! -f "$source_file" ]; then
|
||||||
|
echo "缺少正式发布产物:$release_file" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
cp -- "$source_file" dist/release/
|
||||||
|
done
|
||||||
|
|
||||||
|
digest_count=0
|
||||||
|
while IFS= read -r artifact_file; do
|
||||||
|
artifact_name="$(basename "$artifact_file")"
|
||||||
|
if [[ "$artifact_name" =~ ^[0-9a-f]{64}$ ]]; then
|
||||||
|
cp -- "$artifact_file" dist/digests/
|
||||||
|
digest_count=$((digest_count + 1))
|
||||||
|
fi
|
||||||
|
done < <(find dist/artifacts -maxdepth 2 -type f -print)
|
||||||
|
if [ "$digest_count" -ne 2 ]; then
|
||||||
|
echo "Docker 镜像摘要数量错误:预期 2 个,实际 $digest_count 个。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "准备发布的桌面产物:"
|
||||||
|
find dist/release -maxdepth 1 -type f -printf '%f\n' | sort
|
||||||
|
echo "准备发布的 Docker 摘要:"
|
||||||
|
find dist/digests -maxdepth 1 -type f -printf '%f\n' | sort
|
||||||
|
(cd dist/release && sha256sum * > SHA256SUMS)
|
||||||
|
|
||||||
|
- name: 配置 Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
|
- name: 登录 GitHub Container Registry
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: 发布正式 Docker manifest
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
image_name="ghcr.io/${GITHUB_REPOSITORY,,}"
|
||||||
|
minor_version="${APP_VERSION%.*}"
|
||||||
|
digest_args=()
|
||||||
|
while IFS= read -r digest_file; do
|
||||||
|
digest_args+=("$image_name@sha256:$(basename "$digest_file")")
|
||||||
|
done < <(find dist/digests -maxdepth 1 -type f -print | sort)
|
||||||
|
docker buildx imagetools create \
|
||||||
|
--tag "$image_name:$GITHUB_REF_NAME" \
|
||||||
|
--tag "$image_name:$APP_VERSION" \
|
||||||
|
--tag "$image_name:$minor_version" \
|
||||||
|
--tag "$image_name:latest" \
|
||||||
|
--tag "$image_name:sha-$GITHUB_SHA" \
|
||||||
|
"${digest_args[@]}"
|
||||||
|
docker buildx imagetools inspect "$image_name:$GITHUB_REF_NAME"
|
||||||
|
docker buildx imagetools inspect "$image_name:latest"
|
||||||
|
|
||||||
|
- name: 创建或更新 GitHub Release
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
APP_VERSION: ${{ needs.prepare.outputs.app_version }}
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
release_notes_file="dist/release-notes.md"
|
||||||
|
git log -1 --format='提交:%h%n%n%B' "$GITHUB_REF_NAME" > "$release_notes_file"
|
||||||
|
if [ ! -s "$release_notes_file" ]; then
|
||||||
|
printf '%s\n' '本版本提交未提供 release notes。' > "$release_notes_file"
|
||||||
|
fi
|
||||||
|
mapfile -t release_files < <(find dist/release -maxdepth 1 -type f -print | sort)
|
||||||
|
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||||
|
gh release edit "$GITHUB_REF_NAME" \
|
||||||
|
--title "Ydisks 闲鱼助手 $APP_VERSION" \
|
||||||
|
--notes-file "$release_notes_file"
|
||||||
|
gh release upload "$GITHUB_REF_NAME" "${release_files[@]}" --clobber
|
||||||
|
else
|
||||||
|
gh release create "$GITHUB_REF_NAME" "${release_files[@]}" \
|
||||||
|
--verify-tag \
|
||||||
|
--notes-file "$release_notes_file" \
|
||||||
|
--title "Ydisks 闲鱼助手 $APP_VERSION"
|
||||||
|
fi
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
*.test
|
*.test
|
||||||
!/Dockerfile.test
|
!/Dockerfile.test
|
||||||
*.out
|
*.out
|
||||||
|
/cmd/server/rsrc_windows_amd64.syso
|
||||||
|
/cmd/tray/rsrc_windows_amd64.syso
|
||||||
|
|
||||||
# Local deployment environment (keep secrets out of Git)
|
# Local deployment environment (keep secrets out of Git)
|
||||||
/.env
|
/.env
|
||||||
@@ -29,6 +31,7 @@
|
|||||||
|
|
||||||
# Frontend dependencies
|
# Frontend dependencies
|
||||||
/frontend/node_modules/
|
/frontend/node_modules/
|
||||||
|
/frontend/coverage/
|
||||||
/frontend/.env.local
|
/frontend/.env.local
|
||||||
/frontend/.env.*.local
|
/frontend/.env.*.local
|
||||||
/internal/server/data/
|
/internal/server/data/
|
||||||
|
|||||||
+5
-1
@@ -15,6 +15,7 @@ linters:
|
|||||||
- staticcheck # 综合静态分析(含原 gosimple 检查)
|
- staticcheck # 综合静态分析(含原 gosimple 检查)
|
||||||
- unused # 检测未使用的代码
|
- unused # 检测未使用的代码
|
||||||
- misspell # 拼写检查
|
- misspell # 拼写检查
|
||||||
|
- gocyclo # 检查函数分支复杂度,阶段 10 收口高风险热点
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
errcheck:
|
errcheck:
|
||||||
@@ -27,6 +28,9 @@ linters:
|
|||||||
- (*database/sql.DB).Close
|
- (*database/sql.DB).Close
|
||||||
- (*database/sql.Tx).Rollback
|
- (*database/sql.Tx).Rollback
|
||||||
- (*bufio.Writer).Flush
|
- (*bufio.Writer).Flush
|
||||||
|
gocyclo:
|
||||||
|
# 50 以上才视为需要结构拆分的生产热点;测试编排不以断言数量伪装业务复杂度债务。
|
||||||
|
min-complexity: 50
|
||||||
|
|
||||||
exclusions:
|
exclusions:
|
||||||
presets:
|
presets:
|
||||||
@@ -37,7 +41,7 @@ linters:
|
|||||||
linters: [errcheck, staticcheck, govet]
|
linters: [errcheck, staticcheck, govet]
|
||||||
# 测试代码允许在 setup 中忽略错误。
|
# 测试代码允许在 setup 中忽略错误。
|
||||||
- path: _test\.go
|
- path: _test\.go
|
||||||
linters: [errcheck]
|
linters: [errcheck, gocyclo]
|
||||||
# cmd/spike 是一次性诊断脚本,放宽要求。
|
# cmd/spike 是一次性诊断脚本,放宽要求。
|
||||||
- path: cmd/spike/
|
- path: cmd/spike/
|
||||||
linters: [errcheck]
|
linters: [errcheck]
|
||||||
|
|||||||
@@ -25,9 +25,14 @@ cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper
|
|||||||
|
|
||||||
make build # go build ./cmd/server
|
make build # go build ./cmd/server
|
||||||
make test # go test ./...
|
make test # go test ./...
|
||||||
|
make test-server # go test ./internal/server
|
||||||
|
make test-server-race # server 生命周期与凭证并发 smoke race
|
||||||
make vet # go vet ./...
|
make vet # go vet ./...
|
||||||
make lint # golangci-lint run ./... (0 issues baseline)
|
make lint # golangci-lint run ./... (0 issues baseline)
|
||||||
make check # vet + lint + test
|
make check # vet + lint + test
|
||||||
|
make cover # Go 全量覆盖率(默认不启动 Chromium)
|
||||||
|
make cover-browser # 本地 Chromium 页面与 CDP 覆盖率
|
||||||
|
make cover-frontend # 前端 V8 覆盖率(文本/JSON/HTML)
|
||||||
make frontend # build frontend into internal/webui/static
|
make frontend # build frontend into internal/webui/static
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -42,7 +47,7 @@ On a new database, open the management page after starting the server. The first
|
|||||||
and confirms an administrator password, creates the `admin` user, and signs the user in automatically.
|
and confirms an administrator password, creates the `admin` user, and signs the user in automatically.
|
||||||
The CLI bootstrap remains available for headless or operational environments.
|
The CLI bootstrap remains available for headless or operational environments.
|
||||||
|
|
||||||
Disable browser automation when Chromium is unavailable:
|
Disable browser automation only when the user explicitly requests it or explicitly confirms that Chromium is unavailable. Unless the user gives that direction, agents MUST NOT add `-no-browser` when starting the server:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
||||||
@@ -91,6 +96,173 @@ npm run dev
|
|||||||
|
|
||||||
Vite proxies backend routes to `localhost:59188`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
Vite proxies backend routes to `localhost:59188`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
||||||
|
|
||||||
|
## Mandatory refactoring governance — DO NOT SKIP
|
||||||
|
|
||||||
|
The repository is following the authoritative long-term plan in
|
||||||
|
`docs/architecture/refactoring-master-plan.md`. Before changing Go package boundaries, HTTP APIs, database
|
||||||
|
access, account credentials, application wiring, React page structure, tests, CI or compatibility behavior,
|
||||||
|
agents MUST read all of:
|
||||||
|
|
||||||
|
- `docs/architecture/refactoring-master-plan.md`
|
||||||
|
- `docs/architecture/dependency-rules.md`
|
||||||
|
- `docs/architecture/comment-standard.md`
|
||||||
|
- `docs/slider-captcha-frozen-spec.md` when credentials, login, engine, account, server or browser call paths are involved
|
||||||
|
|
||||||
|
The authoritative schedule has exactly six formal phases and is defined only by
|
||||||
|
`docs/architecture/refactoring-master-plan.md`. Before editing, read its state table. Do not infer a phase from
|
||||||
|
old commits, a document heading, implementation that happened to land early, or a historical completion claim.
|
||||||
|
|
||||||
|
Each phase is one task, one review unit and one final Chinese commit. A phase may change every package, feature,
|
||||||
|
test, gate and document required by its stated scope. Agents MUST NOT split it into vertical slices, milestones,
|
||||||
|
separately delivered subtasks, independent PRs, or intermediate commits. The worktree may be temporarily
|
||||||
|
non-compiling only while the single phase is in progress; its final commit must compile, start, pass every listed
|
||||||
|
verification and have complete evidence recorded once in `refactoring-progress.md`.
|
||||||
|
|
||||||
|
The complete architecture-gate catalog is established before production migration. `tools/architecturecheck`
|
||||||
|
reads the single current phase from the master plan, activates that phase and every earlier gate, and fails when
|
||||||
|
the phase state is missing or ambiguous. After phase six is complete, every gate remains permanently active.
|
||||||
|
Agents must not defer gate design to phase six, enable a future phase
|
||||||
|
early, or bypass an active gate with a whitelist, baseline, ignored path or warning-only result.
|
||||||
|
|
||||||
|
Do not use a large phase change to hide unfinished branches, error paths or unverified behavior. Do not weaken,
|
||||||
|
skip or delete tests; reformat or rename unrelated code; upgrade unrelated dependencies; delete coverage; expand
|
||||||
|
a compatibility whitelist; or change frozen CAPTCHA behavior. Preserve unrelated working-tree changes.
|
||||||
|
|
||||||
|
Compatibility adapters remain until every known caller has migrated and contract tests prove removal. Emergency
|
||||||
|
bug or security fixes may precede the plan only when narrowly scoped and recorded in the master plan.
|
||||||
|
|
||||||
|
## Mandatory Chinese comments for all functions and variables
|
||||||
|
|
||||||
|
`docs/architecture/comment-standard.md` is authoritative. This requirement is intentionally stricter than
|
||||||
|
normal Go exported-symbol documentation rules and applies to Go, TypeScript and TSX production and test code.
|
||||||
|
|
||||||
|
Agents MUST:
|
||||||
|
|
||||||
|
- add accurate Chinese comments for every new or modified function, method, anonymous function, parameter,
|
||||||
|
return value, package/module variable, constant, field, local variable, short declaration, loop variable,
|
||||||
|
callback parameter, React state value, setter, ref and memoized value;
|
||||||
|
- explain all variables in a multi-variable declaration in one nearby comment when appropriate;
|
||||||
|
- explain business meaning, input/output semantics, units, lifecycle, ownership, cancellation, concurrency,
|
||||||
|
sensitivity or compatibility constraints instead of translating the identifier or restating syntax;
|
||||||
|
- update comments in the same change whenever behavior or ownership changes;
|
||||||
|
- clear historical comment-baseline entries for every file or logical unit materially refactored;
|
||||||
|
- keep generated code, third-party code and `internal/webui/static` out of manual comment backfills.
|
||||||
|
|
||||||
|
Automated checks can prove only presence and Chinese text. Reviewers and agents remain responsible for semantic
|
||||||
|
accuracy. Placeholder comments such as “err 表示错误” or “count 表示数量” are forbidden. Comments must never
|
||||||
|
contain real Cookie, Token, password, SMTP credential or production secret values.
|
||||||
|
|
||||||
|
Until the historical baseline is removed, untouched legacy declarations may remain exempt, but no task may add
|
||||||
|
new debt or use the baseline to exempt newly created or semantically modified declarations.
|
||||||
|
|
||||||
|
Run `make comments` (or `go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json`
|
||||||
|
and `npm --prefix frontend run comments:check`) for the mandatory AST presence gate. Baseline regeneration is a
|
||||||
|
reviewed maintenance operation only: use `make comments-baseline` after clearing the affected file's historical
|
||||||
|
debt and record the scope in `docs/architecture/refactoring-master-plan.md`.
|
||||||
|
|
||||||
|
## Mandatory coverage policy
|
||||||
|
|
||||||
|
- Every new or modified deterministic function, branch and error path MUST have a focused test. Prefer injected
|
||||||
|
dependencies, local `httptest` servers, in-memory databases and local Playwright pages over real platform calls.
|
||||||
|
- Run `make cover` for the ordinary Go baseline, `make cover-browser` when Chromium is available, and
|
||||||
|
`make cover-frontend` for the React/Vite V8 report. Coverage reports are verification artifacts and MUST NOT be
|
||||||
|
committed (`cover*.out` and `frontend/coverage/` remain generated files).
|
||||||
|
- Do not exclude production business files, lower thresholds, mark business code as ignored, or weaken assertions
|
||||||
|
merely to improve a percentage. Per the current user requirement, pure React UI components are outside the business
|
||||||
|
coverage target and may be excluded by the frontend coverage configuration; their business behavior must remain in
|
||||||
|
tested Hook/state/service modules. Any remaining uncovered business code must be classified in the plan as
|
||||||
|
deterministic work, environment-only work, or real-account/external-platform work.
|
||||||
|
- Tests may skip only behavior that genuinely requires a real account, private platform state, or an unavailable
|
||||||
|
external service. Local browser behavior, error handling, cancellation, lifecycle, parsing and UI state transitions
|
||||||
|
MUST use deterministic fixtures and remain covered.
|
||||||
|
- A coverage claim MUST include the command, whether `RUN_BROWSER_INTEGRATION=1` was used, the Go and frontend
|
||||||
|
statement percentages, and the exact real-account/external-platform exceptions.
|
||||||
|
|
||||||
|
## Mandatory target dependency boundaries
|
||||||
|
|
||||||
|
`docs/architecture/dependency-rules.md` is authoritative. During migration, existing violations may remain only
|
||||||
|
until their recorded phase is completed; agents MUST NOT add new violations.
|
||||||
|
|
||||||
|
- `cmd` handles configuration, dependency construction, signals and lifecycle only; no new business rules, SQL,
|
||||||
|
HTTP handlers or protocol parsing belong there.
|
||||||
|
- `internal/server` is the HTTP/SPA transport. Do not add new direct `Store.DB`, transaction, MTOP, browser,
|
||||||
|
credential-renewal, business-worker or platform-session logic. New use cases go through application services.
|
||||||
|
- Application services own use-case orchestration, authorization and transaction boundaries and must not depend
|
||||||
|
on `net/http`, chi or frontend compatibility fields.
|
||||||
|
- Interfaces are defined by consumers and kept minimal. Do not add a service locator, universal repository
|
||||||
|
interface or runtime setter for a required dependency.
|
||||||
|
- `internal/db` owns SQL, dialects, migrations, encryption-at-rest and repository implementations. It must not
|
||||||
|
import upper layers or decide HTTP responses.
|
||||||
|
- `internal/xianyu` and `internal/browser` own platform and browser implementation. They must not write business
|
||||||
|
data directly, decide automation rules or depend on the HTTP/application layer.
|
||||||
|
- `internal/engine` and `internal/automation` must remain independent of Server. New mutable concurrent state
|
||||||
|
requires explicit ownership, lock, Context, goroutine and shutdown documentation plus focused tests.
|
||||||
|
- Cross-repository atomic work belongs behind an application-level Unit of Work. New handlers must not call
|
||||||
|
`BeginTx` directly.
|
||||||
|
|
||||||
|
## Mandatory sensitive-data boundaries
|
||||||
|
|
||||||
|
- Account summaries and ownership checks MUST NOT read or decrypt Cookie, Token, password or encrypted metadata.
|
||||||
|
- Platform credentials and password-login secrets use separate models and purpose-specific repository methods.
|
||||||
|
- Sensitive persistence models MUST NOT be serialized as HTTP responses or frontend state.
|
||||||
|
- Logs, notifications, API errors and test failure output MUST NOT contain plaintext credentials.
|
||||||
|
- New ownership checks return existence/non-sensitive identity rather than maps of decrypted Cookie values.
|
||||||
|
- Do not hold credential locks across slow external I/O unless an authoritative protocol invariant explicitly
|
||||||
|
requires it and the lock order is documented and tested.
|
||||||
|
|
||||||
|
## Mandatory HTTP API constraints
|
||||||
|
|
||||||
|
- New APIs use the `/api/v1` prefix unless the current task is an explicit compatibility fix.
|
||||||
|
- New request and response bodies use named DTOs. Do not add anonymous handler request structs, dynamic
|
||||||
|
`map[string]any` response contracts or direct DB-model serialization.
|
||||||
|
- New failures use the unified error envelope and correct HTTP status. Do not add HTTP 200 + `success:false` or
|
||||||
|
new `detail`/`msg`/`error` aliases.
|
||||||
|
- DB models, domain models and transport DTOs remain distinct. Compatibility normalization belongs only at the
|
||||||
|
transport adapter boundary.
|
||||||
|
- Route-prefix changes require `frontend/vite.config.ts`, frontend API callers, contract tests and embedded assets
|
||||||
|
to be updated together.
|
||||||
|
|
||||||
|
## Mandatory React constraints
|
||||||
|
|
||||||
|
- New frontend code follows `app -> features -> shared`; a feature must not import another feature's internal
|
||||||
|
files, and shared code must not import features.
|
||||||
|
- React components must not call `fetch` or `axios` directly. Use the shared HTTP client through a feature API
|
||||||
|
adapter; keep domain normalization out of the generic client.
|
||||||
|
- Do not store derivable values in state. Put user-triggered side effects in event handlers, split effects with
|
||||||
|
different dependencies, and use functional state updates when the next value depends on the previous value.
|
||||||
|
- Every async effect or request must define cancellation or latest-generation behavior so stale responses cannot
|
||||||
|
replace current state. Independent requests should start in parallel.
|
||||||
|
- Do not add memoization without a concrete expensive calculation or stable-child-prop reason. Do not define
|
||||||
|
child components inside parent components.
|
||||||
|
- Keep server data, form state and transient UI state separate. Heavy pages and heavy optional dependencies use
|
||||||
|
route/feature-level lazy loading where practical.
|
||||||
|
- New or materially changed user flows require behavior tests for success, failure, cancellation, switching and
|
||||||
|
stale responses. Source-string tests are reserved for static architecture rules.
|
||||||
|
- Generated API types are read-only; feature adapters convert transport DTOs to UI models.
|
||||||
|
|
||||||
|
## Mandatory database, transaction and multi-dialect constraints
|
||||||
|
|
||||||
|
- Do not expose new raw `*sql.DB` access to upper layers. Add narrow repository methods or an explicit Unit of
|
||||||
|
Work instead.
|
||||||
|
- SQL row structs, persistence models, domain models and HTTP DTOs must not be collapsed into one convenience
|
||||||
|
type when they have different sensitivity or ownership.
|
||||||
|
- Every migration keeps SQLite, MySQL and PostgreSQL numbering and final schema aligned.
|
||||||
|
- Database behavior changes require focused SQLite tests and, when available, MySQL/Postgres regression or
|
||||||
|
`cmd/dbverify` evidence.
|
||||||
|
- Repository/package splitting is permitted only after consumer interfaces and transaction boundaries are clear;
|
||||||
|
directory count is not a goal and package cycles must not be hidden behind globals or reflection.
|
||||||
|
|
||||||
|
## Mandatory lifecycle and concurrency constraints
|
||||||
|
|
||||||
|
- Background goroutines require a documented owner, Context source, cancellation path and Wait/Join path.
|
||||||
|
- Start methods must not make partially constructed objects observable. Stop/Close must be idempotent when the
|
||||||
|
component contract allows repeated shutdown.
|
||||||
|
- The sender closes a channel unless a more specific documented ownership rule applies.
|
||||||
|
- Do not perform uncontrolled network, browser or user-wait I/O while holding a mutex.
|
||||||
|
- Types with concurrent use must document which locks protect which fields and the allowed lock order.
|
||||||
|
- Required dependencies are constructor inputs and validated before Start; mutable setters are only for optional
|
||||||
|
runtime configuration or isolated tests and must not create an invalid intermediate production state.
|
||||||
|
|
||||||
## Desktop packaging and service behavior
|
## Desktop packaging and service behavior
|
||||||
|
|
||||||
The application defaults to port `59188`; commands using `-addr :59188` listen on all interfaces. Desktop
|
The application defaults to port `59188`; commands using `-addr :59188` listen on all interfaces. Desktop
|
||||||
@@ -107,11 +279,16 @@ packages explicitly bind the server to `127.0.0.1:59188` and keep the server and
|
|||||||
|
|
||||||
All desktop packages contain the matching Playwright driver, Chromium and headless shell. Do not add a
|
All desktop packages contain the matching Playwright driver, Chromium and headless shell. Do not add a
|
||||||
Debian Chromium package or download a second browser during installation. The Docker final image uses
|
Debian Chromium package or download a second browser during installation. The Docker final image uses
|
||||||
`node:latest`, copies the cached runtime prepared by CI, and does not run `apt-get update`. The desktop CI workflow
|
`node:24-trixie-slim`, copies the cached runtime prepared by CI, installs only the Chromium system libraries
|
||||||
runs on `main` and `codex/desktop-packaging`; Linux amd64 and arm64 jobs use native GitHub-hosted runners and
|
through the bundled Playwright driver, and clears apt indexes and temporary caches in the same image layer.
|
||||||
|
The desktop CI workflow runs on `main` and `dev`; formal desktop builds are invoked by the unified
|
||||||
|
`release.yml` workflow for `v*.*.*` version tags. Linux amd64 and arm64 jobs use native GitHub-hosted runners and
|
||||||
must not use QEMU or cross-architecture emulation. Docker publishing also builds each architecture on its native
|
must not use QEMU or cross-architecture emulation. Docker publishing also builds each architecture on its native
|
||||||
runner and publishes `main` and `latest` from `main`, `desktop-packaging` and `alpha` from
|
runner: branch builds publish `main` or `dev` plus a full-commit `sha-*` tag, while formal builds publish semantic
|
||||||
`codex/desktop-packaging`.
|
version tags, `latest`, and the full-commit `sha-*` tag only after the `production-release` Environment approval.
|
||||||
|
Version tags create a GitHub Release containing all platform packages and SHA-256 checksums. Never publish a Docker
|
||||||
|
manifest until Go/frontend tests, an actual Chromium launch, and the packaged server health check have passed for
|
||||||
|
every architecture.
|
||||||
|
|
||||||
The tray state machine is shared by Windows and macOS: it serializes actions, shows transition states,
|
The tray state machine is shared by Windows and macOS: it serializes actions, shows transition states,
|
||||||
waits for a healthy `/health` response after start/restart, waits for the endpoint to become unreachable
|
waits for a healthy `/health` response after start/restart, waits for the endpoint to become unreachable
|
||||||
@@ -171,6 +348,10 @@ the directory containing `install.sh`, `uninstall.sh`, the systemd unit, binarie
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
|
The following paragraphs describe the current runtime wiring. They are not permission to add more business
|
||||||
|
logic to HTTP handlers. The mandatory target architecture and the allowed transition path are defined in
|
||||||
|
`docs/architecture/refactoring-master-plan.md` and `docs/architecture/dependency-rules.md`.
|
||||||
|
|
||||||
`cmd/server/main.go` opens the database (SQLite/MySQL/Postgres by URL scheme), constructs the adapter + account manager + automation center + notifier, starts enabled account runtimes, initializes the optional in-process browser manager, and starts the HTTP server. Business logic does not live in `main.go` — it delegates to `internal/adapter` (Handler/OrderDetailFetcher wiring), `internal/engine`, `internal/account`, `internal/automation`, and domain-specific server handlers.
|
`cmd/server/main.go` opens the database (SQLite/MySQL/Postgres by URL scheme), constructs the adapter + account manager + automation center + notifier, starts enabled account runtimes, initializes the optional in-process browser manager, and starts the HTTP server. Business logic does not live in `main.go` — it delegates to `internal/adapter` (Handler/OrderDetailFetcher wiring), `internal/engine`, `internal/account`, `internal/automation`, and domain-specific server handlers.
|
||||||
|
|
||||||
`internal/xianyu` owns lower-level platform integration:
|
`internal/xianyu` owns lower-level platform integration:
|
||||||
|
|||||||
+25
-5
@@ -1,6 +1,6 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
|
|
||||||
FROM --platform=$BUILDPLATFORM node:latest AS frontend
|
FROM --platform=$BUILDPLATFORM node:24-trixie-slim AS frontend
|
||||||
WORKDIR /src/frontend
|
WORKDIR /src/frontend
|
||||||
COPY frontend/package*.json ./
|
COPY frontend/package*.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
@@ -10,12 +10,17 @@ RUN npm run build
|
|||||||
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
|
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
|
||||||
ARG TARGETOS
|
ARG TARGETOS
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
|
ARG APP_VERSION=dev
|
||||||
|
ARG VCS_REF=unknown
|
||||||
|
ARG BUILD_TIME=unknown
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
|
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
|
||||||
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
|
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath \
|
||||||
|
-ldflags="-s -w -X xianyu-go/internal/version.Version=$APP_VERSION -X xianyu-go/internal/version.Commit=$VCS_REF -X xianyu-go/internal/version.BuildTime=$BUILD_TIME" \
|
||||||
|
-o /out/xianyu-server ./cmd/server \
|
||||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
|
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
|
||||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
|
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
|
||||||
|
|
||||||
@@ -30,7 +35,7 @@ RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/browser-install-ho
|
|||||||
|
|
||||||
# Docker CI 会把与独立安装包相同的目标架构 runtime 放到
|
# Docker CI 会把与独立安装包相同的目标架构 runtime 放到
|
||||||
# .docker/playwright-runtime,构建时直接复制,不在 Dockerfile 内重复下载浏览器。
|
# .docker/playwright-runtime,构建时直接复制,不在 Dockerfile 内重复下载浏览器。
|
||||||
FROM --platform=$BUILDPLATFORM node:latest AS playwright-runtime
|
FROM --platform=$BUILDPLATFORM node:24-trixie-slim AS playwright-runtime
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
||||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||||
@@ -63,19 +68,34 @@ RUN set -eux; \
|
|||||||
test -d "/ms-playwright/chromium_headless_shell-$headless_revision"; \
|
test -d "/ms-playwright/chromium_headless_shell-$headless_revision"; \
|
||||||
find /ms-playwright -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .
|
find /ms-playwright -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .
|
||||||
|
|
||||||
FROM node:latest AS runtime
|
FROM node:24-trixie-slim AS runtime
|
||||||
ENV TZ=Asia/Shanghai
|
ENV TZ=Asia/Shanghai
|
||||||
ENV BROWSER_HEADLESS=true
|
ENV BROWSER_HEADLESS=true
|
||||||
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
||||||
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
|
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
|
||||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||||
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||||
|
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=backend /out/xianyu-server /app/xianyu-server
|
COPY --from=backend /out/xianyu-server /app/xianyu-server
|
||||||
COPY --from=backend /out/xianyu-dbseed /app/xianyu-dbseed
|
COPY --from=backend /out/xianyu-dbseed /app/xianyu-dbseed
|
||||||
COPY --from=backend /out/xianyu-dbverify /app/xianyu-dbverify
|
COPY --from=backend /out/xianyu-dbverify /app/xianyu-dbverify
|
||||||
COPY --from=playwright-runtime /ms-playwright-go /ms-playwright-go
|
COPY --from=playwright-runtime /ms-playwright-go /ms-playwright-go
|
||||||
COPY --from=playwright-runtime /ms-playwright /ms-playwright
|
COPY --from=playwright-runtime /ms-playwright /ms-playwright
|
||||||
RUN mkdir -p /app/data /app/browser_data
|
# 浏览器文件本身不包含 Linux 动态链接库。使用与 runtime 同捆的 Playwright
|
||||||
|
# driver 只安装 Chromium 所需系统依赖,并在同一镜像层清理 apt/npm/临时缓存。
|
||||||
|
RUN set -eux; \
|
||||||
|
node /ms-playwright-go/package/cli.js install-deps chromium; \
|
||||||
|
apt-get update; \
|
||||||
|
apt-get install --reinstall -y --no-install-recommends ca-certificates; \
|
||||||
|
update-ca-certificates --fresh; \
|
||||||
|
test -s "$SSL_CERT_FILE"; \
|
||||||
|
grep -q -- '-----BEGIN CERTIFICATE-----' "$SSL_CERT_FILE"; \
|
||||||
|
test -x "$PLAYWRIGHT_NODEJS_PATH"; \
|
||||||
|
test -f "$PLAYWRIGHT_DRIVER_PATH/package/cli.js"; \
|
||||||
|
find "$PLAYWRIGHT_BROWSERS_PATH" -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .; \
|
||||||
|
apt-get clean; \
|
||||||
|
rm -rf /var/lib/apt/lists/* /var/cache/apt/* /root/.cache /tmp/* /var/tmp/*; \
|
||||||
|
mkdir -p /app/data /app/browser_data
|
||||||
EXPOSE 59188
|
EXPOSE 59188
|
||||||
CMD ["/app/xianyu-server", "-addr", ":59188"]
|
CMD ["/app/xianyu-server", "-addr", ":59188"]
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
FROM alpine:3.22 AS sqlite-tools
|
FROM alpine:3.22 AS sqlite-tools
|
||||||
RUN apk add --no-cache sqlite
|
RUN apk add --no-cache sqlite
|
||||||
|
|
||||||
FROM node:latest AS frontend-assets
|
FROM node:24-trixie-slim AS frontend-assets
|
||||||
WORKDIR /src/frontend
|
WORKDIR /src/frontend
|
||||||
COPY frontend/package*.json ./
|
COPY frontend/package*.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
@@ -24,7 +24,7 @@ COPY . .
|
|||||||
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
|
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
|
||||||
CMD ["golangci-lint", "run", "./..."]
|
CMD ["golangci-lint", "run", "./..."]
|
||||||
|
|
||||||
FROM node:latest AS frontend-test
|
FROM node:24-trixie-slim AS frontend-test
|
||||||
WORKDIR /src/frontend
|
WORKDIR /src/frontend
|
||||||
COPY frontend/package*.json ./
|
COPY frontend/package*.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
GO ?= go
|
GO ?= go
|
||||||
GOLANGCI_LINT ?= golangci-lint
|
GOLANGCI_LINT ?= golangci-lint
|
||||||
|
|
||||||
.PHONY: build build-int build-browser-install build-tray test test-int vet lint cover tidy frontend fmt check
|
.PHONY: build build-int build-browser-install build-tray test test-server test-server-race test-multidb test-int vet lint architecture cover cover-browser cover-frontend tidy frontend fmt comments check
|
||||||
|
|
||||||
## build: 编译 server(默认,跳过 integration build tag)
|
## build: 编译 server(默认,跳过 integration build tag)
|
||||||
build:
|
build:
|
||||||
@@ -25,6 +25,20 @@ build-int:
|
|||||||
test:
|
test:
|
||||||
$(GO) test ./...
|
$(GO) test ./...
|
||||||
|
|
||||||
|
## test-server: 跑 HTTP server 全量单元测试
|
||||||
|
test-server:
|
||||||
|
$(GO) test ./internal/server
|
||||||
|
|
||||||
|
## test-server-race: 跑已验证的 server 生命周期与凭证并发 race 子集
|
||||||
|
test-server-race:
|
||||||
|
$(GO) test -race ./internal/server -run 'TestRun_|TestPublishWorkerTrackingWaitsForCompletion|TestPublishRecoveryLifecycleStopsBeforeWorkerWait|TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager|TestSetCookieStatusWaitsForCredentialTransition|TestDeleteCookieRechecksOwnershipInsideCredentialLock'
|
||||||
|
|
||||||
|
## test-multidb: 严格执行 SQLite、MySQL、PostgreSQL 三方言回归;缺少任一外部 URL 时明确失败
|
||||||
|
test-multidb:
|
||||||
|
@test -n "$${TEST_MYSQL_URL:-}" || (echo '缺少 TEST_MYSQL_URL,无法执行 MySQL 实测' >&2; exit 2)
|
||||||
|
@test -n "$${TEST_POSTGRES_URL:-}" || (echo '缺少 TEST_POSTGRES_URL,无法执行 PostgreSQL 实测' >&2; exit 2)
|
||||||
|
REQUIRE_MULTIDB=1 $(GO) test ./internal/db -run '^TestMultiDB_' -v -count=1
|
||||||
|
|
||||||
## test-int: 带 integration tag 跑测试(含 browser,需 Chromium)
|
## test-int: 带 integration tag 跑测试(含 browser,需 Chromium)
|
||||||
test-int:
|
test-int:
|
||||||
$(GO) test -tags integration ./...
|
$(GO) test -tags integration ./...
|
||||||
@@ -37,10 +51,22 @@ vet:
|
|||||||
lint:
|
lint:
|
||||||
$(GOLANGCI_LINT) run ./...
|
$(GOLANGCI_LINT) run ./...
|
||||||
|
|
||||||
|
## architecture: 按总计划当前阶段启用完整架构规则目录中的对应门禁
|
||||||
|
architecture:
|
||||||
|
$(GO) run ./tools/architecturecheck
|
||||||
|
|
||||||
## cover: 生成覆盖率报告
|
## cover: 生成覆盖率报告
|
||||||
cover:
|
cover:
|
||||||
$(GO) test -coverprofile=cover.out ./... && $(GO) tool cover -func=cover.out | tail -1
|
$(GO) test -coverprofile=cover.out ./... && $(GO) tool cover -func=cover.out | tail -1
|
||||||
|
|
||||||
|
## cover-browser: 在本地 Chromium 可用时补齐浏览器页面与 CDP 集成覆盖率
|
||||||
|
cover-browser:
|
||||||
|
RUN_BROWSER_INTEGRATION=1 $(GO) test -coverprofile=cover-browser.out ./internal/browser && $(GO) tool cover -func=cover-browser.out | tail -1
|
||||||
|
|
||||||
|
## cover-frontend: 生成前端 V8 覆盖率报告(文本、JSON 摘要和 HTML)
|
||||||
|
cover-frontend:
|
||||||
|
npm run test:coverage --prefix frontend
|
||||||
|
|
||||||
## fmt: 格式化所有 Go 源码
|
## fmt: 格式化所有 Go 源码
|
||||||
fmt:
|
fmt:
|
||||||
$(GO) fmt ./...
|
$(GO) fmt ./...
|
||||||
@@ -53,5 +79,10 @@ tidy:
|
|||||||
frontend:
|
frontend:
|
||||||
cd frontend && npm ci && npm run build
|
cd frontend && npm ci && npm run build
|
||||||
|
|
||||||
|
## comments: 严格检查 Go 与 TypeScript/TSX 声明的中文语义注释和模板债务
|
||||||
|
comments:
|
||||||
|
$(GO) run ./tools/commentlint -mode check -root .
|
||||||
|
node frontend/scripts/check-comments.mjs --mode check --root frontend
|
||||||
|
|
||||||
## check: 本地提交前全套检查(fmt + vet + lint + test)
|
## check: 本地提交前全套检查(fmt + vet + lint + test)
|
||||||
check: fmt vet lint test
|
check: fmt architecture vet lint test comments
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
[](go.mod)
|
[](go.mod)
|
||||||
[](frontend/package.json)
|
[](frontend/package.json)
|
||||||
[](compose.yml)
|
[](compose.yml)
|
||||||
[](https://github.com/Christ9038/Ydisks-Xianyu-Helper/actions/workflows/docker-publish.yml)
|
[](https://github.com/Christ9038/Ydisks-Xianyu-Helper/actions/workflows/release.yml)
|
||||||
|
|
||||||
[功能特性](#功能特性) · [快速开始](#快速开始) · [配置说明](#配置说明) ·
|
[功能特性](#功能特性) · [快速开始](#快速开始) · [配置说明](#配置说明) ·
|
||||||
[Docker 部署](#docker-部署) · [开发指南](#开发指南) · [开源协议](#开源协议)
|
[Docker 部署](#docker-部署) · [开发指南](#开发指南) · [开源协议](#开源协议)
|
||||||
@@ -89,12 +89,14 @@ flowchart LR
|
|||||||
|
|
||||||
核心职责划分:
|
核心职责划分:
|
||||||
|
|
||||||
|
- `internal/composition`:唯一生产组合根,装配应用服务与生命周期组件
|
||||||
|
- `internal/application`:用例编排、所有权校验、事务边界与补偿
|
||||||
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
||||||
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
||||||
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
||||||
- `internal/browser`:Chromium 指纹读取与滑块验证
|
- `internal/browser`:Chromium 指纹读取与滑块验证
|
||||||
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
||||||
- `internal/server`:HTTP API、管理端鉴权和前端静态资源
|
- `internal/server`:HTTP/SPA transport、管理端鉴权和前端静态资源
|
||||||
|
|
||||||
## 页面预览
|
## 页面预览
|
||||||
|
|
||||||
@@ -158,7 +160,7 @@ docker compose up -d
|
|||||||
环境要求:
|
环境要求:
|
||||||
|
|
||||||
- Go 1.26.4 或兼容版本
|
- Go 1.26.4 或兼容版本
|
||||||
- Node.js 22 与 npm
|
- Node.js 24 与 npm
|
||||||
- Chromium 运行所需的系统依赖
|
- Chromium 运行所需的系统依赖
|
||||||
- 默认可直接使用 SQLite,无需额外数据库服务
|
- 默认可直接使用 SQLite,无需额外数据库服务
|
||||||
|
|
||||||
@@ -208,25 +210,41 @@ Windows 和 macOS 托盘启动时会自动启动后台服务,并显示检查
|
|||||||
`/var/log/ydisks-xianyu-helper/server.log`,也可以使用
|
`/var/log/ydisks-xianyu-helper/server.log`,也可以使用
|
||||||
`journalctl -u ydisks-xianyu-helper.service` 查看。
|
`journalctl -u ydisks-xianyu-helper.service` 查看。
|
||||||
|
|
||||||
桌面端安装包由 GitHub Actions 工作流在 `main` 和 `codex/desktop-packaging` 分支构建:Linux 上传
|
桌面端安装包由 `.github/workflows/desktop-cd.yml` 在 `dev`、`main` 分支上持续构建;正式版本由统一的
|
||||||
amd64/arm64 tar 包,Windows 上传安装器,macOS 分别上传 arm64 和 amd64 安装包。Windows
|
`.github/workflows/release.yml` 在 `v1.2.3` 格式的版本标签上协调构建:
|
||||||
|
Linux 上传 amd64/arm64 tar 包,Windows 上传安装器,macOS 分别上传 arm64 和 amd64 安装包。
|
||||||
|
分支构建只保留非正式 Actions artifacts;版本标签必须指向 `main` 中的提交,全部桌面端和 Docker
|
||||||
|
构建验证成功后等待 `production-release` Environment 人工审批,审批通过才创建 GitHub Release、
|
||||||
|
上传各平台安装包及 `SHA256SUMS`,并发布正式 Docker 标签。Windows
|
||||||
和 macOS 安装包使用工作流中配置的固定签名证书签名;未配置对应 GitHub Secrets 时,签名
|
和 macOS 安装包使用工作流中配置的固定签名证书签名;未配置对应 GitHub Secrets 时,签名
|
||||||
步骤会失败,不会生成可分发的安装包。
|
步骤会失败,不会生成可分发的安装包。当前仓库未配置正式签名证书时,Windows/macOS 正式发布
|
||||||
|
会停在签名步骤;Linux 安装包不依赖桌面端签名证书。
|
||||||
|
|
||||||
|
GitHub Release 正文使用正式标签所指向提交的短 SHA 和完整 Git commit message(主题和正文),不会展开
|
||||||
|
标签之间的全部历史提交。重跑同名标签时会同步更新正文并覆盖发布附件,不会使用 GitHub 自动生成的
|
||||||
|
PR 分类说明。
|
||||||
|
|
||||||
Linux 安装包的 `install.sh` 必须在与安装包相同架构的 Linux 主机上以 root 执行。安装包已经
|
Linux 安装包的 `install.sh` 必须在与安装包相同架构的 Linux 主机上以 root 执行。安装包已经
|
||||||
包含对应架构的 Playwright driver、Chromium 和 headless shell;安装时只安装 Chromium 所需
|
包含对应架构的 Playwright driver、Chromium 和 headless shell;安装时只安装 Chromium 所需
|
||||||
系统库,不会从 Debian 仓库重新安装 Chromium。
|
系统库,不会从 Debian 仓库重新安装 Chromium。
|
||||||
|
|
||||||
本地 macOS 打包可直接执行:
|
本地 macOS 打包必须先构建嵌入式前端和三个随包分发的可执行文件;`build-pkg.sh` 在 runtime 缺失时会自动调用
|
||||||
|
`prepare-runtime.sh`,不需要手工复制 Chromium、driver 或 headless shell:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./packaging/macos/prepare-runtime.sh arm64 ./dist/macos/playwright-runtime/arm64
|
npm ci --prefix frontend
|
||||||
./packaging/macos/build-pkg.sh 0.0.0-local ./dist/macos arm64
|
npm run build --prefix frontend
|
||||||
|
mkdir -p dist/macos/arm64
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-server ./cmd/server
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/browser-install ./cmd/browser-install
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-tray ./cmd/tray
|
||||||
|
packaging/macos/build-pkg.sh 0.0.0-local "$PWD/dist/macos" arm64
|
||||||
```
|
```
|
||||||
|
|
||||||
`build-pkg.sh` 会自动复用 `~/Library/Caches/ms-playwright-go` 和
|
`build-pkg.sh` 会自动复用 `~/Library/Caches/ms-playwright-go` 和
|
||||||
`~/Library/Caches/ms-playwright` 中与当前 Playwright driver 匹配的 Chromium;缓存不完整时会明确报错,
|
`~/Library/Caches/ms-playwright` 中与当前 Playwright driver 匹配的 Chromium;缓存不完整时会明确报错,
|
||||||
不会生成安装后无法启动服务的残缺安装包。Intel macOS 使用 `amd64` 参数,并需要本机已有对应 x64 runtime。
|
不会生成安装后无法启动服务的残缺安装包。Intel macOS 使用 `amd64` 参数,并需要本机已有对应 x64 runtime。
|
||||||
|
本机没有签名身份时生成的是未签名 pkg,不可作为已签名分发包使用。
|
||||||
|
|
||||||
桌面端首次启动:
|
桌面端首次启动:
|
||||||
|
|
||||||
@@ -243,9 +261,10 @@ sudo ./install.sh
|
|||||||
|
|
||||||
然后访问 `http://127.0.0.1:59188` 完成首次初始化。
|
然后访问 `http://127.0.0.1:59188` 完成首次初始化。
|
||||||
|
|
||||||
Linux、Windows、macOS 和源码运行默认都使用网页初始化:启动服务后打开
|
Linux、Windows 和 macOS 桌面安装包固定使用网页初始化:启动服务后打开
|
||||||
`http://127.0.0.1:59188`,在“首次设置管理员密码”页面输入并确认不少于 8 个字符的密码,
|
`http://127.0.0.1:59188`,在“首次设置管理员密码”页面输入并确认不少于 8 个字符的密码,
|
||||||
系统会创建 `admin` 并自动登录。只有 Docker Compose 使用 `.env` 中的
|
系统会创建 `admin` 并自动登录。源码运行的默认地址是 `:59188`,访问地址取决于传入的 `-addr`;
|
||||||
|
例如本文的 `-addr :59188` 示例可通过本机地址访问,但也会监听全部接口。只有 Docker Compose 使用 `.env` 中的
|
||||||
`XIANYU_ADMIN_PASSWORD` 做非交互初始化;CLI 方式仅用于无浏览器、自动化部署或重置密码。
|
`XIANYU_ADMIN_PASSWORD` 做非交互初始化;CLI 方式仅用于无浏览器、自动化部署或重置密码。
|
||||||
|
|
||||||
对于无浏览器环境、自动化部署或需要重置管理员密码的运维场景,仍可使用 CLI 初始化:
|
对于无浏览器环境、自动化部署或需要重置管理员密码的运维场景,仍可使用 CLI 初始化:
|
||||||
@@ -267,6 +286,11 @@ go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
|||||||
启动完成后访问 `http://localhost:59188`。如果数据库尚未初始化,直接在页面填写并确认
|
启动完成后访问 `http://localhost:59188`。如果数据库尚未初始化,直接在页面填写并确认
|
||||||
管理员密码即可,不需要知道数据库文件路径,也不需要先执行 CLI 命令。
|
管理员密码即可,不需要知道数据库文件路径,也不需要先执行 CLI 命令。
|
||||||
|
|
||||||
|
> 安全提示:`-addr :59188` 会监听全部网络接口。未初始化数据库的首次网页初始化不要求预共享
|
||||||
|
> secret,因此能够访问该端口的首个客户端可以创建管理员。该模式保留用于远程部署便利性,风险由
|
||||||
|
> 部署者承担。公网或不可信网络必须在防火墙、反向代理或安全组中限制管理端口访问,并建议通过
|
||||||
|
> `XIANYU_ADMIN_PASSWORD` 或 `-init-admin` 预先初始化。
|
||||||
|
|
||||||
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -310,11 +334,18 @@ DATABASE_URL > -db-url > -db
|
|||||||
| `LOG_LEVEL` | 系统设置或 `info` | `debug`、`info`、`warn`、`error` |
|
| `LOG_LEVEL` | 系统设置或 `info` | `debug`、`info`、`warn`、`error` |
|
||||||
| `LOG_FORMAT` | 系统设置或 `text` | `text` 或 `json` |
|
| `LOG_FORMAT` | 系统设置或 `text` | `text` 或 `json` |
|
||||||
| `BROWSER_HEADLESS` | 按账号设置;Docker 为 `true` | 强制启用或关闭无头 Chromium |
|
| `BROWSER_HEADLESS` | 按账号设置;Docker 为 `true` | 强制启用或关闭无头 Chromium |
|
||||||
|
| `PLAYWRIGHT_DRIVER_PATH` | 自动发现 | Playwright driver 目录;可与安装包内 runtime 对应 |
|
||||||
| `PLAYWRIGHT_BROWSERS_PATH` | 自动发现;Docker 为 `/ms-playwright` | Playwright Chromium runtime 目录 |
|
| `PLAYWRIGHT_BROWSERS_PATH` | 自动发现;Docker 为 `/ms-playwright` | Playwright Chromium runtime 目录 |
|
||||||
|
| `PLAYWRIGHT_NODEJS_PATH` | 自动发现 | Playwright driver 使用的 Node.js 可执行文件 |
|
||||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 仅在需要强制使用外部 Chromium 时指定 |
|
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 仅在需要强制使用外部 Chromium 时指定 |
|
||||||
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
|
||||||
|
| `PLAYWRIGHT_BROWSER_INSTALLER` | 自动发现 | runtime 缺失时使用的可取消 `browser-install` 入口;优先环境变量,其次服务同目录安装器,源码环境最后回退到模块内 `cmd/browser-install` |
|
||||||
|
| `CAPTCHA_BROWSER_PROXY` | 空 | 仅 token CAPTCHA Chromium 使用的无凭证 `http(s)`、`socks4` 或 `socks5` 代理地址;非法或含凭证的值会被忽略 |
|
||||||
|
| `CAPTCHA_IGNORE_CERT_ERRORS` | `false` | 仅受控 TLS 检查代理环境可设为 `true`;默认保持 Chromium 证书校验 |
|
||||||
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
|
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
|
||||||
|
|
||||||
|
前端构建还支持 `VITE_AMAP_JS_KEY`,用于覆盖发布页高德 JS API 的公开 Key;未设置时使用内置的公开 Key。修改后需重新执行 `make frontend` 才会写入嵌入式前端资源。
|
||||||
|
|
||||||
Docker Compose 还支持:
|
Docker Compose 还支持:
|
||||||
|
|
||||||
| 变量 | 默认值 | 说明 |
|
| 变量 | 默认值 | 说明 |
|
||||||
@@ -328,8 +359,11 @@ Docker Compose 还支持:
|
|||||||
| `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 |
|
| `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 |
|
||||||
| `XIANYU_HTTP_PORT` | `59188` | 应用在宿主机上的端口 |
|
| `XIANYU_HTTP_PORT` | `59188` | 应用在宿主机上的端口 |
|
||||||
|
|
||||||
默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请将
|
默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请把
|
||||||
`XIANYU_IMAGE` 改为 `:main`、版本号或 `:sha-<提交号>` 标签。
|
`XIANYU_IMAGE` 设置为完整镜像地址,例如
|
||||||
|
`ghcr.io/christ9038/ydisks-xianyu-helper:v1.2.3`、
|
||||||
|
`ghcr.io/christ9038/ydisks-xianyu-helper:main` 或
|
||||||
|
`ghcr.io/christ9038/ydisks-xianyu-helper:sha-<完整提交号>`。
|
||||||
|
|
||||||
`XIANYU_DATA_KEY` 用于加密 Cookie、账号密码、设备令牌、访问令牌、AI/SMTP 密钥和
|
`XIANYU_DATA_KEY` 用于加密 Cookie、账号密码、设备令牌、访问令牌、AI/SMTP 密钥和
|
||||||
通知凭证。启用后,服务会自动升级历史明文数据。密钥丢失或更换后,已有加密数据将
|
通知凭证。启用后,服务会自动升级历史明文数据。密钥丢失或更换后,已有加密数据将
|
||||||
@@ -343,6 +377,11 @@ Docker Compose 还支持:
|
|||||||
| `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL |
|
| `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL |
|
||||||
| `-addr` | `:59188` | HTTP 监听地址 |
|
| `-addr` | `:59188` | HTTP 监听地址 |
|
||||||
| `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` |
|
| `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` |
|
||||||
|
| `-workdir` | 空 | 服务工作目录;桌面服务用它固定数据和浏览器目录 |
|
||||||
|
| `-playwright-runtime-root` | 空 | 安装包随附的 Playwright runtime 根目录 |
|
||||||
|
| `-playwright-driver-dir` | 空 | Playwright driver 目录,会设置为当前进程的 driver 路径 |
|
||||||
|
| `-playwright-browser-dir` | 空 | Playwright 浏览器缓存目录,会设置为当前进程的 browser 路径 |
|
||||||
|
| `-data-key-file` | 空 | `XIANYU_DATA_KEY` 持久化文件;文件不存在时自动生成 |
|
||||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||||
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
||||||
@@ -352,6 +391,8 @@ Docker Compose 还支持:
|
|||||||
| `-ensure-admin` | `false` | 仅在 `admin` 不存在时初始化;已存在时不重置密码 |
|
| `-ensure-admin` | `false` | 仅在 `admin` 不存在时初始化;已存在时不重置密码 |
|
||||||
| `-admin-email` | `admin@example.com` | 初始化管理员邮箱 |
|
| `-admin-email` | `admin@example.com` | 初始化管理员邮箱 |
|
||||||
| `-admin-password` | 空 | 初始化管理员密码 |
|
| `-admin-password` | 空 | 初始化管理员密码 |
|
||||||
|
| `-service` | `false` | Windows Service 模式运行 |
|
||||||
|
| `-version` | `false` | 显示版本和构建信息后退出 |
|
||||||
|
|
||||||
### 数据库连接示例
|
### 数据库连接示例
|
||||||
|
|
||||||
@@ -407,13 +448,14 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
|||||||
|
|
||||||
| Git 引用 | 镜像标签 |
|
| Git 引用 | 镜像标签 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||||
| `codex/desktop-packaging` 分支 | `alpha`、`desktop-packaging`、`sha-<完整提交号>` |
|
| `main` 分支 | `main`、`sha-<完整提交号>` |
|
||||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
| `v1.2.3` 标签 | `v1.2.3`、`1.2.3`、`1.2`、`latest`、`sha-<完整提交号>` |
|
||||||
|
|
||||||
当前 Docker 发布工作流会在 `main` 分支发布 `main` 和 `latest` 正式镜像,并在
|
`dev` 是日常调试通道,`main` 是稳定候选通道,两者都不会更新 `latest` 或创建 Release。推送
|
||||||
`codex/desktop-packaging` 分支发布 `desktop-packaging` 和 `alpha` 标签用于验收;其他开发分支
|
`v1.2.3` 格式的 Git 标签会触发统一正式发布流程。所有 Docker 发布都必须先通过 Go/前端测试,
|
||||||
不会自动生成 GHCR 标签。
|
再对每个原生架构镜像实际启动 Chromium 和服务并通过 `/health` 检查;正式版还必须等全部桌面
|
||||||
|
安装包构建成功并通过人工审批,之后才生成版本 manifest、更新 `latest` 并创建 GitHub Release。
|
||||||
|
|
||||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||||
|
|
||||||
@@ -470,12 +512,15 @@ curl -fsS http://127.0.0.1:59188/health
|
|||||||
docker compose logs --tail=200 app
|
docker compose logs --tail=200 app
|
||||||
```
|
```
|
||||||
|
|
||||||
健康接口正常时返回:
|
健康接口正常时返回(构建信息会随运行方式变化):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"database":"ok","status":"ok"}
|
{"status":"ok","database":"ok","version":"dev","commit":"unknown","build_time":"unknown"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
正式安装包和 Docker 镜像会注入对应版本、提交号和构建时间;源码运行默认显示
|
||||||
|
`dev`/`unknown`。管理后台侧边栏底部也会显示当前运行版本和短提交号。
|
||||||
|
|
||||||
### 更新镜像
|
### 更新镜像
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -548,9 +593,11 @@ services:
|
|||||||
│ └── dbseed/ # Docker 功能测试数据种子
|
│ └── dbseed/ # Docker 功能测试数据种子
|
||||||
├── internal/
|
├── internal/
|
||||||
│ ├── account/ # 多账号监督与生命周期
|
│ ├── account/ # 多账号监督与生命周期
|
||||||
|
│ ├── application/ # 用例编排、事务与补偿
|
||||||
│ ├── adapter/ # 业务模块接线层
|
│ ├── adapter/ # 业务模块接线层
|
||||||
│ ├── automation/ # 自动化中心与调度器
|
│ ├── automation/ # 自动化中心与调度器
|
||||||
│ ├── browser/ # Chromium 指纹和滑块验证
|
│ ├── browser/ # Chromium 指纹和滑块验证
|
||||||
|
│ ├── composition/ # 唯一生产组合根
|
||||||
│ ├── db/ # 数据访问、加密与迁移
|
│ ├── db/ # 数据访问、加密与迁移
|
||||||
│ ├── engine/ # 单账号消息和交付运行时
|
│ ├── engine/ # 单账号消息和交付运行时
|
||||||
│ ├── notify/ # 通知渠道
|
│ ├── notify/ # 通知渠道
|
||||||
@@ -650,8 +697,9 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
|||||||
### Chromium 或 Playwright 初始化失败
|
### Chromium 或 Playwright 初始化失败
|
||||||
|
|
||||||
- Docker 部署优先使用项目提供的镜像,镜像在构建阶段已下载并校验匹配架构的 Chromium runtime;
|
- Docker 部署优先使用项目提供的镜像,镜像在构建阶段已下载并校验匹配架构的 Chromium runtime;
|
||||||
Docker CI 优先复用 GitHub Actions 缓存,不依赖 Debian 仓库中的 `chromium` 包,也不会在最终镜像
|
Docker CI 优先复用 GitHub Actions 缓存,不依赖 Debian 仓库中的 `chromium` 包。最终镜像基于
|
||||||
构建阶段执行 `apt-get update`。
|
固定的 Node.js 24 slim 镜像,只通过 Playwright 安装 Chromium 所需动态库,并在同一镜像层清理
|
||||||
|
apt 索引和临时缓存;发布前会实际启动 Chromium 和服务进行门禁验证。
|
||||||
- 独立安装包在 CI 构建阶段下载对应架构的 Playwright driver 和 Chromium;Linux 安装时只
|
- 独立安装包在 CI 构建阶段下载对应架构的 Playwright driver 和 Chromium;Linux 安装时只
|
||||||
安装系统库,不需要再次下载浏览器。
|
安装系统库,不需要再次下载浏览器。
|
||||||
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
||||||
@@ -708,3 +756,9 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
|||||||
连续性或数据完整性的长期兼容。因使用本项目造成的账号限制、交易纠纷、数据损失或
|
连续性或数据完整性的长期兼容。因使用本项目造成的账号限制、交易纠纷、数据损失或
|
||||||
其他直接与间接损失,应由使用者自行承担。请勿将本项目用于垃圾消息、欺诈、未授权
|
其他直接与间接损失,应由使用者自行承担。请勿将本项目用于垃圾消息、欺诈、未授权
|
||||||
访问、规避平台限制或任何违法违规活动。
|
访问、规避平台限制或任何违法违规活动。
|
||||||
|
|
||||||
|
## 社区支持
|
||||||
|
|
||||||
|
本项目受到 LINUX DO 社区的交流与反馈支持:
|
||||||
|
|
||||||
|
[访问 LINUX DO 社区](https://linux.do/)
|
||||||
@@ -10,27 +10,37 @@ import (
|
|||||||
"github.com/mxschmitt/playwright-go"
|
"github.com/mxschmitt/playwright-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// driverDir 用于本次流程后续判断的driverDir
|
||||||
driverDir := flag.String("driver-dir", "", "Playwright driver directory")
|
driverDir := flag.String("driver-dir", "", "Playwright driver directory")
|
||||||
|
// browserDir 用于本次流程后续判断的浏览器Dir
|
||||||
browserDir := flag.String("browser-dir", "", "Playwright browser cache directory")
|
browserDir := flag.String("browser-dir", "", "Playwright browser cache directory")
|
||||||
|
// withDeps 用于本次流程后续判断的withDeps
|
||||||
withDeps := flag.Bool("with-deps", false, "also install Linux system dependencies")
|
withDeps := flag.Bool("with-deps", false, "also install Linux system dependencies")
|
||||||
|
// depsOnly 用于本次流程后续判断的depsOnly
|
||||||
depsOnly := flag.Bool("deps-only", false, "only install Linux system dependencies; do not download Chromium")
|
depsOnly := flag.Bool("deps-only", false, "only install Linux system dependencies; do not download Chromium")
|
||||||
|
// driverOnly 表示只准备 Playwright driver,供服务初始化的可取消安装子进程使用。
|
||||||
|
driverOnly := flag.Bool("driver-only", false, "only install the Playwright driver")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
if *depsOnly && !*withDeps {
|
if *depsOnly && !*withDeps {
|
||||||
*withDeps = true
|
*withDeps = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if *driverDir != "" {
|
if *driverDir != "" {
|
||||||
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", *driverDir); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", *driverDir); err != nil {
|
||||||
fatal("设置 driver 目录失败", err)
|
fatal("设置 driver 目录失败", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if *browserDir != "" {
|
if *browserDir != "" {
|
||||||
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", *browserDir); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", *browserDir); err != nil {
|
||||||
fatal("设置浏览器目录失败", err)
|
fatal("设置浏览器目录失败", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// options 用于本次流程后续判断的options
|
||||||
options := &playwright.RunOptions{
|
options := &playwright.RunOptions{
|
||||||
Browsers: []string{"chromium"},
|
Browsers: []string{"chromium"},
|
||||||
Verbose: true,
|
Verbose: true,
|
||||||
@@ -38,14 +48,20 @@ func main() {
|
|||||||
if *driverDir != "" {
|
if *driverDir != "" {
|
||||||
options.DriverDirectory = *driverDir
|
options.DriverDirectory = *driverDir
|
||||||
}
|
}
|
||||||
|
// driver、err 用于本次流程后续判断的driver、err
|
||||||
driver, err := playwright.NewDriver(options)
|
driver, err := playwright.NewDriver(options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fatal("创建 Playwright driver 失败", err)
|
fatal("创建 Playwright driver 失败", err)
|
||||||
}
|
}
|
||||||
if err := driver.DownloadDriver(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := driver.DownloadDriver(); err != nil {
|
||||||
fatal("下载 Playwright driver 失败", err)
|
fatal("下载 Playwright driver 失败", err)
|
||||||
}
|
}
|
||||||
|
if *driverOnly {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// args 用于本次流程后续判断的args
|
||||||
args := []string{"install"}
|
args := []string{"install"}
|
||||||
if *depsOnly {
|
if *depsOnly {
|
||||||
args = []string{"install-deps", "chromium"}
|
args = []string{"install-deps", "chromium"}
|
||||||
@@ -55,14 +71,17 @@ func main() {
|
|||||||
} else {
|
} else {
|
||||||
args = append(args, "chromium")
|
args = append(args, "chromium")
|
||||||
}
|
}
|
||||||
|
// cmd 用于本次流程后续判断的cmd
|
||||||
cmd := driver.Command(args...)
|
cmd := driver.Command(args...)
|
||||||
cmd.Stdout = os.Stdout
|
cmd.Stdout = os.Stdout
|
||||||
cmd.Stderr = os.Stderr
|
cmd.Stderr = os.Stderr
|
||||||
if err := cmd.Run(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := cmd.Run(); err != nil {
|
||||||
fatal("安装 Chromium 失败", err)
|
fatal("安装 Chromium 失败", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fatal 封装fatal业务协调。
|
||||||
func fatal(message string, err error) {
|
func fatal(message string, err error) {
|
||||||
fmt.Fprintf(os.Stderr, "%s: %v\n", message, err)
|
fmt.Fprintf(os.Stderr, "%s: %v\n", message, err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
+91
-16
@@ -14,8 +14,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
|
"xianyu-go/internal/logsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// seedOptions 用于本次流程后续判断的seedOptions
|
||||||
type seedOptions struct {
|
type seedOptions struct {
|
||||||
Username string
|
Username string
|
||||||
Password string
|
Password string
|
||||||
@@ -24,19 +26,28 @@ type seedOptions struct {
|
|||||||
Limit int
|
Limit int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedResult 用于本次流程后续判断的seed结果
|
||||||
type seedResult struct {
|
type seedResult struct {
|
||||||
Items int
|
Items int
|
||||||
Orders int
|
Orders int
|
||||||
Cards int
|
Cards int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// sourcePath 用于本次流程后续判断的source路径
|
||||||
sourcePath := flag.String("source", "/seed/xianyu_data.db", "源 SQLite 文件")
|
sourcePath := flag.String("source", "/seed/xianyu_data.db", "源 SQLite 文件")
|
||||||
|
// targetURL 用于本次流程后续判断的targetURL
|
||||||
targetURL := flag.String("target", "", "目标数据库 URL")
|
targetURL := flag.String("target", "", "目标数据库 URL")
|
||||||
|
// username 用于本次流程后续判断的username
|
||||||
username := flag.String("username", "docker_fixture", "测试登录用户名")
|
username := flag.String("username", "docker_fixture", "测试登录用户名")
|
||||||
|
// password 用于本次流程后续判断的密码
|
||||||
password := flag.String("password", "docker_fixture_password", "测试登录密码")
|
password := flag.String("password", "docker_fixture_password", "测试登录密码")
|
||||||
|
// adminUsername 用于本次流程后续判断的adminUsername
|
||||||
adminUsername := flag.String("admin-username", "docker_admin", "测试管理员用户名")
|
adminUsername := flag.String("admin-username", "docker_admin", "测试管理员用户名")
|
||||||
|
// adminPassword 用于本次流程后续判断的admin密码
|
||||||
adminPassword := flag.String("admin-password", "docker_admin_password", "测试管理员密码")
|
adminPassword := flag.String("admin-password", "docker_admin_password", "测试管理员密码")
|
||||||
|
// limit 用于本次流程后续判断的上限
|
||||||
limit := flag.Int("limit", 20, "每类最多抽取条数")
|
limit := flag.Int("limit", 20, "每类最多抽取条数")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
if strings.TrimSpace(*targetURL) == "" {
|
if strings.TrimSpace(*targetURL) == "" {
|
||||||
@@ -44,22 +55,27 @@ func main() {
|
|||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
// source、err 用于本次流程后续判断的source、err
|
||||||
source, err := sql.Open("sqlite", "file:"+*sourcePath+"?mode=ro&_pragma=busy_timeout(10000)")
|
source, err := sql.Open("sqlite", "file:"+*sourcePath+"?mode=ro&_pragma=busy_timeout(10000)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fatalf("打开源 SQLite: %v", err)
|
fatalf("打开源 SQLite: %v", err)
|
||||||
}
|
}
|
||||||
defer source.Close()
|
defer source.Close()
|
||||||
if err := source.PingContext(ctx); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := source.PingContext(ctx); err != nil {
|
||||||
fatalf("连接源 SQLite: %v", err)
|
fatalf("连接源 SQLite: %v", err)
|
||||||
}
|
}
|
||||||
|
// targetDB、dialect、err 用于本次流程后续判断的targetDB、dialect、err
|
||||||
targetDB, dialect, err := db.Open(ctx, *targetURL)
|
targetDB, dialect, err := db.Open(ctx, *targetURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fatalf("打开目标数据库: %v", err)
|
fatalf("打开目标数据库: %v", err)
|
||||||
}
|
}
|
||||||
defer targetDB.Close()
|
defer targetDB.Close()
|
||||||
|
|
||||||
|
// result、err 用于本次流程后续判断的result、err
|
||||||
result, err := seedFromSQLite(ctx, source, db.NewStore(targetDB, dialect), seedOptions{
|
result, err := seedFromSQLite(ctx, source, db.NewStore(targetDB, dialect), seedOptions{
|
||||||
Username: *username,
|
Username: *username,
|
||||||
Password: *password,
|
Password: *password,
|
||||||
@@ -73,6 +89,7 @@ func main() {
|
|||||||
fmt.Printf("数据库种子完成:items=%d orders=%d cards=%d user=%s\n", result.Items, result.Orders, result.Cards, *username)
|
fmt.Printf("数据库种子完成:items=%d orders=%d cards=%d user=%s\n", result.Items, result.Orders, result.Cards, *username)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedFromSQLite 封装seedFromSQLite业务协调。
|
||||||
func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, options seedOptions) (seedResult, error) {
|
func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, options seedOptions) (seedResult, error) {
|
||||||
if options.Limit <= 0 || options.Limit > 100 {
|
if options.Limit <= 0 || options.Limit > 100 {
|
||||||
options.Limit = 20
|
options.Limit = 20
|
||||||
@@ -86,22 +103,29 @@ func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, optio
|
|||||||
if options.AdminPassword == "" {
|
if options.AdminPassword == "" {
|
||||||
options.AdminPassword = "docker_admin_password"
|
options.AdminPassword = "docker_admin_password"
|
||||||
}
|
}
|
||||||
if err := ensureFixtureAdmin(ctx, target, options.AdminUsername, options.AdminPassword); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := ensureFixtureAdmin(ctx, target, options.AdminUsername, options.AdminPassword); err != nil {
|
||||||
return seedResult{}, err
|
return seedResult{}, err
|
||||||
}
|
}
|
||||||
|
// user、err 用于本次流程后续判断的user、err
|
||||||
user, err := prepareFixtureUser(ctx, target, options)
|
user, err := prepareFixtureUser(ctx, target, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return seedResult{}, err
|
return seedResult{}, err
|
||||||
}
|
}
|
||||||
|
// accountID 用于本次流程后续判断的账号ID
|
||||||
const accountID = "docker-fixture-account"
|
const accountID = "docker-fixture-account"
|
||||||
if err := target.Cookies.Save(ctx, accountID, "unb=docker-fixture; _m_h5_tk=fixture_1;", user.ID); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Cookies.Save(ctx, accountID, "unb=docker-fixture; _m_h5_tk=fixture_1;", user.ID); err != nil {
|
||||||
return seedResult{}, err
|
return seedResult{}, err
|
||||||
}
|
}
|
||||||
if err := target.Cookies.SetStatusWithReason(ctx, accountID, false, "Docker 脱敏测试账号"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Cookies.SetStatusWithReason(ctx, accountID, false, "Docker 脱敏测试账号"); err != nil {
|
||||||
return seedResult{}, err
|
return seedResult{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// result 用于本次流程后续判断的结果
|
||||||
result := seedResult{}
|
result := seedResult{}
|
||||||
|
// itemMap、count、err 用于本次流程后续判断的商品Map、count、err
|
||||||
itemMap, count, err := seedItems(ctx, source, target, accountID, options.Limit)
|
itemMap, count, err := seedItems(ctx, source, target, accountID, options.Limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return result, err
|
return result, err
|
||||||
@@ -113,12 +137,14 @@ func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, optio
|
|||||||
}
|
}
|
||||||
// 保留一条历史脏金额,用于验证三种数据库下统计接口都能安全跳过而不是 500。
|
// 保留一条历史脏金额,用于验证三种数据库下统计接口都能安全跳过而不是 500。
|
||||||
fixtureItemID := ""
|
fixtureItemID := ""
|
||||||
|
// id 表示当前遍历过程中的标识
|
||||||
for _, id := range itemMap {
|
for _, id := range itemMap {
|
||||||
fixtureItemID = id
|
fixtureItemID = id
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if fixtureItemID != "" {
|
if fixtureItemID != "" {
|
||||||
if err := target.Orders.Upsert(ctx, "docker-invalid-amount", db.OrderUpsertOpts{
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Orders.Upsert(ctx, "docker-invalid-amount", db.OrderUpsertOpts{
|
||||||
CookieID: accountID, ItemID: fixtureItemID, BuyerID: "docker-buyer-invalid",
|
CookieID: accountID, ItemID: fixtureItemID, BuyerID: "docker-buyer-invalid",
|
||||||
Quantity: "1", OrderStatus: "completed",
|
Quantity: "1", OrderStatus: "completed",
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
@@ -133,9 +159,12 @@ func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, optio
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureFixtureAdmin 封装ensureFixtureAdmin业务协调。
|
||||||
func ensureFixtureAdmin(ctx context.Context, target *db.Store, username, password string) error {
|
func ensureFixtureAdmin(ctx context.Context, target *db.Store, username, password string) error {
|
||||||
|
// user、err 用于本次流程后续判断的user、err
|
||||||
user, err := target.Users.GetByUsername(ctx, username)
|
user, err := target.Users.GetByUsername(ctx, username)
|
||||||
if errors.Is(err, db.ErrNotFound) {
|
if errors.Is(err, db.ErrNotFound) {
|
||||||
|
// created、createErr 用于本次流程后续判断的created、createErr
|
||||||
created, createErr := target.Users.Create(ctx, username, username+"@docker.test", password)
|
created, createErr := target.Users.Create(ctx, username, username+"@docker.test", password)
|
||||||
if createErr != nil {
|
if createErr != nil {
|
||||||
return fmt.Errorf("创建测试管理员: %w", createErr)
|
return fmt.Errorf("创建测试管理员: %w", createErr)
|
||||||
@@ -146,12 +175,14 @@ func ensureFixtureAdmin(ctx context.Context, target *db.Store, username, passwor
|
|||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return fmt.Errorf("查询测试管理员: %w", err)
|
return fmt.Errorf("查询测试管理员: %w", err)
|
||||||
} else {
|
} else {
|
||||||
|
// updated、updateErr 用于本次流程后续判断的updated、updateErr
|
||||||
updated, updateErr := target.Users.UpdatePassword(ctx, username, password)
|
updated, updateErr := target.Users.UpdatePassword(ctx, username, password)
|
||||||
if updateErr != nil || !updated {
|
if updateErr != nil || !updated {
|
||||||
return fmt.Errorf("重置测试管理员密码: updated=%v err=%v", updated, updateErr)
|
return fmt.Errorf("重置测试管理员密码: updated=%v err=%v", updated, updateErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := target.Users.SetAdmin(ctx, username); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Users.SetAdmin(ctx, username); err != nil {
|
||||||
return fmt.Errorf("设置测试管理员: %w", err)
|
return fmt.Errorf("设置测试管理员: %w", err)
|
||||||
}
|
}
|
||||||
if user != nil {
|
if user != nil {
|
||||||
@@ -165,9 +196,12 @@ func ensureFixtureAdmin(ctx context.Context, target *db.Store, username, passwor
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// prepareFixtureUser 封装prepareFixture用户业务协调。
|
||||||
func prepareFixtureUser(ctx context.Context, target *db.Store, options seedOptions) (*db.User, error) {
|
func prepareFixtureUser(ctx context.Context, target *db.Store, options seedOptions) (*db.User, error) {
|
||||||
|
// user、err 用于本次流程后续判断的user、err
|
||||||
user, err := target.Users.GetByUsername(ctx, options.Username)
|
user, err := target.Users.GetByUsername(ctx, options.Username)
|
||||||
if errors.Is(err, db.ErrNotFound) {
|
if errors.Is(err, db.ErrNotFound) {
|
||||||
|
// created、createErr 用于本次流程后续判断的created、createErr
|
||||||
created, createErr := target.Users.Create(ctx, options.Username, options.Username+"@docker.test", options.Password)
|
created, createErr := target.Users.Create(ctx, options.Username, options.Username+"@docker.test", options.Password)
|
||||||
if createErr != nil {
|
if createErr != nil {
|
||||||
return nil, fmt.Errorf("创建测试用户: %w", createErr)
|
return nil, fmt.Errorf("创建测试用户: %w", createErr)
|
||||||
@@ -183,41 +217,53 @@ func prepareFixtureUser(ctx context.Context, target *db.Store, options seedOptio
|
|||||||
|
|
||||||
// 测试用户可能来自持久卷中的上一次执行。先移除其自动化规则,释放
|
// 测试用户可能来自持久卷中的上一次执行。先移除其自动化规则,释放
|
||||||
// card_id 的 RESTRICT 外键,再清理账号数据和卡密,保留用户主键并重置密码。
|
// card_id 的 RESTRICT 外键,再清理账号数据和卡密,保留用户主键并重置密码。
|
||||||
|
// query 表示当前遍历过程中的查询
|
||||||
for _, query := range []string{
|
for _, query := range []string{
|
||||||
`DELETE FROM automation_rules WHERE user_id=?`,
|
`DELETE FROM automation_rules WHERE user_id=?`,
|
||||||
`DELETE FROM cookies WHERE user_id=?`,
|
`DELETE FROM cookies WHERE user_id=?`,
|
||||||
`DELETE FROM cards WHERE user_id=?`,
|
`DELETE FROM cards WHERE user_id=?`,
|
||||||
} {
|
} {
|
||||||
if _, err := target.DB.ExecContext(ctx, query, user.ID); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := target.DB.ExecContext(ctx, query, user.ID); err != nil {
|
||||||
return nil, fmt.Errorf("清理上次测试数据: %w", err)
|
return nil, fmt.Errorf("清理上次测试数据: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// updated、err 用于本次流程后续判断的updated、err
|
||||||
updated, err := target.Users.UpdatePassword(ctx, options.Username, options.Password)
|
updated, err := target.Users.UpdatePassword(ctx, options.Username, options.Password)
|
||||||
if err != nil || !updated {
|
if err != nil || !updated {
|
||||||
return nil, fmt.Errorf("重置测试用户密码: updated=%v err=%v", updated, err)
|
return nil, fmt.Errorf("重置测试用户密码: updated=%v err=%v", updated, err)
|
||||||
}
|
}
|
||||||
if _, err := target.DB.ExecContext(ctx, `UPDATE users SET is_active=1,is_admin=0 WHERE id=?`, user.ID); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := target.DB.ExecContext(ctx, `UPDATE users SET is_active=1,is_admin=0 WHERE id=?`, user.ID); err != nil {
|
||||||
return nil, fmt.Errorf("重置测试用户状态: %w", err)
|
return nil, fmt.Errorf("重置测试用户状态: %w", err)
|
||||||
}
|
}
|
||||||
return target.Users.GetByUsername(ctx, options.Username)
|
return target.Users.GetByUsername(ctx, options.Username)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedItems 封装seed商品列表业务协调。
|
||||||
func seedItems(ctx context.Context, source *sql.DB, target *db.Store, accountID string, limit int) (map[string]string, int, error) {
|
func seedItems(ctx context.Context, source *sql.DB, target *db.Store, accountID string, limit int) (map[string]string, int, error) {
|
||||||
|
// rows、err 用于本次流程后续判断的rows、err
|
||||||
rows, err := source.QueryContext(ctx, `SELECT item_id,COALESCE(item_title,''),COALESCE(item_description,''),
|
rows, err := source.QueryContext(ctx, `SELECT item_id,COALESCE(item_title,''),COALESCE(item_description,''),
|
||||||
COALESCE(item_category,''),COALESCE(item_price,'') FROM item_info ORDER BY updated_at DESC LIMIT ?`, limit)
|
COALESCE(item_category,''),COALESCE(item_price,'') FROM item_info ORDER BY updated_at DESC LIMIT ?`, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
// mapping 用于本次流程后续判断的mapping
|
||||||
mapping := make(map[string]string)
|
mapping := make(map[string]string)
|
||||||
|
// count 用于本次流程后续判断的数量
|
||||||
count := 0
|
count := 0
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
|
// sourceID、title、description、category、price 用于本次流程后续判断的sourceID、title、description、category、price
|
||||||
var sourceID, title, description, category, price string
|
var sourceID, title, description, category, price string
|
||||||
if err := rows.Scan(&sourceID, &title, &description, &category, &price); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := rows.Scan(&sourceID, &title, &description, &category, &price); err != nil {
|
||||||
return nil, count, err
|
return nil, count, err
|
||||||
}
|
}
|
||||||
|
// fixtureID 用于本次流程后续判断的fixtureID
|
||||||
fixtureID := fmt.Sprintf("docker-item-%03d", count+1)
|
fixtureID := fmt.Sprintf("docker-item-%03d", count+1)
|
||||||
if err := target.Items.Upsert(ctx, &db.ItemInfoRow{
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Items.Upsert(ctx, &db.ItemInfoRow{
|
||||||
CookieID: accountID, ItemID: fixtureID, ItemTitle: fallback(title, "SQLite 测试商品"),
|
CookieID: accountID, ItemID: fixtureID, ItemTitle: fallback(title, "SQLite 测试商品"),
|
||||||
ItemDescription: description, ItemCategory: category, ItemPrice: price,
|
ItemDescription: description, ItemCategory: category, ItemPrice: price,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
@@ -229,7 +275,9 @@ func seedItems(ctx context.Context, source *sql.DB, target *db.Store, accountID
|
|||||||
return mapping, count, rows.Err()
|
return mapping, count, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedOrders 封装seed订单列表业务协调。
|
||||||
func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID string, items map[string]string, limit int) (int, error) {
|
func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID string, items map[string]string, limit int) (int, error) {
|
||||||
|
// rows、err 用于本次流程后续判断的rows、err
|
||||||
rows, err := source.QueryContext(ctx, `SELECT order_id,COALESCE(item_id,''),COALESCE(quantity,'1'),
|
rows, err := source.QueryContext(ctx, `SELECT order_id,COALESCE(item_id,''),COALESCE(quantity,'1'),
|
||||||
COALESCE(amount,'0'),COALESCE(order_status,'unknown'),COALESCE(spec_name,''),COALESCE(spec_value,'')
|
COALESCE(amount,'0'),COALESCE(order_status,'unknown'),COALESCE(spec_name,''),COALESCE(spec_value,'')
|
||||||
FROM orders ORDER BY updated_at DESC LIMIT ?`, limit*4)
|
FROM orders ORDER BY updated_at DESC LIMIT ?`, limit*4)
|
||||||
@@ -237,22 +285,28 @@ func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID
|
|||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
// count 用于本次流程后续判断的数量
|
||||||
count := 0
|
count := 0
|
||||||
for rows.Next() && count < limit {
|
for rows.Next() && count < limit {
|
||||||
|
// sourceOrderID、sourceItemID、quantity、amount、status、specName、specValue 用于本次流程后续判断的source订单ID、source商品ID、quantity、amount、status、specName、spec值
|
||||||
var sourceOrderID, sourceItemID, quantity, amount, status, specName, specValue string
|
var sourceOrderID, sourceItemID, quantity, amount, status, specName, specValue string
|
||||||
if err := rows.Scan(&sourceOrderID, &sourceItemID, &quantity, &amount, &status, &specName, &specValue); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := rows.Scan(&sourceOrderID, &sourceItemID, &quantity, &amount, &status, &specName, &specValue); err != nil {
|
||||||
return count, err
|
return count, err
|
||||||
}
|
}
|
||||||
|
// itemID、ok 用于本次流程后续判断的商品ID、ok
|
||||||
itemID, ok := items[sourceItemID]
|
itemID, ok := items[sourceItemID]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if normalized, valid := db.NormalizeOrderAmount(amount); valid {
|
if // normalized、valid 用于本次流程后续判断的normalized、valid
|
||||||
|
normalized, valid := db.NormalizeOrderAmount(amount); valid {
|
||||||
amount = normalized
|
amount = normalized
|
||||||
} else {
|
} else {
|
||||||
amount = ""
|
amount = ""
|
||||||
}
|
}
|
||||||
if err := target.Orders.Upsert(ctx, "docker-order-"+shortHash(sourceOrderID), db.OrderUpsertOpts{
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := target.Orders.Upsert(ctx, "docker-order-"+shortHash(sourceOrderID), db.OrderUpsertOpts{
|
||||||
CookieID: accountID, ItemID: itemID, BuyerID: "docker-buyer", Quantity: quantity,
|
CookieID: accountID, ItemID: itemID, BuyerID: "docker-buyer", Quantity: quantity,
|
||||||
Amount: amount, OrderStatus: status, SpecName: specName, SpecValue: specValue,
|
Amount: amount, OrderStatus: status, SpecName: specName, SpecValue: specValue,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
@@ -263,20 +317,27 @@ func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID
|
|||||||
return count, rows.Err()
|
return count, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedCards 封装seed卡密列表业务协调。
|
||||||
func seedCards(ctx context.Context, source *sql.DB, target *db.Store, userID int64, limit int) (int, error) {
|
func seedCards(ctx context.Context, source *sql.DB, target *db.Store, userID int64, limit int) (int, error) {
|
||||||
|
// rows、err 用于本次流程后续判断的rows、err
|
||||||
rows, err := source.QueryContext(ctx, `SELECT COALESCE(name,''),type,COALESCE(delay_seconds,0)
|
rows, err := source.QueryContext(ctx, `SELECT COALESCE(name,''),type,COALESCE(delay_seconds,0)
|
||||||
FROM cards ORDER BY updated_at DESC LIMIT ?`, limit)
|
FROM cards ORDER BY updated_at DESC LIMIT ?`, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
// count 用于本次流程后续判断的数量
|
||||||
count := 0
|
count := 0
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
|
// name、cardType 用于本次流程后续判断的name、card类型
|
||||||
var name, cardType string
|
var name, cardType string
|
||||||
|
// delay 用于本次流程后续判断的延迟
|
||||||
var delay int
|
var delay int
|
||||||
if err := rows.Scan(&name, &cardType, &delay); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := rows.Scan(&name, &cardType, &delay); err != nil {
|
||||||
return count, err
|
return count, err
|
||||||
}
|
}
|
||||||
|
// card 用于本次流程后续判断的卡密
|
||||||
card := &db.CardFull{
|
card := &db.CardFull{
|
||||||
Name: fmt.Sprintf("[Docker测试] %s %d", fallback(name, "SQLite 卡密"), count+1),
|
Name: fmt.Sprintf("[Docker测试] %s %d", fallback(name, "SQLite 卡密"), count+1),
|
||||||
Type: "text", TextContent: "Docker 脱敏测试发货内容", Enabled: true,
|
Type: "text", TextContent: "Docker 脱敏测试发货内容", Enabled: true,
|
||||||
@@ -286,7 +347,8 @@ func seedCards(ctx context.Context, source *sql.DB, target *db.Store, userID int
|
|||||||
card.Type = "data"
|
card.Type = "data"
|
||||||
card.DataContent = fmt.Sprintf("DOCKER-FIXTURE-%03d-A\nDOCKER-FIXTURE-%03d-B", count+1, count+1)
|
card.DataContent = fmt.Sprintf("DOCKER-FIXTURE-%03d-A\nDOCKER-FIXTURE-%03d-B", count+1, count+1)
|
||||||
}
|
}
|
||||||
if _, err := target.Cards.Create(ctx, card); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := target.Cards.Create(ctx, card); err != nil {
|
||||||
return count, err
|
return count, err
|
||||||
}
|
}
|
||||||
count++
|
count++
|
||||||
@@ -294,11 +356,14 @@ func seedCards(ctx context.Context, source *sql.DB, target *db.Store, userID int
|
|||||||
return count, rows.Err()
|
return count, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// shortHash 封装shortHash业务协调。
|
||||||
func shortHash(value string) string {
|
func shortHash(value string) string {
|
||||||
|
// sum 用于本次流程后续判断的sum
|
||||||
sum := sha256.Sum256([]byte(value))
|
sum := sha256.Sum256([]byte(value))
|
||||||
return fmt.Sprintf("%x", sum[:6])
|
return fmt.Sprintf("%x", sum[:6])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fallback 封装fallback业务协调。
|
||||||
func fallback(value, defaultValue string) string {
|
func fallback(value, defaultValue string) string {
|
||||||
if strings.TrimSpace(value) == "" {
|
if strings.TrimSpace(value) == "" {
|
||||||
return defaultValue
|
return defaultValue
|
||||||
@@ -306,7 +371,17 @@ func fallback(value, defaultValue string) string {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fatalf 封装fatalf业务协调。
|
||||||
func fatalf(format string, args ...any) {
|
func fatalf(format string, args ...any) {
|
||||||
fmt.Fprintf(os.Stderr, format+"\n", args...)
|
// safeArgs 保存经过错误脱敏的命令行错误参数,避免目标数据库连接信息进入终端。
|
||||||
|
safeArgs := append([]any(nil), args...)
|
||||||
|
// index 表示当前格式化参数下标;value 表示待检查的原始参数。
|
||||||
|
for index, value := range safeArgs {
|
||||||
|
// errValue 表示当前参数是否为错误对象。
|
||||||
|
if errValue, ok := value.(error); ok {
|
||||||
|
safeArgs[index] = logsafe.Error(errValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, format+"\n", safeArgs...)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
@@ -9,28 +9,37 @@ import (
|
|||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets 封装TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets业务协调。
|
||||||
func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) {
|
func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) {
|
||||||
|
// ctx 用于本次流程后续判断的ctx
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// sourceDB、sourceDialect、err 用于本次流程后续判断的sourceDB、sourceDialect、err
|
||||||
sourceDB, sourceDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "source.db"))
|
sourceDB, sourceDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "source.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer sourceDB.Close()
|
defer sourceDB.Close()
|
||||||
|
// source 用于本次流程后续判断的source
|
||||||
source := db.NewStore(sourceDB, sourceDialect)
|
source := db.NewStore(sourceDB, sourceDialect)
|
||||||
source.Users.Create(ctx, "source", "source@example.com", "pw")
|
source.Users.Create(ctx, "source", "source@example.com", "pw")
|
||||||
|
// user 用于本次流程后续判断的用户
|
||||||
user, _ := source.Users.GetByUsername(ctx, "source")
|
user, _ := source.Users.GetByUsername(ctx, "source")
|
||||||
source.Cookies.Save(ctx, "real-account", "unb=real-secret; _m_h5_tk=secret;", user.ID)
|
source.Cookies.Save(ctx, "real-account", "unb=real-secret; _m_h5_tk=secret;", user.ID)
|
||||||
source.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "real-account", ItemID: "real-item", ItemTitle: "真实商品", ItemPrice: "19.90"})
|
source.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "real-account", ItemID: "real-item", ItemTitle: "真实商品", ItemPrice: "19.90"})
|
||||||
source.Orders.Upsert(ctx, "real-order", db.OrderUpsertOpts{CookieID: "real-account", ItemID: "real-item", BuyerID: "real-buyer", Amount: "19.90", OrderStatus: "completed"})
|
source.Orders.Upsert(ctx, "real-order", db.OrderUpsertOpts{CookieID: "real-account", ItemID: "real-item", BuyerID: "real-buyer", Amount: "19.90", OrderStatus: "completed"})
|
||||||
source.Cards.Create(ctx, &db.CardFull{Name: "真实卡密", Type: "data", DataContent: "SECRET-CODE", Enabled: true, UserID: user.ID})
|
source.Cards.Create(ctx, &db.CardFull{Name: "真实卡密", Type: "data", DataContent: "SECRET-CODE", Enabled: true, UserID: user.ID})
|
||||||
|
|
||||||
|
// targetDB、targetDialect、err 用于本次流程后续判断的targetDB、targetDialect、err
|
||||||
targetDB, targetDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "target.db"))
|
targetDB, targetDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "target.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer targetDB.Close()
|
defer targetDB.Close()
|
||||||
|
// target 用于本次流程后续判断的target
|
||||||
target := db.NewStore(targetDB, targetDialect)
|
target := db.NewStore(targetDB, targetDialect)
|
||||||
|
// options 用于本次流程后续判断的options
|
||||||
options := seedOptions{Username: "fixture", Password: "fixture-password", AdminUsername: "fixture-admin", AdminPassword: "fixture-admin-password", Limit: 10}
|
options := seedOptions{Username: "fixture", Password: "fixture-password", AdminUsername: "fixture-admin", AdminPassword: "fixture-admin-password", Limit: 10}
|
||||||
|
// result、err 用于本次流程后续判断的result、err
|
||||||
result, err := seedFromSQLite(ctx, sourceDB, target, options)
|
result, err := seedFromSQLite(ctx, sourceDB, target, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -38,24 +47,30 @@ func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) {
|
|||||||
if result.Items != 1 || result.Orders != 1 || result.Cards != 1 {
|
if result.Items != 1 || result.Orders != 1 || result.Cards != 1 {
|
||||||
t.Fatalf("result=%+v", result)
|
t.Fatalf("result=%+v", result)
|
||||||
}
|
}
|
||||||
|
// cookie 用于本次流程后续判断的登录凭证
|
||||||
cookie, _ := target.Cookies.GetValue(ctx, "docker-fixture-account")
|
cookie, _ := target.Cookies.GetValue(ctx, "docker-fixture-account")
|
||||||
if strings.Contains(cookie, "real-secret") || strings.Contains(cookie, "secret") {
|
if strings.Contains(cookie, "real-secret") || strings.Contains(cookie, "secret") {
|
||||||
t.Fatalf("source cookie leaked: %q", cookie)
|
t.Fatalf("source cookie leaked: %q", cookie)
|
||||||
}
|
}
|
||||||
|
// fixtureUser 用于本次流程后续判断的fixture用户
|
||||||
fixtureUser, _ := target.Users.GetByUsername(ctx, "fixture")
|
fixtureUser, _ := target.Users.GetByUsername(ctx, "fixture")
|
||||||
|
// fixtureAdmin、adminErr 用于本次流程后续判断的fixtureAdmin、adminErr
|
||||||
fixtureAdmin, adminErr := target.Users.GetByUsername(ctx, "fixture-admin")
|
fixtureAdmin, adminErr := target.Users.GetByUsername(ctx, "fixture-admin")
|
||||||
if adminErr != nil || !fixtureAdmin.IsAdmin || !fixtureAdmin.IsActive {
|
if adminErr != nil || !fixtureAdmin.IsAdmin || !fixtureAdmin.IsActive {
|
||||||
t.Fatalf("fixture admin missing or inactive: user=%+v err=%v", fixtureAdmin, adminErr)
|
t.Fatalf("fixture admin missing or inactive: user=%+v err=%v", fixtureAdmin, adminErr)
|
||||||
}
|
}
|
||||||
|
// cards 用于本次流程后续判断的卡密列表
|
||||||
cards, _ := target.Cards.AllForUser(ctx, fixtureUser.ID)
|
cards, _ := target.Cards.AllForUser(ctx, fixtureUser.ID)
|
||||||
if len(cards) != 1 || strings.Contains(cards[0].DataContent, "SECRET-CODE") {
|
if len(cards) != 1 || strings.Contains(cards[0].DataContent, "SECRET-CODE") {
|
||||||
t.Fatalf("source card secret leaked: %+v", cards)
|
t.Fatalf("source card secret leaked: %+v", cards)
|
||||||
}
|
}
|
||||||
|
// invalidOrder、err 用于本次流程后续判断的invalidOrder、err
|
||||||
invalidOrder, err := target.Orders.Get(ctx, "docker-invalid-amount")
|
invalidOrder, err := target.Orders.Get(ctx, "docker-invalid-amount")
|
||||||
if err != nil || invalidOrder.Amount != "not-a-number" {
|
if err != nil || invalidOrder.Amount != "not-a-number" {
|
||||||
t.Fatalf("invalid amount fixture missing: order=%+v err=%v", invalidOrder, err)
|
t.Fatalf("invalid amount fixture missing: order=%+v err=%v", invalidOrder, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// second、err 用于本次流程后续判断的second、err
|
||||||
second, err := seedFromSQLite(ctx, sourceDB, target, options)
|
second, err := seedFromSQLite(ctx, sourceDB, target, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("second idempotent seed: %v", err)
|
t.Fatalf("second idempotent seed: %v", err)
|
||||||
|
|||||||
+102
-32
@@ -14,6 +14,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
@@ -21,17 +22,22 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
|
"xianyu-go/internal/logsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// main 是验证 CLI 的进程入口;参数与运行错误统一由 run 返回退出码。
|
||||||
func main() {
|
func main() {
|
||||||
|
// cleanup 用于本次流程后续判断的cleanup
|
||||||
var cleanup func() error
|
var cleanup func() error
|
||||||
|
// fail 用于本次流程后续判断的fail
|
||||||
fail := func(format string, args ...any) {
|
fail := func(format string, args ...any) {
|
||||||
if cleanup != nil {
|
if cleanup != nil {
|
||||||
if err := cleanup(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
fmt.Printf("⚠️ 清理验证数据失败: %v\n", err)
|
err := cleanup(); err != nil {
|
||||||
|
fmt.Printf("⚠️ 清理验证数据失败: %s\n", logsafe.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Printf(format, args...)
|
fmt.Printf(format, safeDiagnosticArgs(args)...)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,11 +45,14 @@ func main() {
|
|||||||
fmt.Println("用法: dbverify <database-url>")
|
fmt.Println("用法: dbverify <database-url>")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
// url 用于本次流程后续判断的地址
|
||||||
url := os.Args[1]
|
url := os.Args[1]
|
||||||
|
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
fmt.Printf("连接 %s ...\n", maskURL(url))
|
fmt.Printf("连接 %s ...\n", maskURL(url))
|
||||||
|
// database、dialect、err 用于本次流程后续判断的database、dialect、err
|
||||||
database, dialect, err := db.Open(ctx, url)
|
database, dialect, err := db.Open(ctx, url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail("❌ Open 失败: %v\n", err)
|
fail("❌ Open 失败: %v\n", err)
|
||||||
@@ -51,57 +60,50 @@ func main() {
|
|||||||
defer database.Close()
|
defer database.Close()
|
||||||
fmt.Printf("✅ 迁移成功,方言=%s\n", dialect)
|
fmt.Printf("✅ 迁移成功,方言=%s\n", dialect)
|
||||||
|
|
||||||
|
// store 用于本次流程后续判断的store
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
|
|
||||||
// 1) 创建用户(用唯一用户名,避免在已有数据的库上因 admin 重名而失败)。
|
// 1) 创建用户(用唯一用户名,避免在已有数据的库上因 admin 重名而失败)。
|
||||||
ids := newVerifyIDs(time.Now().UnixNano())
|
ids := newVerifyIDs(time.Now().UnixNano())
|
||||||
|
// username 用于本次流程后续判断的username
|
||||||
username := ids.username
|
username := ids.username
|
||||||
|
// accountID 用于本次流程后续判断的账号ID
|
||||||
accountID := ids.accountID
|
accountID := ids.accountID
|
||||||
|
// orderID 用于本次流程后续判断的订单ID
|
||||||
orderID := ids.orderID
|
orderID := ids.orderID
|
||||||
|
// itemID 用于本次流程后续判断的商品ID
|
||||||
itemID := ids.itemID
|
itemID := ids.itemID
|
||||||
|
// buyerID 用于本次流程后续判断的买家ID
|
||||||
buyerID := ids.buyerID
|
buyerID := ids.buyerID
|
||||||
cleanup = func() error {
|
cleanup = func() error {
|
||||||
|
// cleanupCtx、cleanupCancel 用于本次流程后续判断的cleanupCtx、cleanup取消
|
||||||
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
defer cleanupCancel()
|
defer cleanupCancel()
|
||||||
return cleanupVerifyData(cleanupCtx, store, ids)
|
return cleanupVerifyData(cleanupCtx, store, ids)
|
||||||
}
|
}
|
||||||
|
// password、err 用于本次流程后续判断的password、err
|
||||||
password, err := newVerifyPassword()
|
password, err := newVerifyPassword()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail("❌ 生成验证密码失败: %v\n", err)
|
fail("❌ 生成验证密码失败: %v\n", err)
|
||||||
}
|
}
|
||||||
|
// ok、err 用于本次流程后续判断的ok、err
|
||||||
ok, err := store.Users.Create(ctx, username, username+"@test.local", password)
|
ok, err := store.Users.Create(ctx, username, username+"@test.local", password)
|
||||||
if err != nil || !ok {
|
if err != nil || !ok {
|
||||||
fail("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
|
fail("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
|
||||||
}
|
}
|
||||||
|
// adminUser、err 用于本次流程后续判断的adminUser、err
|
||||||
adminUser, err := store.Users.GetByUsername(ctx, username)
|
adminUser, err := store.Users.GetByUsername(ctx, username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail("❌ 查询验证用户失败: %v\n", err)
|
fail("❌ 查询验证用户失败: %v\n", err)
|
||||||
}
|
}
|
||||||
|
// userID 用于本次流程后续判断的用户ID
|
||||||
userID := adminUser.ID
|
userID := adminUser.ID
|
||||||
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
|
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
|
||||||
|
|
||||||
// 2) 保存 cookie(dialectUpsert: ON CONFLICT/ON DUPLICATE KEY)
|
// verifyCookieAndSettings 校验跨方言 Cookie 与设置的 upsert 语义,失败时由 CLI 统一清理临时数据。
|
||||||
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
|
if err := verifyCookieAndSettings(ctx, store, accountID, userID); err != nil {
|
||||||
fail("❌ 保存 cookie 失败: %v\n", err)
|
fail("❌ %v\n", err)
|
||||||
}
|
}
|
||||||
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
|
|
||||||
fail("❌ 禁用验证账号失败: %v\n", err)
|
|
||||||
}
|
|
||||||
// 再 Save 一次验证 upsert
|
|
||||||
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
|
|
||||||
fail("❌ 二次保存 cookie 失败: %v\n", err)
|
|
||||||
}
|
|
||||||
v, _ := store.Cookies.GetValue(ctx, accountID)
|
|
||||||
fmt.Printf("✅ cookie upsert 成功,value=%s\n", v)
|
|
||||||
|
|
||||||
// 3) 系统设置 upsert(dialectUpsert + key 保留字引用)
|
|
||||||
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
|
|
||||||
fail("❌ 系统设置 Set 失败: %v\n", err)
|
|
||||||
}
|
|
||||||
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
|
|
||||||
fail("❌ 系统设置二次 Set 失败: %v\n", err)
|
|
||||||
}
|
|
||||||
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
|
|
||||||
|
|
||||||
// 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE)
|
// 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE)
|
||||||
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
|
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
|
||||||
@@ -123,7 +125,8 @@ func main() {
|
|||||||
}); err != nil {
|
}); err != nil {
|
||||||
fail("❌ 商品 Upsert 失败: %v\n", err)
|
fail("❌ 商品 Upsert 失败: %v\n", err)
|
||||||
}
|
}
|
||||||
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Items.Upsert(ctx, &db.ItemInfoRow{
|
||||||
CookieID: accountID, ItemID: itemID, ItemTitle: "更新后商品", ItemPrice: "29.90",
|
CookieID: accountID, ItemID: itemID, ItemTitle: "更新后商品", ItemPrice: "29.90",
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
fail("❌ 商品二次 Upsert 失败: %v\n", err)
|
fail("❌ 商品二次 Upsert 失败: %v\n", err)
|
||||||
@@ -153,7 +156,8 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
fail("❌ 创建通知渠道失败: %v\n", err)
|
fail("❌ 创建通知渠道失败: %v\n", err)
|
||||||
}
|
}
|
||||||
if err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
|
||||||
fail("❌ 绑定通知渠道失败: %v\n", err)
|
fail("❌ 绑定通知渠道失败: %v\n", err)
|
||||||
}
|
}
|
||||||
fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID)
|
fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID)
|
||||||
@@ -166,6 +170,7 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
fail("❌ 创建自动化规则失败: %v\n", err)
|
fail("❌ 创建自动化规则失败: %v\n", err)
|
||||||
}
|
}
|
||||||
|
// runID、started、err 用于本次流程后续判断的运行ID、started、err
|
||||||
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
|
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||||
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
|
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
|
||||||
})
|
})
|
||||||
@@ -184,8 +189,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID)
|
fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID)
|
||||||
|
|
||||||
if err := cleanup(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
fmt.Printf("❌ 清理验证数据失败: %v\n", err)
|
err := cleanup(); err != nil {
|
||||||
|
fmt.Printf("❌ 清理验证数据失败: %s\n", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
cleanup = nil
|
cleanup = nil
|
||||||
@@ -193,12 +199,64 @@ func main() {
|
|||||||
fmt.Println("\n🎉 全部验证通过")
|
fmt.Println("\n🎉 全部验证通过")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// verifyCookieAndSettings 验证 Cookie 状态写入、重复 upsert 和保留字设置项的跨方言行为。
|
||||||
|
func verifyCookieAndSettings(ctx context.Context, store *db.Store, accountID string, userID int64) error {
|
||||||
|
// firstCookie 是首次保存的非敏感测试 Cookie;secondCookie 用于确认重复保存会覆盖同一账号记录。
|
||||||
|
const firstCookie = "unb=123; _m_h5_tk=tk_1;"
|
||||||
|
// secondCookie 是第二次 upsert 使用的测试凭证,用于验证已存在账号记录会被安全覆盖。
|
||||||
|
const secondCookie = "unb=123; _m_h5_tk=tk_2;"
|
||||||
|
// err 保存首次 Cookie 写入失败原因,调用方据此输出脱敏诊断并执行清理。
|
||||||
|
if err := store.Cookies.Save(ctx, accountID, firstCookie, userID); err != nil {
|
||||||
|
return fmt.Errorf("保存 cookie 失败: %w", err)
|
||||||
|
}
|
||||||
|
// err 保存账号状态写入失败原因,状态记录必须与 Cookie 记录一并跨方言验证。
|
||||||
|
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
|
||||||
|
return fmt.Errorf("禁用验证账号失败: %w", err)
|
||||||
|
}
|
||||||
|
// err 保存覆盖式 Cookie 写入失败原因,失败表示方言 upsert 语义不满足验证要求。
|
||||||
|
if err := store.Cookies.Save(ctx, accountID, secondCookie, userID); err != nil {
|
||||||
|
return fmt.Errorf("二次保存 cookie 失败: %w", err)
|
||||||
|
}
|
||||||
|
// savedCookie 是读取回来的值;fingerprint 仅输出不可逆摘要,避免验证日志泄露完整 Cookie。
|
||||||
|
savedCookie, _ := store.Cookies.GetValue(ctx, accountID)
|
||||||
|
// fingerprint 是读取结果的不可逆摘要,只用于确认更新结果且不得输出完整 Cookie。
|
||||||
|
fingerprint := sha256.Sum256([]byte(savedCookie))
|
||||||
|
fmt.Printf("✅ cookie upsert 成功,length=%d fingerprint=%x\n", len(savedCookie), fingerprint[:8])
|
||||||
|
// err 保存首次设置写入失败原因,数据库方言必须正确处理 key 保留字。
|
||||||
|
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
|
||||||
|
return fmt.Errorf("系统设置 Set 失败: %w", err)
|
||||||
|
}
|
||||||
|
// err 保存第二次设置写入失败原因,用于确认相同键会执行更新而非重复插入。
|
||||||
|
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
|
||||||
|
return fmt.Errorf("系统设置二次 Set 失败: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// safeDiagnosticArgs 将错误参数转换为脱敏文本,避免验证工具把连接凭证写到终端。
|
||||||
|
func safeDiagnosticArgs(args []any) []any {
|
||||||
|
// safeArgs 保存经过错误脱敏的格式化参数;非错误参数保持原有类型和格式语义。
|
||||||
|
safeArgs := append([]any(nil), args...)
|
||||||
|
// index 表示当前格式化参数下标;value 表示待检查的原始参数。
|
||||||
|
for index, value := range safeArgs {
|
||||||
|
// errValue 表示当前参数是否为错误对象。
|
||||||
|
if errValue, ok := value.(error); ok {
|
||||||
|
safeArgs[index] = logsafe.Error(errValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return safeArgs
|
||||||
|
}
|
||||||
|
|
||||||
|
// maskURL 封装maskURL业务协调。
|
||||||
func maskURL(url string) string {
|
func maskURL(url string) string {
|
||||||
// 只显示 scheme 和 host,把 scheme 后到首个 '@' 之间的凭证替换为 ***。
|
// 只显示 scheme 和 host,把 scheme 后到首个 '@' 之间的凭证替换为 ***。
|
||||||
for _, p := range []string{"mysql://", "postgres://", "postgresql://"} {
|
for _, p := range []string{"mysql://", "postgres://", "postgresql://"} {
|
||||||
if len(url) > len(p) && url[:len(p)] == p {
|
if len(url) > len(p) && url[:len(p)] == p {
|
||||||
|
// rest 用于本次流程后续判断的rest
|
||||||
rest := url[len(p):]
|
rest := url[len(p):]
|
||||||
if at := strings.Index(rest, "@"); at >= 0 {
|
if // at 用于本次流程后续判断的at
|
||||||
|
at := strings.Index(rest, "@"); at >= 0 {
|
||||||
return p + "***@" + rest[at+1:]
|
return p + "***@" + rest[at+1:]
|
||||||
}
|
}
|
||||||
return url
|
return url
|
||||||
@@ -207,6 +265,7 @@ func maskURL(url string) string {
|
|||||||
return url
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// verifyIDs 用于本次流程后续判断的verifyIDs
|
||||||
type verifyIDs struct {
|
type verifyIDs struct {
|
||||||
username string
|
username string
|
||||||
accountID string
|
accountID string
|
||||||
@@ -215,7 +274,9 @@ type verifyIDs struct {
|
|||||||
buyerID string
|
buyerID string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newVerifyIDs 封装newVerifyIDs业务协调。
|
||||||
func newVerifyIDs(n int64) verifyIDs {
|
func newVerifyIDs(n int64) verifyIDs {
|
||||||
|
// suffix 用于本次流程后续判断的suffix
|
||||||
suffix := fmt.Sprintf("%d", n)
|
suffix := fmt.Sprintf("%d", n)
|
||||||
return verifyIDs{
|
return verifyIDs{
|
||||||
username: "verify_" + suffix,
|
username: "verify_" + suffix,
|
||||||
@@ -226,19 +287,26 @@ func newVerifyIDs(n int64) verifyIDs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newVerifyPassword 封装newVerify密码业务协调。
|
||||||
func newVerifyPassword() (string, error) {
|
func newVerifyPassword() (string, error) {
|
||||||
|
// b 用于本次流程后续判断的b
|
||||||
var b [24]byte
|
var b [24]byte
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := rand.Read(b[:]); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return "verify_" + hex.EncodeToString(b[:]), nil
|
return "verify_" + hex.EncodeToString(b[:]), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanupVerifyData 封装cleanupVerify数据业务协调。
|
||||||
func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) error {
|
func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) error {
|
||||||
|
// userID 用于本次流程后续判断的用户ID
|
||||||
userID := int64(0)
|
userID := int64(0)
|
||||||
if user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
|
if // user、err 用于本次流程后续判断的user、err
|
||||||
|
user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
|
||||||
userID = user.ID
|
userID = user.ID
|
||||||
}
|
}
|
||||||
|
// queries 用于本次流程后续判断的queries
|
||||||
queries := []struct {
|
queries := []struct {
|
||||||
query string
|
query string
|
||||||
args []any
|
args []any
|
||||||
@@ -256,8 +324,10 @@ func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) erro
|
|||||||
{`DELETE FROM sessions WHERE user_id=?`, []any{userID}},
|
{`DELETE FROM sessions WHERE user_id=?`, []any{userID}},
|
||||||
{`DELETE FROM users WHERE username=? AND email=?`, []any{ids.username, ids.username + "@test.local"}},
|
{`DELETE FROM users WHERE username=? AND email=?`, []any{ids.username, ids.username + "@test.local"}},
|
||||||
}
|
}
|
||||||
|
// q 表示当前遍历过程中的q
|
||||||
for _, q := range queries {
|
for _, q := range queries {
|
||||||
if _, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+47
-11
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
// TestMaskURL 验证带凭证的数据库 URL 脱敏:保留 scheme + host,密码替换为 ***。
|
// TestMaskURL 验证带凭证的数据库 URL 脱敏:保留 scheme + host,密码替换为 ***。
|
||||||
func TestMaskURL(t *testing.T) {
|
func TestMaskURL(t *testing.T) {
|
||||||
|
// cases 用于本次流程后续判断的cases
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
|
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
|
||||||
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
|
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
|
||||||
@@ -18,15 +19,20 @@ func TestMaskURL(t *testing.T) {
|
|||||||
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
|
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
|
||||||
"/local/path.db": "/local/path.db", // 非 URL,原样
|
"/local/path.db": "/local/path.db", // 非 URL,原样
|
||||||
}
|
}
|
||||||
|
// in、want 表示当前遍历过程中的in、want
|
||||||
for in, want := range cases {
|
for in, want := range cases {
|
||||||
if got := maskURL(in); got != want {
|
if // got 用于本次流程后续判断的got
|
||||||
|
got := maskURL(in); got != want {
|
||||||
t.Errorf("maskURL(%q) = %q; want %q", in, got, want)
|
t.Errorf("maskURL(%q) = %q; want %q", in, got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestNewVerifyIDsAreUniqueForPersistentRuns 封装TestNewVerifyIDsAreUniqueForPersistent运行记录业务协调。
|
||||||
func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
|
func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
|
||||||
|
// ids 用于本次流程后续判断的ids
|
||||||
ids := newVerifyIDs(12345)
|
ids := newVerifyIDs(12345)
|
||||||
|
// want 用于本次流程后续判断的want
|
||||||
want := map[string]string{
|
want := map[string]string{
|
||||||
"username": "verify_12345",
|
"username": "verify_12345",
|
||||||
"accountID": "acc_12345",
|
"accountID": "acc_12345",
|
||||||
@@ -34,6 +40,7 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
|
|||||||
"itemID": "item_12345",
|
"itemID": "item_12345",
|
||||||
"buyerID": "buyer_12345",
|
"buyerID": "buyer_12345",
|
||||||
}
|
}
|
||||||
|
// got 用于本次流程后续判断的got
|
||||||
got := map[string]string{
|
got := map[string]string{
|
||||||
"username": ids.username,
|
"username": ids.username,
|
||||||
"accountID": ids.accountID,
|
"accountID": ids.accountID,
|
||||||
@@ -41,6 +48,7 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
|
|||||||
"itemID": ids.itemID,
|
"itemID": ids.itemID,
|
||||||
"buyerID": ids.buyerID,
|
"buyerID": ids.buyerID,
|
||||||
}
|
}
|
||||||
|
// key、wantValue 表示当前遍历过程中的key、want值
|
||||||
for key, wantValue := range want {
|
for key, wantValue := range want {
|
||||||
if got[key] != wantValue {
|
if got[key] != wantValue {
|
||||||
t.Fatalf("%s=%q want %q", key, got[key], wantValue)
|
t.Fatalf("%s=%q want %q", key, got[key], wantValue)
|
||||||
@@ -51,11 +59,14 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestNewVerifyPasswordIsNotFixedDefault 封装TestNewVerify密码IsNotFixedDefault业务协调。
|
||||||
func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
|
func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
|
||||||
|
// first、err 用于本次流程后续判断的first、err
|
||||||
first, err := newVerifyPassword()
|
first, err := newVerifyPassword()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("newVerifyPassword: %v", err)
|
t.Fatalf("newVerifyPassword: %v", err)
|
||||||
}
|
}
|
||||||
|
// second、err 用于本次流程后续判断的second、err
|
||||||
second, err := newVerifyPassword()
|
second, err := newVerifyPassword()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("newVerifyPassword second: %v", err)
|
t.Fatalf("newVerifyPassword second: %v", err)
|
||||||
@@ -68,24 +79,32 @@ func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled 封装TestCleanupVerify数据RemovesRowsAndVerify数据IsDisabled业务协调。
|
||||||
func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
|
func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
|
||||||
|
// ctx 用于本次流程后续判断的ctx
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// database、dialect、err 用于本次流程后续判断的database、dialect、err
|
||||||
database, dialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "verify.db"))
|
database, dialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "verify.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Open: %v", err)
|
t.Fatalf("Open: %v", err)
|
||||||
}
|
}
|
||||||
defer database.Close()
|
defer database.Close()
|
||||||
|
// store 用于本次流程后续判断的store
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
|
// ids 用于本次流程后续判断的ids
|
||||||
ids := newVerifyIDs(987654321)
|
ids := newVerifyIDs(987654321)
|
||||||
|
|
||||||
|
// password、err 用于本次流程后续判断的password、err
|
||||||
password, err := newVerifyPassword()
|
password, err := newVerifyPassword()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("newVerifyPassword: %v", err)
|
t.Fatalf("newVerifyPassword: %v", err)
|
||||||
}
|
}
|
||||||
|
// ok、err 用于本次流程后续判断的ok、err
|
||||||
ok, err := store.Users.Create(ctx, ids.username, ids.username+"@test.local", password)
|
ok, err := store.Users.Create(ctx, ids.username, ids.username+"@test.local", password)
|
||||||
if err != nil || !ok {
|
if err != nil || !ok {
|
||||||
t.Fatalf("Create user: ok=%v err=%v", ok, err)
|
t.Fatalf("Create user: ok=%v err=%v", ok, err)
|
||||||
}
|
}
|
||||||
|
// user、err 用于本次流程后续判断的user、err
|
||||||
user, err := store.Users.GetByUsername(ctx, ids.username)
|
user, err := store.Users.GetByUsername(ctx, ids.username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("GetByUsername: %v", err)
|
t.Fatalf("GetByUsername: %v", err)
|
||||||
@@ -93,41 +112,51 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
|
|||||||
if user.IsAdmin {
|
if user.IsAdmin {
|
||||||
t.Fatal("dbverify 创建的验证用户不应是管理员")
|
t.Fatal("dbverify 创建的验证用户不应是管理员")
|
||||||
}
|
}
|
||||||
if err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
|
||||||
t.Fatalf("Save cookie: %v", err)
|
t.Fatalf("Save cookie: %v", err)
|
||||||
}
|
}
|
||||||
if err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
|
||||||
t.Fatalf("SetStatus false: %v", err)
|
t.Fatalf("SetStatus false: %v", err)
|
||||||
}
|
}
|
||||||
if store.Cookies.GetStatus(ctx, ids.accountID) {
|
if store.Cookies.GetStatus(ctx, ids.accountID) {
|
||||||
t.Fatal("dbverify 验证账号应默认禁用,避免被服务启动")
|
t.Fatal("dbverify 验证账号应默认禁用,避免被服务启动")
|
||||||
}
|
}
|
||||||
if err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
|
||||||
t.Fatalf("Orders.Upsert: %v", err)
|
t.Fatalf("Orders.Upsert: %v", err)
|
||||||
}
|
}
|
||||||
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
|
||||||
t.Fatalf("Items.Upsert: %v", err)
|
t.Fatalf("Items.Upsert: %v", err)
|
||||||
}
|
}
|
||||||
|
// cardID、err 用于本次流程后续判断的卡密ID、err
|
||||||
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "测试卡组", Type: "data", DataContent: "card", Enabled: true, UserID: user.ID})
|
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "测试卡组", Type: "data", DataContent: "card", Enabled: true, UserID: user.ID})
|
||||||
if err != nil || cardID == 0 {
|
if err != nil || cardID == 0 {
|
||||||
t.Fatalf("Cards.Create: id=%d err=%v", cardID, err)
|
t.Fatalf("Cards.Create: id=%d err=%v", cardID, err)
|
||||||
}
|
}
|
||||||
|
// channelID、err 用于本次流程后续判断的渠道ID、err
|
||||||
channelID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
|
channelID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
|
||||||
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: user.ID,
|
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: user.ID,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("CreateChannel: %v", err)
|
t.Fatalf("CreateChannel: %v", err)
|
||||||
}
|
}
|
||||||
|
// channelEnabled 用于本次流程后续判断的渠道启用状态
|
||||||
var channelEnabled int
|
var channelEnabled int
|
||||||
if err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
|
||||||
t.Fatalf("query channel enabled: %v", err)
|
t.Fatalf("query channel enabled: %v", err)
|
||||||
}
|
}
|
||||||
if channelEnabled != 0 {
|
if channelEnabled != 0 {
|
||||||
t.Fatal("dbverify 验证通知渠道应默认禁用")
|
t.Fatal("dbverify 验证通知渠道应默认禁用")
|
||||||
}
|
}
|
||||||
if err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
|
||||||
t.Fatalf("SetBindings: %v", err)
|
t.Fatalf("SetBindings: %v", err)
|
||||||
}
|
}
|
||||||
|
// ruleID、err 用于本次流程后续判断的规则ID、err
|
||||||
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||||
UserID: user.ID, CookieID: ids.accountID, ItemID: ids.itemID, Name: "付款发货",
|
UserID: user.ID, CookieID: ids.accountID, ItemID: ids.itemID, Name: "付款发货",
|
||||||
TriggerType: "order_paid", Enabled: false, Priority: 100,
|
TriggerType: "order_paid", Enabled: false, Priority: 100,
|
||||||
@@ -135,22 +164,28 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Automation.Create: %v", err)
|
t.Fatalf("Automation.Create: %v", err)
|
||||||
}
|
}
|
||||||
if _, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
|
if // started、err 用于本次流程后续判断的started、err
|
||||||
|
_, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||||
RuleID: ruleID, CookieID: ids.accountID, TriggerType: "order_paid", TriggerKey: ids.orderID, Status: "running",
|
RuleID: ruleID, CookieID: ids.accountID, TriggerType: "order_paid", TriggerKey: ids.orderID, Status: "running",
|
||||||
}); err != nil || !started {
|
}); err != nil || !started {
|
||||||
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
|
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := cleanupVerifyData(ctx, store, ids); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := cleanupVerifyData(ctx, store, ids); err != nil {
|
||||||
t.Fatalf("cleanupVerifyData: %v", err)
|
t.Fatalf("cleanupVerifyData: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
|
||||||
t.Fatalf("验证用户应被清理,err=%v", err)
|
t.Fatalf("验证用户应被清理,err=%v", err)
|
||||||
}
|
}
|
||||||
if _, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
|
||||||
t.Fatalf("验证账号应被清理,err=%v", err)
|
t.Fatalf("验证账号应被清理,err=%v", err)
|
||||||
}
|
}
|
||||||
|
// count 用于本次流程后续判断的数量
|
||||||
var count int
|
var count int
|
||||||
|
// name、query 表示当前遍历过程中的name、query
|
||||||
for name, query := range map[string]string{
|
for name, query := range map[string]string{
|
||||||
"automation_runs": `SELECT COUNT(*) FROM automation_runs WHERE cookie_id=? OR trigger_key=?`,
|
"automation_runs": `SELECT COUNT(*) FROM automation_runs WHERE cookie_id=? OR trigger_key=?`,
|
||||||
"automation_rules": `SELECT COUNT(*) FROM automation_rules WHERE cookie_id=? OR item_id=?`,
|
"automation_rules": `SELECT COUNT(*) FROM automation_rules WHERE cookie_id=? OR item_id=?`,
|
||||||
@@ -158,6 +193,7 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
|
|||||||
"orders": `SELECT COUNT(*) FROM orders WHERE cookie_id=? OR order_id=?`,
|
"orders": `SELECT COUNT(*) FROM orders WHERE cookie_id=? OR order_id=?`,
|
||||||
"items": `SELECT COUNT(*) FROM item_info WHERE cookie_id=? OR item_id=?`,
|
"items": `SELECT COUNT(*) FROM item_info WHERE cookie_id=? OR item_id=?`,
|
||||||
} {
|
} {
|
||||||
|
// err 用于本次流程后续判断的err
|
||||||
var err error
|
var err error
|
||||||
switch name {
|
switch name {
|
||||||
case "automation_runs", "orders":
|
case "automation_runs", "orders":
|
||||||
|
|||||||
+58
-15
@@ -18,10 +18,14 @@ import (
|
|||||||
|
|
||||||
"xianyu-go/internal/auth"
|
"xianyu-go/internal/auth"
|
||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
|
"xianyu-go/internal/logsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
|
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
|
||||||
|
// dbURL 用于本次流程后续判断的dbURL
|
||||||
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
@@ -34,75 +38,93 @@ func main() {
|
|||||||
resolved = *dbPath
|
resolved = *dbPath
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil {
|
||||||
fatalf("初始化管理员失败: %v", err)
|
fatalf("初始化管理员失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为
|
// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为
|
||||||
// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。
|
// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。
|
||||||
|
// run 封装运行业务协调。
|
||||||
func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error {
|
func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error {
|
||||||
|
// database、dialect、err 用于本次流程后续判断的database、dialect、err
|
||||||
database, dialect, err := db.Open(ctx, resolved)
|
database, dialect, err := db.Open(ctx, resolved)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("打开数据库失败: %w", err)
|
return fmt.Errorf("打开数据库失败: %w", err)
|
||||||
}
|
}
|
||||||
defer database.Close()
|
defer database.Close()
|
||||||
|
// store 用于本次流程后续判断的store
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
|
|
||||||
|
// existing、err 用于本次流程后续判断的existing、err
|
||||||
existing, err := store.Users.GetAdmin(ctx)
|
existing, err := store.Users.GetAdmin(ctx)
|
||||||
if err != nil && !isNotFound(err) {
|
if err != nil && !isNotFound(err) {
|
||||||
return fmt.Errorf("查询 admin 失败: %w", err)
|
return fmt.Errorf("查询 admin 失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if existing != nil {
|
if existing != nil {
|
||||||
if _, err := fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprint(out, "是否重置管理员密码?(y/N): "); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprint(out, "是否重置管理员密码?(y/N): "); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// ans 用于本次流程后续判断的ans
|
||||||
ans, _ := reader.ReadString('\n')
|
ans, _ := reader.ReadString('\n')
|
||||||
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
|
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
|
||||||
if _, err := fmt.Fprintln(out, "跳过初始化"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out, "跳过初始化"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
// pw、err 用于本次流程后续判断的pw、err
|
||||||
pw, err := promptPasswordTwice(reader, out)
|
pw, err := promptPasswordTwice(reader, out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("读取密码失败: %w", err)
|
return fmt.Errorf("读取密码失败: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
|
||||||
return fmt.Errorf("重置 admin 密码失败: %w", err)
|
return fmt.Errorf("重置 admin 密码失败: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := fmt.Fprintln(out, "=== 初始化管理员账号(CLI)==="); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out, "=== 初始化管理员账号(CLI)==="); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprint(out, "请输入管理员邮箱: "); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprint(out, "请输入管理员邮箱: "); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// email 用于本次流程后续判断的邮箱
|
||||||
email, _ := reader.ReadString('\n')
|
email, _ := reader.ReadString('\n')
|
||||||
email = strings.TrimSpace(email)
|
email = strings.TrimSpace(email)
|
||||||
if email == "" {
|
if email == "" {
|
||||||
return errors.New("邮箱不能为空")
|
return errors.New("邮箱不能为空")
|
||||||
}
|
}
|
||||||
|
// pw、err 用于本次流程后续判断的pw、err
|
||||||
pw, err := promptPasswordTwice(reader, out)
|
pw, err := promptPasswordTwice(reader, out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("读取密码失败: %w", err)
|
return fmt.Errorf("读取密码失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// created、err 用于本次流程后续判断的created、err
|
||||||
created, err := auth.InitAdmin(ctx, store, email, pw)
|
created, err := auth.InitAdmin(ctx, store, email, pw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("创建 admin 用户失败:%w", err)
|
return fmt.Errorf("创建 admin 用户失败:%w", err)
|
||||||
}
|
}
|
||||||
if created {
|
if created {
|
||||||
if _, err := fmt.Fprintln(out, "初始化完成:已创建 admin 用户"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out, "初始化完成:已创建 admin 用户"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,22 +134,26 @@ func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writ
|
|||||||
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
|
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
|
||||||
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) {
|
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) {
|
||||||
for {
|
for {
|
||||||
|
// p1、err 用于本次流程后续判断的p1、err
|
||||||
p1, err := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
|
p1, err := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if p1 == "" {
|
if p1 == "" {
|
||||||
if _, err := fmt.Fprintln(out, "密码不能为空"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out, "密码不能为空"); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// p2、err 用于本次流程后续判断的p2、err
|
||||||
p2, err := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
|
p2, err := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if p1 != p2 {
|
if p1 != p2 {
|
||||||
if _, err := fmt.Fprintln(out, "两次输入不一致,请重试"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out, "两次输入不一致,请重试"); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
@@ -138,16 +164,20 @@ func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) {
|
|||||||
|
|
||||||
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
|
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
|
||||||
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
|
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
|
||||||
|
// readPasswordNoEcho 封装read密码NoEcho业务协调。
|
||||||
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (string, error) {
|
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (string, error) {
|
||||||
if _, err := fmt.Fprint(out, prompt); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprint(out, prompt); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||||
|
// b、err 用于本次流程后续判断的b、err
|
||||||
b, err := term.ReadPassword(int(os.Stdin.Fd()))
|
b, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprintln(out); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return strings.TrimSpace(string(b)), nil
|
return strings.TrimSpace(string(b)), nil
|
||||||
@@ -157,16 +187,29 @@ func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (str
|
|||||||
if err != nil && !errors.Is(err, io.EOF) {
|
if err != nil && !errors.Is(err, io.EOF) {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprintln(out); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintln(out); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return strings.TrimSpace(s), nil
|
return strings.TrimSpace(s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isNotFound 封装isNotFound业务协调。
|
||||||
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
|
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
|
||||||
|
|
||||||
|
// fatalf 封装fatalf业务协调。
|
||||||
func fatalf(format string, a ...any) {
|
func fatalf(format string, a ...any) {
|
||||||
if _, err := fmt.Fprintf(os.Stderr, format+"\n", a...); err != nil {
|
// safeArgs 保存经过错误脱敏的初始化错误参数,避免数据库连接凭证进入终端。
|
||||||
|
safeArgs := append([]any(nil), a...)
|
||||||
|
// index 表示当前格式化参数下标;value 表示待检查的原始参数。
|
||||||
|
for index, value := range safeArgs {
|
||||||
|
// errValue 表示当前参数是否为错误对象。
|
||||||
|
if errValue, ok := value.(error); ok {
|
||||||
|
safeArgs[index] = logsafe.Error(errValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := fmt.Fprintf(os.Stderr, format+"\n", safeArgs...); err != nil {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
@@ -14,9 +14,13 @@ import (
|
|||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestRunCreatesAdminInTemporaryDatabase 封装Test运行CreatesAdminInTemporaryDatabase业务协调。
|
||||||
func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
|
func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||||
|
// out 用于本次流程后续判断的out
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
|
// err 用于本次流程后续判断的err
|
||||||
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out)
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("run create: %v", err)
|
t.Fatalf("run create: %v", err)
|
||||||
@@ -24,25 +28,33 @@ func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
|
|||||||
if !strings.Contains(out.String(), "初始化完成") {
|
if !strings.Contains(out.String(), "初始化完成") {
|
||||||
t.Fatalf("missing create confirmation: %s", out.String())
|
t.Fatalf("missing create confirmation: %s", out.String())
|
||||||
}
|
}
|
||||||
|
// d、dialect、err 用于本次流程后续判断的d、dialect、err
|
||||||
d, dialect, err := db.Open(context.Background(), dbPath)
|
d, dialect, err := db.Open(context.Background(), dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer d.Close()
|
defer d.Close()
|
||||||
|
// admin、err 用于本次流程后续判断的admin、err
|
||||||
admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background())
|
admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background())
|
||||||
if err != nil || admin == nil || admin.Email != "admin@example.com" {
|
if err != nil || admin == nil || admin.Email != "admin@example.com" {
|
||||||
t.Fatalf("admin=%+v err=%v", admin, err)
|
t.Fatalf("admin=%+v err=%v", admin, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunExistingAdminCanSkipReset 封装Test运行ExistingAdminCanSkipReset业务协调。
|
||||||
func TestRunExistingAdminCanSkipReset(t *testing.T) {
|
func TestRunExistingAdminCanSkipReset(t *testing.T) {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||||
|
// input 用于本次流程后续判断的input
|
||||||
input := "admin@example.com\nsecret\nsecret\n"
|
input := "admin@example.com\nsecret\nsecret\n"
|
||||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// out 用于本次流程后续判断的out
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "跳过初始化") {
|
if !strings.Contains(out.String(), "跳过初始化") {
|
||||||
@@ -50,43 +62,59 @@ func TestRunExistingAdminCanSkipReset(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunExistingAdminResetsPasswordAfterMismatchRetry 封装Test运行ExistingAdminResets密码AfterMismatch重试业务协调。
|
||||||
func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) {
|
func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// input 用于本次流程后续判断的input
|
||||||
input := "y\nnew\nnot-the-same\nnew\nnew\n"
|
input := "y\nnew\nnot-the-same\nnew\nnew\n"
|
||||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// d、dialect、err 用于本次流程后续判断的d、dialect、err
|
||||||
d, dialect, err := db.Open(context.Background(), dbPath)
|
d, dialect, err := db.Open(context.Background(), dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer d.Close()
|
defer d.Close()
|
||||||
|
// store 用于本次流程后续判断的store
|
||||||
store := db.NewStore(d, dialect)
|
store := db.NewStore(d, dialect)
|
||||||
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok {
|
if // ok 用于本次流程后续判断的ok
|
||||||
|
_, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok {
|
||||||
t.Fatal("old password should be invalid")
|
t.Fatal("old password should be invalid")
|
||||||
}
|
}
|
||||||
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok {
|
if // ok 用于本次流程后续判断的ok
|
||||||
|
_, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok {
|
||||||
t.Fatal("new password should be valid")
|
t.Fatal("new password should be valid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunRejectsEmptyEmail 封装Test运行RejectsEmpty邮箱业务协调。
|
||||||
func TestRunRejectsEmptyEmail(t *testing.T) {
|
func TestRunRejectsEmptyEmail(t *testing.T) {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||||
|
// err 用于本次流程后续判断的err
|
||||||
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{})
|
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{})
|
||||||
if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") {
|
if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") {
|
||||||
t.Fatalf("err=%v, want empty email error", err)
|
t.Fatalf("err=%v, want empty email error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestMainCLIEntrypointUsesDatabaseFlag 封装TestMainCLIEntrypointUsesDatabaseFlag业务协调。
|
||||||
func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) {
|
func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) {
|
||||||
|
// dbPath 用于本次流程后续判断的db路径
|
||||||
dbPath := filepath.Join(t.TempDir(), "main.db")
|
dbPath := filepath.Join(t.TempDir(), "main.db")
|
||||||
|
// stdin、writer、err 用于本次流程后续判断的stdin、writer、err
|
||||||
stdin, writer, err := os.Pipe()
|
stdin, writer, err := os.Pipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// oldArgs、oldStdin、oldEnv、oldCommandLine 用于本次流程后续判断的oldArgs、oldStdin、oldEnv、oldCommandLine
|
||||||
oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine
|
oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine
|
||||||
defer func() {
|
defer func() {
|
||||||
os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine
|
os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine
|
||||||
|
|||||||
+410
-97
@@ -5,32 +5,31 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"database/sql"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"xianyu-go/internal/account"
|
|
||||||
"xianyu-go/internal/adapter"
|
|
||||||
"xianyu-go/internal/auth"
|
"xianyu-go/internal/auth"
|
||||||
"xianyu-go/internal/automation"
|
compositionruntime "xianyu-go/internal/composition/runtime"
|
||||||
"xianyu-go/internal/browser"
|
|
||||||
"xianyu-go/internal/chat"
|
|
||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
"xianyu-go/internal/logging"
|
"xianyu-go/internal/logging"
|
||||||
"xianyu-go/internal/notify"
|
"xianyu-go/internal/logsafe"
|
||||||
"xianyu-go/internal/renewal"
|
appversion "xianyu-go/internal/version"
|
||||||
"xianyu-go/internal/server"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// serverOptions 保存命令行和环境变量解析后的进程启动选项。
|
||||||
type serverOptions struct {
|
type serverOptions struct {
|
||||||
dbPath string
|
dbPath string
|
||||||
dbURL string
|
dbURL string
|
||||||
@@ -51,41 +50,142 @@ type serverOptions struct {
|
|||||||
adminEmail string
|
adminEmail string
|
||||||
adminPassword string
|
adminPassword string
|
||||||
service bool
|
service bool
|
||||||
|
showVersion bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// defaultDBPath 保存默认 SQLite 数据库的相对路径;桌面运行时会根据 dataDir 重定位。
|
||||||
const (
|
const (
|
||||||
defaultDBPath = "data/xianyu_data.db"
|
defaultDBPath = "data/xianyu_data.db"
|
||||||
userDataDirName = "YdisksXianyuHelper"
|
userDataDirName = "YdisksXianyuHelper"
|
||||||
defaultDataKeyName = "data-key"
|
defaultDataKeyName = "data-key"
|
||||||
|
// httpShutdownTimeout 限制 HTTP 请求排空和 Server 自有后台任务等待时长。
|
||||||
|
httpShutdownTimeout = 10 * time.Second
|
||||||
|
// applicationShutdownTimeout 限制应用 worker 收到取消后的独立收束和 Join 时长。
|
||||||
|
applicationShutdownTimeout = 10 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// errDataKeyEmpty 表示已打开的数据密钥文件尚未包含有效内容;并发读取者可以有限等待写入者完成。
|
||||||
|
var errDataKeyEmpty = errors.New("data key 文件为空")
|
||||||
|
|
||||||
|
// serverStartupConfig 保存目录、数据库和日志策略准备阶段的派生配置。
|
||||||
|
type serverStartupConfig struct {
|
||||||
|
// dataDir 是桌面服务或显式 workdir 使用的应用数据目录,空值表示沿用当前目录布局。
|
||||||
|
dataDir string
|
||||||
|
// resolvedDBURL 是按环境变量、命令行和默认路径优先级解析出的数据库地址。
|
||||||
|
resolvedDBURL string
|
||||||
|
// explicitLogLevel 表示日志等级是否由环境变量或命令行显式指定,显式值优先于数据库设置。
|
||||||
|
explicitLogLevel bool
|
||||||
|
// explicitLogFormat 表示日志格式是否由环境变量或命令行显式指定,显式值优先于数据库设置。
|
||||||
|
explicitLogFormat bool
|
||||||
|
// resolvedLogFormat 是启动时选择的初始日志输出格式。
|
||||||
|
resolvedLogFormat string
|
||||||
|
}
|
||||||
|
|
||||||
|
// serverInfrastructure 保存数据库、日志和加密设置已就绪的基础设施,并集中承担关闭责任。
|
||||||
|
type serverInfrastructure struct {
|
||||||
|
// database 是已完成迁移并由本进程独占关闭的数据库连接池。
|
||||||
|
database *sql.DB
|
||||||
|
// store 提供应用服务使用的数据库仓储集合。
|
||||||
|
store *db.Store
|
||||||
|
// logger 是同时写入标准输出或服务日志文件的结构化日志器。
|
||||||
|
logger *slog.Logger
|
||||||
|
// logWriter 是 logger 使用的输出目标,关闭由 closeLog 负责。
|
||||||
|
logWriter io.Writer
|
||||||
|
// closeLog 释放服务日志文件;标准输出场景下该函数为空操作。
|
||||||
|
closeLog func()
|
||||||
|
// initializationOnly 表示本次调用仅完成 -init-admin 管理员初始化,调用方不得继续启动运行时。
|
||||||
|
initializationOnly bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// close 逆序释放日志文件和数据库连接,允许基础设施初始化失败路径统一调用。
|
||||||
|
func (i serverInfrastructure) close() {
|
||||||
|
if i.database != nil {
|
||||||
|
_ = i.database.Close()
|
||||||
|
}
|
||||||
|
if i.closeLog != nil {
|
||||||
|
i.closeLog()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// serverRuntime 保存 HTTP 服务及应用生命周期协调器,二者必须由同一 Context 启动和关闭。
|
||||||
|
type serverRuntime struct {
|
||||||
|
// httpServer 是已完成依赖注入、尚未启动监听的 HTTP 服务。
|
||||||
|
httpServer httpRuntime
|
||||||
|
// lifecycleCoordinator 按登记顺序启动组件并按逆序关闭后台 worker。
|
||||||
|
lifecycleCoordinator applicationRuntimeCoordinator
|
||||||
|
}
|
||||||
|
|
||||||
|
// httpRuntimeStopper 定义进程关闭阶段需要的最小 HTTP 停止能力。
|
||||||
|
// Stop 必须只收束 HTTP 请求和 Server 自有任务,不能等待应用 worker。
|
||||||
|
type httpRuntimeStopper interface {
|
||||||
|
// Stop 在调用方提供的独立 HTTP 关闭 Context 内完成请求排空。
|
||||||
|
Stop(context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// httpRuntime 定义正常进程启动、等待和关闭 HTTP 服务所需的完整能力。
|
||||||
|
type httpRuntime interface {
|
||||||
|
// Bind 在启动后台组件前同步占用 HTTP 监听端口。
|
||||||
|
Bind() error
|
||||||
|
// Start 开始接收 HTTP 请求。
|
||||||
|
Start(context.Context) error
|
||||||
|
// Wait 等待 HTTP 监听退出。
|
||||||
|
Wait() error
|
||||||
|
Stop(context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// applicationRuntimeCloser 定义进程关闭阶段需要的最小应用组件收束能力。
|
||||||
|
// Close 必须取消并等待全部已登记应用 worker,返回值保留未完成组件诊断。
|
||||||
|
type applicationRuntimeCloser interface {
|
||||||
|
// Close 在调用方提供的独立应用关闭 Context 内取消并 Join worker。
|
||||||
|
Close(context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// applicationRuntimeCoordinator 定义 cmd 对组合根生命周期对象执行启动和关闭所需的能力。
|
||||||
|
type applicationRuntimeCoordinator interface {
|
||||||
|
Start(context.Context) error
|
||||||
|
Close(context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// opts 是命令行解析出的服务启动选项。
|
||||||
opts := parseOptions()
|
opts := parseOptions()
|
||||||
|
if opts.showVersion {
|
||||||
|
fmt.Printf("Ydisks Xianyu Helper %s (commit %s, built %s)\n", appversion.Version, appversion.ShortCommit(), appversion.BuildTime)
|
||||||
|
return
|
||||||
|
}
|
||||||
if opts.workDir != "" {
|
if opts.workDir != "" {
|
||||||
|
// err 表示切换到桌面服务指定工作目录失败。
|
||||||
if err := os.Chdir(opts.workDir); err != nil {
|
if err := os.Chdir(opts.workDir); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "切换工作目录失败: %v\n", err)
|
fmt.Fprintf(os.Stderr, "切换工作目录失败: %s\n", logsafe.Error(err))
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// run 统一封装平台服务和前台进程都会调用的启动函数。
|
||||||
run := func(ctx context.Context) error { return runServer(ctx, opts) }
|
run := func(ctx context.Context) error { return runServer(ctx, opts) }
|
||||||
if opts.service {
|
if opts.service {
|
||||||
|
// err 表示平台注册或运行服务失败。
|
||||||
if err := runPlatformService("YdisksXianyuHelper", run); err != nil {
|
if err := runPlatformService("YdisksXianyuHelper", run); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "服务运行失败: %v\n", err)
|
fmt.Fprintf(os.Stderr, "服务运行失败: %s\n", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ctx 接收终端信号取消;cancel 在主进程退出时解除信号订阅。
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
// err 表示前台服务的启动、监听或关闭失败。
|
||||||
if err := run(ctx); err != nil {
|
if err := run(ctx); err != nil {
|
||||||
slog.Error("服务退出", "err", err)
|
slog.Error("服务退出", "err", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseOptions 封装parseOptions业务协调。
|
||||||
func parseOptions() serverOptions {
|
func parseOptions() serverOptions {
|
||||||
|
// opts 收集所有命令行标志的目标字段,并在 flag.Parse 后返回。
|
||||||
var opts serverOptions
|
var opts serverOptions
|
||||||
flag.StringVar(&opts.dbPath, "db", defaultDBPath, "SQLite 数据库路径(兼容旧用法)")
|
flag.StringVar(&opts.dbPath, "db", defaultDBPath, "SQLite 数据库路径(兼容旧用法)")
|
||||||
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
||||||
@@ -106,54 +206,87 @@ func parseOptions() serverOptions {
|
|||||||
flag.StringVar(&opts.adminEmail, "admin-email", "admin@example.com", "初始化 admin 的邮箱")
|
flag.StringVar(&opts.adminEmail, "admin-email", "admin@example.com", "初始化 admin 的邮箱")
|
||||||
flag.StringVar(&opts.adminPassword, "admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
|
flag.StringVar(&opts.adminPassword, "admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
|
||||||
flag.BoolVar(&opts.service, "service", false, "以 Windows Service 模式运行")
|
flag.BoolVar(&opts.service, "service", false, "以 Windows Service 模式运行")
|
||||||
|
flag.BoolVar(&opts.showVersion, "version", false, "显示版本和构建信息后退出")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runServer 按准备、基础设施、运行时装配和生命周期四个阶段启动服务,并在退出时逆序释放资源。
|
||||||
func runServer(parent context.Context, opts serverOptions) error {
|
func runServer(parent context.Context, opts serverOptions) error {
|
||||||
|
// ctx 是本次服务实例的取消上下文;cancel 在所有启动路径结束时释放派生资源。
|
||||||
ctx, cancel := context.WithCancel(parent)
|
ctx, cancel := context.WithCancel(parent)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
// startup 保存目录、数据库和日志策略的派生配置。
|
||||||
dataDir, err := resolveDataDir(opts.workDir)
|
startup, err := prepareServerStartup(&opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
applyPlaywrightRuntimeRoot(&opts)
|
// infrastructure 负责数据库、日志和加密设置资源的生命周期。
|
||||||
|
infrastructure, err := openServerInfrastructure(ctx, startup, opts)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer infrastructure.close()
|
||||||
|
if infrastructure.initializationOnly {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// runtime 保存已完成依赖注入但尚未启动的 HTTP 服务和生命周期协调器。
|
||||||
|
runtime, err := buildServerRuntime(opts, infrastructure)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return runServerLifecycle(ctx, runtime, infrastructure.logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareServerStartup 解析数据目录、Playwright 路径、数据密钥、数据库地址和日志启动策略,并把必需环境变量写入当前进程。
|
||||||
|
func prepareServerStartup(opts *serverOptions) (serverStartupConfig, error) {
|
||||||
|
// dataDir 是显式 workdir 或桌面平台默认用户数据目录。
|
||||||
|
dataDir, err := resolveDataDir(opts.workDir)
|
||||||
|
if err != nil {
|
||||||
|
return serverStartupConfig{}, err
|
||||||
|
}
|
||||||
|
// packagedPlaywrightRuntime 表示安装包是否显式提供浏览器 runtime;本地开发不应把空目录当作缓存。
|
||||||
|
packagedPlaywrightRuntime := strings.TrimSpace(opts.playwrightRuntimeRoot) != ""
|
||||||
|
applyPlaywrightRuntimeRoot(opts)
|
||||||
if dataDir != "" {
|
if dataDir != "" {
|
||||||
|
// err 表示创建受限权限应用数据目录时的文件系统错误。
|
||||||
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||||
return fmt.Errorf("创建应用数据目录失败: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("创建应用数据目录失败: %w", err)
|
||||||
}
|
}
|
||||||
if opts.dataKeyFile == "" {
|
if opts.dataKeyFile == "" {
|
||||||
opts.dataKeyFile = filepath.Join(dataDir, defaultDataKeyName)
|
opts.dataKeyFile = filepath.Join(dataDir, defaultDataKeyName)
|
||||||
}
|
}
|
||||||
if opts.playwrightDriverDir == "" {
|
if packagedPlaywrightRuntime && opts.playwrightDriverDir == "" {
|
||||||
opts.playwrightDriverDir = filepath.Join(dataDir, "playwright-driver")
|
opts.playwrightDriverDir = filepath.Join(dataDir, "playwright-driver")
|
||||||
}
|
}
|
||||||
if opts.playwrightBrowserDir == "" {
|
if packagedPlaywrightRuntime && opts.playwrightBrowserDir == "" {
|
||||||
opts.playwrightBrowserDir = filepath.Join(dataDir, "playwright-browsers")
|
opts.playwrightBrowserDir = filepath.Join(dataDir, "playwright-browsers")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.playwrightDriverDir != "" {
|
if opts.playwrightDriverDir != "" {
|
||||||
|
// err 表示写入 Playwright driver 路径环境变量失败。
|
||||||
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
|
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
|
||||||
return fmt.Errorf("设置 Playwright driver 目录失败: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("设置 Playwright driver 目录失败: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if opts.playwrightBrowserDir != "" {
|
if opts.playwrightBrowserDir != "" {
|
||||||
|
// err 表示写入 Playwright browser 缓存路径环境变量失败。
|
||||||
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
|
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
|
||||||
return fmt.Errorf("设置 Playwright 浏览器目录失败: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("设置 Playwright 浏览器目录失败: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(os.Getenv("XIANYU_DATA_KEY")) == "" && opts.dataKeyFile != "" {
|
if strings.TrimSpace(os.Getenv("XIANYU_DATA_KEY")) == "" && opts.dataKeyFile != "" {
|
||||||
key, err := loadOrCreateDataKey(opts.dataKeyFile)
|
// key 是从磁盘读取或新生成的加密主密钥;不得写入日志。
|
||||||
if err != nil {
|
key, keyErr := loadOrCreateDataKey(opts.dataKeyFile)
|
||||||
return err
|
if keyErr != nil {
|
||||||
|
return serverStartupConfig{}, keyErr
|
||||||
}
|
}
|
||||||
|
// err 表示把数据加密主密钥写入当前进程环境失败。
|
||||||
if err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
|
if err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
|
||||||
return fmt.Errorf("设置 XIANYU_DATA_KEY 失败: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("设置 XIANYU_DATA_KEY 失败: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// resolvedDBURL 按 DATABASE_URL、-db-url、-db 默认优先级选择实际数据库地址。
|
||||||
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
if resolvedDBURL == "" {
|
if resolvedDBURL == "" {
|
||||||
resolvedDBURL = strings.TrimSpace(opts.dbURL)
|
resolvedDBURL = strings.TrimSpace(opts.dbURL)
|
||||||
@@ -162,12 +295,14 @@ func runServer(parent context.Context, opts serverOptions) error {
|
|||||||
resolvedDBURL = resolveDBPath(dataDir, opts.dbPath)
|
resolvedDBURL = resolveDBPath(dataDir, opts.dbPath)
|
||||||
}
|
}
|
||||||
if dataDir != "" && resolvedDBURL == resolveDBPath(dataDir, defaultDBPath) {
|
if dataDir != "" && resolvedDBURL == resolveDBPath(dataDir, defaultDBPath) {
|
||||||
|
// err 表示创建默认 SQLite 数据库父目录失败。
|
||||||
if err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
|
if err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
|
||||||
return fmt.Errorf("创建数据库目录失败: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("创建数据库目录失败: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// resolvedLogLevel 是环境变量、命令行和 verbose 共同决定的日志等级;explicit 标记是否禁止数据库覆盖。
|
||||||
resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL"))
|
resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL"))
|
||||||
|
// explicitLogLevel 表示日志等级来自进程配置,因此不允许数据库设置覆盖它。
|
||||||
explicitLogLevel := resolvedLogLevel != ""
|
explicitLogLevel := resolvedLogLevel != ""
|
||||||
if strings.TrimSpace(opts.logLevel) != "" {
|
if strings.TrimSpace(opts.logLevel) != "" {
|
||||||
resolvedLogLevel = strings.TrimSpace(opts.logLevel)
|
resolvedLogLevel = strings.TrimSpace(opts.logLevel)
|
||||||
@@ -177,119 +312,200 @@ func runServer(parent context.Context, opts serverOptions) error {
|
|||||||
resolvedLogLevel = "debug"
|
resolvedLogLevel = "debug"
|
||||||
explicitLogLevel = true
|
explicitLogLevel = true
|
||||||
}
|
}
|
||||||
|
// err 表示初始日志等级不被 logging 包支持。
|
||||||
if err := logging.SetLevel(resolvedLogLevel); err != nil {
|
if err := logging.SetLevel(resolvedLogLevel); err != nil {
|
||||||
return fmt.Errorf("日志等级无效: %w", err)
|
return serverStartupConfig{}, fmt.Errorf("日志等级无效: %w", err)
|
||||||
}
|
}
|
||||||
|
// resolvedLogFormat 是环境变量或命令行选择的初始日志格式;explicitLogFormat 控制数据库设置是否可覆盖。
|
||||||
resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT"))
|
resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT"))
|
||||||
|
// explicitLogFormat 表示日志格式来自进程配置,因此不允许数据库设置覆盖它。
|
||||||
explicitLogFormat := resolvedLogFormat != ""
|
explicitLogFormat := resolvedLogFormat != ""
|
||||||
if strings.TrimSpace(opts.logFormat) != "" {
|
if strings.TrimSpace(opts.logFormat) != "" {
|
||||||
resolvedLogFormat = strings.TrimSpace(opts.logFormat)
|
resolvedLogFormat = strings.TrimSpace(opts.logFormat)
|
||||||
explicitLogFormat = true
|
explicitLogFormat = true
|
||||||
}
|
}
|
||||||
logWriter, closeLog, err := openServerLogWriter(dataDir)
|
return serverStartupConfig{dataDir: dataDir, resolvedDBURL: resolvedDBURL, explicitLogLevel: explicitLogLevel, explicitLogFormat: explicitLogFormat, resolvedLogFormat: resolvedLogFormat}, nil
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
defer closeLog()
|
|
||||||
logger := logging.NewLogger(logWriter, resolvedLogFormat)
|
|
||||||
slog.SetDefault(logger)
|
|
||||||
|
|
||||||
database, dialect, err := db.Open(ctx, resolvedDBURL)
|
// openServerInfrastructure 打开日志和数据库、升级敏感字段、应用数据库日志设置并处理管理员初始化选项。
|
||||||
|
func openServerInfrastructure(ctx context.Context, startup serverStartupConfig, opts serverOptions) (serverInfrastructure, error) {
|
||||||
|
// logWriter 和 closeLog 共同管理服务日志输出目标。
|
||||||
|
logWriter, closeLog, err := openServerLogWriter(startup.dataDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("打开数据库失败: %w", err)
|
return serverInfrastructure{}, err
|
||||||
|
}
|
||||||
|
// logger 是当前进程的初始结构化日志器;后续数据库日志格式变更会替换默认 logger。
|
||||||
|
logger := logging.NewLogger(logWriter, startup.resolvedLogFormat)
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
// database 和 dialect 表示已打开数据库及其 SQL 方言;database 的关闭责任转移给返回值。
|
||||||
|
database, dialect, err := db.Open(ctx, startup.resolvedDBURL)
|
||||||
|
if err != nil {
|
||||||
|
closeLog()
|
||||||
|
return serverInfrastructure{}, fmt.Errorf("打开数据库失败: %w", err)
|
||||||
}
|
}
|
||||||
defer database.Close()
|
|
||||||
logger.Info("数据库已就绪", "dialect", dialect)
|
logger.Info("数据库已就绪", "dialect", dialect)
|
||||||
|
// store 是绑定数据库方言的仓储集合。
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
|
// err 表示历史敏感字段加密校验或升级失败,失败时不能继续运行。
|
||||||
if err := store.EncryptLegacySecrets(ctx); err != nil {
|
if err := store.EncryptLegacySecrets(ctx); err != nil {
|
||||||
return fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
_ = database.Close()
|
||||||
|
closeLog()
|
||||||
|
return serverInfrastructure{}, fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
||||||
}
|
}
|
||||||
if !explicitLogLevel {
|
if !startup.explicitLogLevel {
|
||||||
if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
|
// level、levelErr 分别是数据库保存的日志等级及其读取错误;读取失败时保留进程默认值。
|
||||||
if err := logging.SetLevel(lv); err != nil {
|
if level, levelErr := store.Settings.Get(ctx, "log_level"); levelErr == nil && strings.TrimSpace(level) != "" {
|
||||||
logger.Warn("忽略无效的系统日志设置", "value", lv, "err", err)
|
// setErr 表示数据库日志等级不合法,系统会记录警告并继续使用现有等级。
|
||||||
|
if setErr := logging.SetLevel(level); setErr != nil {
|
||||||
|
logger.Warn("忽略无效的系统日志设置", "value", level, "err", setErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !explicitLogFormat {
|
if !startup.explicitLogFormat {
|
||||||
if format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" {
|
// format、formatErr 分别是数据库保存的日志格式及其读取错误;读取失败时保留进程默认格式。
|
||||||
|
if format, formatErr := store.Settings.Get(ctx, "log_format"); formatErr == nil && strings.TrimSpace(format) != "" {
|
||||||
logger = logging.NewLogger(logWriter, format)
|
logger = logging.NewLogger(logWriter, format)
|
||||||
slog.SetDefault(logger)
|
slog.SetDefault(logger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.initAdmin {
|
if opts.initAdmin {
|
||||||
|
// err 表示管理员密码初始化或重置失败,失败时不进入后续运行时装配。
|
||||||
if err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
|
if err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
|
||||||
return fmt.Errorf("初始化管理员失败: %w", err)
|
_ = database.Close()
|
||||||
|
closeLog()
|
||||||
|
return serverInfrastructure{}, fmt.Errorf("初始化管理员失败: %w", err)
|
||||||
}
|
}
|
||||||
logger.Info("管理员初始化完成", "username", "admin")
|
logger.Info("管理员初始化完成", "username", "admin")
|
||||||
return nil
|
return serverInfrastructure{database: database, store: store, logger: logger, logWriter: logWriter, closeLog: closeLog, initializationOnly: true}, nil
|
||||||
}
|
}
|
||||||
if opts.ensureAdmin {
|
if opts.ensureAdmin {
|
||||||
created, err := ensureAdminIfMissing(ctx, store, opts.adminEmail, opts.adminPassword)
|
// created、ensureErr 分别标记是否新建管理员以及查询或创建管理员时的失败。
|
||||||
if err != nil {
|
created, ensureErr := ensureAdminIfMissing(ctx, store, opts.adminEmail, opts.adminPassword)
|
||||||
return fmt.Errorf("检查或初始化管理员失败: %w", err)
|
if ensureErr != nil {
|
||||||
|
_ = database.Close()
|
||||||
|
closeLog()
|
||||||
|
return serverInfrastructure{}, fmt.Errorf("检查或初始化管理员失败: %w", ensureErr)
|
||||||
}
|
}
|
||||||
if created {
|
if created {
|
||||||
logger.Info("管理员初始化完成", "username", "admin")
|
logger.Info("管理员初始化完成", "username", "admin")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// initialized 表示系统是否已有管理员;查询失败按未初始化提示而不阻断启动。
|
||||||
if init, _ := store.Users.IsSystemInitialized(ctx); !init {
|
if initialized, _ := store.Users.IsSystemInitialized(ctx); !initialized {
|
||||||
|
if isNonLoopbackListenAddress(opts.addr) {
|
||||||
|
logger.Warn("系统尚未初始化且 HTTP 监听可被远程访问;首个访问初始化页面的客户端可创建管理员,请由部署者通过网络隔离或 -init-admin 承担该风险", "addr", opts.addr)
|
||||||
|
} else {
|
||||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||||
}
|
}
|
||||||
|
|
||||||
var bm *browser.Manager
|
|
||||||
if !opts.noBrowser {
|
|
||||||
bm = browser.NewManager(logger)
|
|
||||||
if err := bm.Initialize(); err != nil {
|
|
||||||
return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err)
|
|
||||||
}
|
}
|
||||||
|
return serverInfrastructure{database: database, store: store, logger: logger, logWriter: logWriter, closeLog: closeLog}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ap := adapter.New(store, bm, logger)
|
// buildServerRuntime 构造浏览器、账号、自动化、通知、应用服务和 HTTP 服务依赖,并登记全部生命周期组件但不启动它们。
|
||||||
chatService := chat.New(store)
|
func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure) (serverRuntime, error) {
|
||||||
ap.SetChatService(chatService)
|
// runtime、buildErr 分别是组合层返回的完整运行时快照及其装配失败原因。
|
||||||
mgr := account.NewManager(store, ap, logger)
|
runtime, buildErr := compositionruntime.BuildRuntime(compositionruntime.RuntimeOptions{
|
||||||
autoCenter := automation.New(store, mgr, logger)
|
NoBrowser: opts.noBrowser, SecureCookie: opts.secure, WebDir: opts.webDir, Addr: opts.addr,
|
||||||
autoCenter.SetOrderDetailFetcher(ap)
|
}, compositionruntime.RuntimeInfrastructure{Store: infrastructure.store, Logger: infrastructure.logger})
|
||||||
notifier := notify.New("", store, logger)
|
if buildErr != nil {
|
||||||
notifier.Start(ctx)
|
return serverRuntime{}, buildErr
|
||||||
autoCenter.SetNotifier(notifier)
|
}
|
||||||
ap.SetAutomation(autoCenter)
|
return serverRuntime{httpServer: runtime.HTTPServer, lifecycleCoordinator: runtime.Lifecycle}, nil
|
||||||
ap.SetNotifier(notifier)
|
|
||||||
if err := mgr.StartAll(ctx); err != nil {
|
|
||||||
logger.Error("启动账号引擎失败", "err", err)
|
|
||||||
}
|
}
|
||||||
automationScheduler := automation.NewScheduler(autoCenter)
|
|
||||||
go automationScheduler.Run(ctx)
|
|
||||||
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
|
|
||||||
go renewalScheduler.Run(ctx)
|
|
||||||
|
|
||||||
srv := server.New(store, mgr, opts.secure, opts.webDir, opts.addr, logger, autoCenter, notifier)
|
// runServerLifecycle 启动应用组件和 HTTP 监听,等待退出后执行有限时长的 HTTP 与组件逆序关闭。
|
||||||
srv.SetChatService(chatService)
|
func runServerLifecycle(ctx context.Context, runtime serverRuntime, logger *slog.Logger) error {
|
||||||
srv.StartPublishBatchRecovery(ctx)
|
// bindErr 是应用 worker 启动前同步占用 HTTP 端口的错误,端口冲突不得触发任何业务副作用。
|
||||||
runErr := srv.Run(ctx)
|
if bindErr := runtime.httpServer.Bind(); bindErr != nil {
|
||||||
|
return fmt.Errorf("绑定 HTTP 服务失败: %w", bindErr)
|
||||||
|
}
|
||||||
|
// err 表示应用组件按依赖顺序启动失败。
|
||||||
|
if err := runtime.lifecycleCoordinator.Start(ctx); err != nil {
|
||||||
|
// stopCtx、stopCancel 关闭已绑定但尚未 Serve 的监听器,避免启动失败后端口泄漏。
|
||||||
|
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer stopCancel()
|
||||||
|
return errors.Join(fmt.Errorf("启动应用生命周期失败: %w", err), runtime.httpServer.Stop(stopCtx))
|
||||||
|
}
|
||||||
|
// err 表示 HTTP 服务监听启动失败;失败后必须关闭已启动的应用组件。
|
||||||
|
if err := runtime.httpServer.Start(ctx); err != nil {
|
||||||
|
return errors.Join(fmt.Errorf("启动 HTTP 服务失败: %w", err), rollbackApplicationRuntime(runtime.lifecycleCoordinator, 10*time.Second))
|
||||||
|
}
|
||||||
|
// runErr 是 HTTP 监听退出时返回的错误;退出后仍需关闭所有应用组件。
|
||||||
|
runErr := runtime.httpServer.Wait()
|
||||||
if runErr != nil {
|
if runErr != nil {
|
||||||
logger.Error("HTTP 服务退出", "err", runErr)
|
logger.Error("HTTP 服务退出", "err", runErr)
|
||||||
}
|
}
|
||||||
cancel()
|
// shutdownErr 保存 HTTP 与应用组件关闭阶段的聚合结果;任一阶段超时都不能伪装为成功退出。
|
||||||
srv.WaitForBackground()
|
shutdownErr := closeServerRuntime(runtime.httpServer, runtime.lifecycleCoordinator, logger, httpShutdownTimeout, applicationShutdownTimeout)
|
||||||
automationScheduler.Wait()
|
return errors.Join(runErr, shutdownErr)
|
||||||
renewalScheduler.Wait()
|
|
||||||
mgr.StopAll()
|
|
||||||
if bm != nil {
|
|
||||||
_ = bm.Close()
|
|
||||||
}
|
}
|
||||||
notifier.Wait()
|
|
||||||
return runErr
|
// rollbackApplicationRuntime 在 HTTP 启动失败后以独立预算回滚应用组件,并保留未完成 worker 的诊断。
|
||||||
|
func rollbackApplicationRuntime(lifecycleCoordinator applicationRuntimeCloser, timeout time.Duration) error {
|
||||||
|
if lifecycleCoordinator == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// rollbackCtx 限制 HTTP 启动失败后的组件回滚时间,避免后台 worker 泄漏。
|
||||||
|
rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer rollbackCancel()
|
||||||
|
// rollbackErr 保存应用组件逆序回滚的底层错误。
|
||||||
|
rollbackErr := lifecycleCoordinator.Close(rollbackCtx)
|
||||||
|
return wrapShutdownError("HTTP 启动失败后的应用回滚", rollbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeServerRuntime 依次关闭 HTTP transport 和应用 worker,并为两者分配互不共享的关闭预算。
|
||||||
|
// HTTP 关闭失败不会阻止应用 Context 取消和 worker Join;返回值保留每个失败阶段及其未完成组件诊断。
|
||||||
|
func closeServerRuntime(httpServer httpRuntimeStopper, lifecycleCoordinator applicationRuntimeCloser, logger *slog.Logger, httpTimeout, applicationTimeout time.Duration) error {
|
||||||
|
// shutdownStartedAt 记录 HTTP 监听退出后开始收束各生命周期组件的时间,用于排查关闭预算耗尽。
|
||||||
|
shutdownStartedAt := time.Now()
|
||||||
|
// httpStopCtx、httpStopCancel 为 HTTP 请求排空和 Server 自有后台任务分配独立关闭预算。
|
||||||
|
httpStopCtx, httpStopCancel := context.WithTimeout(context.Background(), httpTimeout)
|
||||||
|
defer httpStopCancel()
|
||||||
|
// httpErr 保存 HTTP 优雅关闭错误;该错误不会阻断应用 worker 收束。
|
||||||
|
var httpErr error
|
||||||
|
if httpServer != nil {
|
||||||
|
httpErr = httpServer.Stop(httpStopCtx)
|
||||||
|
}
|
||||||
|
if httpErr != nil && logger != nil {
|
||||||
|
logger.Warn("HTTP 服务关闭未完成", "err", httpErr)
|
||||||
|
}
|
||||||
|
// applicationStopCtx、applicationStopCancel 为已取消的应用 worker 分配独立 Join 预算,避免 HTTP 超时吞掉 worker 收束机会。
|
||||||
|
applicationStopCtx, applicationStopCancel := context.WithTimeout(context.Background(), applicationTimeout)
|
||||||
|
defer applicationStopCancel()
|
||||||
|
// applicationErr 保存应用组件逆序关闭的聚合错误,其中包含未完成组件名称。
|
||||||
|
var applicationErr error
|
||||||
|
if lifecycleCoordinator != nil {
|
||||||
|
applicationErr = lifecycleCoordinator.Close(applicationStopCtx)
|
||||||
|
}
|
||||||
|
if applicationErr != nil && logger != nil {
|
||||||
|
logger.Warn("应用组件关闭未完成", "err", applicationErr)
|
||||||
|
}
|
||||||
|
// shutdownErr 为调用方保留阶段名称和底层错误,便于区分 HTTP 排空与 worker Join 失败。
|
||||||
|
shutdownErr := errors.Join(
|
||||||
|
wrapShutdownError("HTTP 服务关闭", httpErr),
|
||||||
|
wrapShutdownError("应用组件关闭", applicationErr),
|
||||||
|
)
|
||||||
|
if logger != nil {
|
||||||
|
logger.Info("服务生命周期关闭收束完成", "duration", time.Since(shutdownStartedAt), "http_completed", httpErr == nil, "application_completed", applicationErr == nil)
|
||||||
|
}
|
||||||
|
return shutdownErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrapShutdownError 为非空关闭错误附加稳定阶段名称;空错误保持为 nil 以支持 errors.Join。
|
||||||
|
func wrapShutdownError(stage string, shutdownErr error) error {
|
||||||
|
if shutdownErr == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s失败: %w", stage, shutdownErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// openServerLogWriter keeps container and interactive runs on stdout while
|
// openServerLogWriter keeps container and interactive runs on stdout while
|
||||||
// desktop/system-service installations persist logs in their platform log
|
// desktop/system-service installations persist logs in their platform log
|
||||||
// directory. Windows services do not have a useful console, so they get a
|
// directory. Windows services do not have a useful console, so they get a
|
||||||
// default log file beside the service data directory.
|
// default log file beside the service data directory.
|
||||||
|
// openServerLogWriter 封装openServerLogWriter业务协调。
|
||||||
func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
|
func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
|
||||||
|
// logDir 是环境变量或 Windows 服务数据目录指定的持久化日志目录。
|
||||||
logDir := strings.TrimSpace(os.Getenv("XIANYU_LOG_DIR"))
|
logDir := strings.TrimSpace(os.Getenv("XIANYU_LOG_DIR"))
|
||||||
if logDir == "" && runtime.GOOS == "windows" && dataDir != "" {
|
if logDir == "" && runtime.GOOS == "windows" && dataDir != "" {
|
||||||
logDir = filepath.Join(dataDir, "logs")
|
logDir = filepath.Join(dataDir, "logs")
|
||||||
@@ -297,10 +513,13 @@ func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
|
|||||||
if logDir == "" {
|
if logDir == "" {
|
||||||
return os.Stdout, func() {}, nil
|
return os.Stdout, func() {}, nil
|
||||||
}
|
}
|
||||||
|
// err 表示创建受限权限日志目录失败。
|
||||||
if err := os.MkdirAll(logDir, 0o700); err != nil {
|
if err := os.MkdirAll(logDir, 0o700); err != nil {
|
||||||
return nil, nil, fmt.Errorf("创建日志目录失败: %w", err)
|
return nil, nil, fmt.Errorf("创建日志目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// logPath 是服务进程追加写入的单一日志文件路径。
|
||||||
logPath := filepath.Join(logDir, "server.log")
|
logPath := filepath.Join(logDir, "server.log")
|
||||||
|
// file、err 分别是已打开的日志文件与打开失败原因。
|
||||||
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("打开日志文件失败: %w", err)
|
return nil, nil, fmt.Errorf("打开日志文件失败: %w", err)
|
||||||
@@ -308,14 +527,17 @@ func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
|
|||||||
return file, func() { _ = file.Close() }, nil
|
return file, func() { _ = file.Close() }, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// applyPlaywrightRuntimeRoot 封装applyPlaywrightRuntimeRoot业务协调。
|
||||||
func applyPlaywrightRuntimeRoot(opts *serverOptions) {
|
func applyPlaywrightRuntimeRoot(opts *serverOptions) {
|
||||||
if opts == nil {
|
if opts == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// root 是安装包提供的 Playwright runtime 根目录。
|
||||||
root := strings.TrimSpace(opts.playwrightRuntimeRoot)
|
root := strings.TrimSpace(opts.playwrightRuntimeRoot)
|
||||||
if root == "" {
|
if root == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// archRoot 是当前 Go 架构对应的驱动和浏览器资源目录。
|
||||||
archRoot := filepath.Join(root, runtime.GOARCH)
|
archRoot := filepath.Join(root, runtime.GOARCH)
|
||||||
if opts.playwrightDriverDir == "" {
|
if opts.playwrightDriverDir == "" {
|
||||||
opts.playwrightDriverDir = filepath.Join(archRoot, "playwright-driver")
|
opts.playwrightDriverDir = filepath.Join(archRoot, "playwright-driver")
|
||||||
@@ -328,6 +550,7 @@ func applyPlaywrightRuntimeRoot(opts *serverOptions) {
|
|||||||
// resolveDataDir 返回桌面端的标准用户数据目录。
|
// resolveDataDir 返回桌面端的标准用户数据目录。
|
||||||
// Linux/Docker 保留原有相对路径行为;macOS 和 Windows 在没有显式 -workdir
|
// Linux/Docker 保留原有相对路径行为;macOS 和 Windows 在没有显式 -workdir
|
||||||
// 时使用当前用户的系统配置目录,避免把具体用户路径写进安装包或代码。
|
// 时使用当前用户的系统配置目录,避免把具体用户路径写进安装包或代码。
|
||||||
|
// resolveDataDir 封装resolve数据Dir业务协调。
|
||||||
func resolveDataDir(workDir string) (string, error) {
|
func resolveDataDir(workDir string) (string, error) {
|
||||||
if strings.TrimSpace(workDir) != "" {
|
if strings.TrimSpace(workDir) != "" {
|
||||||
return filepath.Clean(workDir), nil
|
return filepath.Clean(workDir), nil
|
||||||
@@ -335,6 +558,7 @@ func resolveDataDir(workDir string) (string, error) {
|
|||||||
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
|
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
// configDir、err 分别是操作系统用户配置根目录及其读取失败原因。
|
||||||
configDir, err := os.UserConfigDir()
|
configDir, err := os.UserConfigDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("读取用户配置目录失败: %w", err)
|
return "", fmt.Errorf("读取用户配置目录失败: %w", err)
|
||||||
@@ -342,6 +566,7 @@ func resolveDataDir(workDir string) (string, error) {
|
|||||||
return filepath.Join(configDir, userDataDirName), nil
|
return filepath.Join(configDir, userDataDirName), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveDBPath 封装resolveDB路径业务协调。
|
||||||
func resolveDBPath(dataDir, configuredPath string) string {
|
func resolveDBPath(dataDir, configuredPath string) string {
|
||||||
if dataDir != "" && configuredPath == defaultDBPath {
|
if dataDir != "" && configuredPath == defaultDBPath {
|
||||||
return filepath.Join(dataDir, "data", "xianyu_data.db")
|
return filepath.Join(dataDir, "data", "xianyu_data.db")
|
||||||
@@ -349,35 +574,119 @@ func resolveDBPath(dataDir, configuredPath string) string {
|
|||||||
return configuredPath
|
return configuredPath
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loadOrCreateDataKey 封装loadOrCreate数据Key业务协调。
|
||||||
func loadOrCreateDataKey(path string) (string, error) {
|
func loadOrCreateDataKey(path string) (string, error) {
|
||||||
path = strings.TrimSpace(path)
|
path = strings.TrimSpace(path)
|
||||||
if path == "" {
|
if path == "" {
|
||||||
return "", fmt.Errorf("data key 文件路径不能为空")
|
return "", fmt.Errorf("data key 文件路径不能为空")
|
||||||
}
|
}
|
||||||
if raw, err := os.ReadFile(path); err == nil {
|
// key、readErr 分别是已存在密钥文件的内容及读取错误;已有文件永远优先于本次生成。
|
||||||
key := strings.TrimSpace(string(raw))
|
if key, readErr := readDataKey(path); readErr == nil {
|
||||||
if key == "" {
|
|
||||||
return "", fmt.Errorf("data key 文件为空: %s", path)
|
|
||||||
}
|
|
||||||
return key, nil
|
return key, nil
|
||||||
} else if !errors.Is(err, os.ErrNotExist) {
|
} else if errors.Is(readErr, errDataKeyEmpty) {
|
||||||
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
|
return waitForDataKey(path)
|
||||||
|
} else if !errors.Is(readErr, os.ErrNotExist) {
|
||||||
|
return "", readErr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// err 表示创建数据加密主密钥父目录失败。
|
||||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
return "", fmt.Errorf("创建 data key 目录失败: %w", err)
|
return "", fmt.Errorf("创建 data key 目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// raw 保存高熵随机字节,编码后成为新的数据加密主密钥且不得日志输出。
|
||||||
raw := make([]byte, 48)
|
raw := make([]byte, 48)
|
||||||
|
// err 表示系统随机源无法生成新的数据加密主密钥。
|
||||||
if _, err := rand.Read(raw); err != nil {
|
if _, err := rand.Read(raw); err != nil {
|
||||||
return "", fmt.Errorf("生成 data key 失败: %w", err)
|
return "", fmt.Errorf("生成 data key 失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// key 是待写入权限为 0600 文件的数据加密主密钥,禁止记录到日志。
|
||||||
key := base64.RawStdEncoding.EncodeToString(raw)
|
key := base64.RawStdEncoding.EncodeToString(raw)
|
||||||
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
|
// file、createErr 分别是以排他方式创建的密钥文件及创建错误;同一时刻只能有一个进程成为写入者。
|
||||||
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
|
file, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||||
|
if errors.Is(createErr, os.ErrExist) {
|
||||||
|
return waitForDataKey(path)
|
||||||
|
}
|
||||||
|
if createErr != nil {
|
||||||
|
return "", fmt.Errorf("创建 data key 文件失败: %w", createErr)
|
||||||
|
}
|
||||||
|
// writeErr 表示新密钥写入错误;失败时删除当前进程独占创建的文件,避免遗留不可恢复的空文件。
|
||||||
|
if _, writeErr := io.WriteString(file, key+"\n"); writeErr != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
_ = os.Remove(path)
|
||||||
|
return "", fmt.Errorf("写入 data key 文件失败: %w", writeErr)
|
||||||
|
}
|
||||||
|
// syncErr 表示密钥内容持久化到文件系统前发生的同步错误;不能在未落盘时继续启动。
|
||||||
|
if syncErr := file.Sync(); syncErr != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
_ = os.Remove(path)
|
||||||
|
return "", fmt.Errorf("同步 data key 文件失败: %w", syncErr)
|
||||||
|
}
|
||||||
|
// closeErr 表示关闭新建密钥文件时产生的错误;关闭失败同样视为密钥未可靠创建。
|
||||||
|
if closeErr := file.Close(); closeErr != nil {
|
||||||
|
_ = os.Remove(path)
|
||||||
|
return "", fmt.Errorf("关闭 data key 文件失败: %w", closeErr)
|
||||||
}
|
}
|
||||||
return key, nil
|
return key, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readDataKey 读取并校验已有的数据加密主密钥;返回错误时绝不输出密钥内容。
|
||||||
|
func readDataKey(path string) (string, error) {
|
||||||
|
// raw、readErr 分别是文件原始内容及读取失败原因。
|
||||||
|
raw, readErr := os.ReadFile(path)
|
||||||
|
if readErr != nil {
|
||||||
|
if errors.Is(readErr, os.ErrNotExist) {
|
||||||
|
return "", os.ErrNotExist
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("读取 data key 文件失败: %w", readErr)
|
||||||
|
}
|
||||||
|
// key 是去除文件末尾换行后的数据加密主密钥,禁止记录到日志。
|
||||||
|
key := strings.TrimSpace(string(raw))
|
||||||
|
if key == "" {
|
||||||
|
return "", fmt.Errorf("%w: %s", errDataKeyEmpty, path)
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitForDataKey 等待并读取由并发启动进程创建的密钥文件,不会生成或覆盖另一把密钥。
|
||||||
|
func waitForDataKey(path string) (string, error) {
|
||||||
|
// lastReadErr 保存最后一次未得到可用密钥的读取错误,用于保留遗留空文件诊断。
|
||||||
|
var lastReadErr error
|
||||||
|
// attempt 是读取竞争方写入结果的有限尝试次数,避免空文件永久阻塞启动。
|
||||||
|
for attempt := 0; attempt < 20; attempt++ {
|
||||||
|
// key、readErr 分别是当前尝试读到的密钥及读取错误。
|
||||||
|
key, readErr := readDataKey(path)
|
||||||
|
if readErr == nil {
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
lastReadErr = readErr
|
||||||
|
if !errors.Is(readErr, errDataKeyEmpty) && !errors.Is(readErr, os.ErrNotExist) {
|
||||||
|
return "", readErr
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
if errors.Is(lastReadErr, errDataKeyEmpty) {
|
||||||
|
return "", lastReadErr
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("等待并发创建 data key 文件超时: %s", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isNonLoopbackListenAddress 判断监听地址是否可能接收本机以外的连接;空 host 与通配地址均视为远程可达。
|
||||||
|
func isNonLoopbackListenAddress(address string) bool {
|
||||||
|
// host、port、splitErr 分别是监听地址的主机部分、端口部分和解析错误。
|
||||||
|
host, _, splitErr := net.SplitHostPort(strings.TrimSpace(address))
|
||||||
|
if splitErr != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
host = strings.TrimSpace(host)
|
||||||
|
if host == "" || strings.EqualFold(host, "localhost") {
|
||||||
|
return host == ""
|
||||||
|
}
|
||||||
|
// ip 是可直接判断 loopback 属性的 IP 地址;主机名按远程可达处理,避免漏报部署风险。
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
return ip == nil || !ip.IsLoopback()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureAdmin 封装ensureAdmin业务协调。
|
||||||
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
|
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
|
||||||
if password == "" {
|
if password == "" {
|
||||||
password = os.Getenv("XIANYU_ADMIN_PASSWORD")
|
password = os.Getenv("XIANYU_ADMIN_PASSWORD")
|
||||||
@@ -385,11 +694,14 @@ func ensureAdmin(ctx context.Context, store *db.Store, email, password string) e
|
|||||||
if password == "" {
|
if password == "" {
|
||||||
return fmt.Errorf("admin 密码不能为空,请传 -admin-password 或设置 XIANYU_ADMIN_PASSWORD")
|
return fmt.Errorf("admin 密码不能为空,请传 -admin-password 或设置 XIANYU_ADMIN_PASSWORD")
|
||||||
}
|
}
|
||||||
|
// err 表示管理员初始化或密码重置失败。
|
||||||
_, err := auth.InitAdmin(ctx, store, email, password)
|
_, err := auth.InitAdmin(ctx, store, email, password)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureAdminIfMissing 封装ensureAdminIfMissing业务协调。
|
||||||
func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password string) (bool, error) {
|
func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password string) (bool, error) {
|
||||||
|
// admin、err 分别是现有管理员记录及其查询失败原因。
|
||||||
admin, err := store.Users.GetAdmin(ctx)
|
admin, err := store.Users.GetAdmin(ctx)
|
||||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||||
return false, fmt.Errorf("查询 admin 失败: %w", err)
|
return false, fmt.Errorf("查询 admin 失败: %w", err)
|
||||||
@@ -397,6 +709,7 @@ func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password
|
|||||||
if admin != nil {
|
if admin != nil {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
// err 表示首次创建管理员失败。
|
||||||
if err := ensureAdmin(ctx, store, email, password); err != nil {
|
if err := ensureAdmin(ctx, store, email, password); err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|||||||
+310
-5
@@ -2,24 +2,166 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
"io"
|
"io"
|
||||||
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// blockingHTTPStopper 模拟不响应关闭的 HTTP transport,用于验证其预算不会吞掉应用 worker 的 Join 时间。
|
||||||
|
type blockingHTTPStopper struct {
|
||||||
|
// calls 记录 Stop 调用次数,确保关闭阶段只调用一次。
|
||||||
|
calls int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop 等待 HTTP 关闭 Context 到期,模拟无法在预算内排空的请求。
|
||||||
|
func (stopper *blockingHTTPStopper) Stop(ctx context.Context) error {
|
||||||
|
stopper.calls++
|
||||||
|
<-ctx.Done()
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// observingApplicationCloser 记录应用关闭 Context,并返回预置 worker 收束错误。
|
||||||
|
type observingApplicationCloser struct {
|
||||||
|
// activeContexts 接收 Close 调用瞬间的 Context 活跃状态,避免函数返回后的 defer 取消影响断言。
|
||||||
|
activeContexts chan bool
|
||||||
|
// closeErr 是模拟未完成 worker 时要保留的聚合错误。
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// startupRollbackCloser 记录 HTTP 启动失败后的应用回滚 Context,并返回预置错误。
|
||||||
|
type startupRollbackCloser struct {
|
||||||
|
// closeErr 是回滚阶段要保留的底层组件错误。
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close 记录回滚请求并返回预置错误,模拟 worker 无法在预算内收束。
|
||||||
|
func (closer *startupRollbackCloser) Close(context.Context) error {
|
||||||
|
return closer.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close 记录独立的应用 worker 关闭 Context,并立即返回预置收束错误。
|
||||||
|
func (closer *observingApplicationCloser) Close(ctx context.Context) error {
|
||||||
|
closer.activeContexts <- ctx.Err() == nil
|
||||||
|
return closer.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseOptionsReadsAllOperationalFlags 验证服务入口的命令行参数完整映射。
|
||||||
|
func TestParseOptionsReadsAllOperationalFlags(t *testing.T) {
|
||||||
|
// oldArgs、oldCommandLine 保存测试前的全局命令行状态。
|
||||||
|
oldArgs, oldCommandLine := os.Args, flag.CommandLine
|
||||||
|
t.Cleanup(func() {
|
||||||
|
os.Args = oldArgs
|
||||||
|
flag.CommandLine = oldCommandLine
|
||||||
|
})
|
||||||
|
os.Args = []string{"server", "-db", "custom.db", "-db-url", "sqlite://override.db", "-addr", "127.0.0.1:1", "-web", "web", "-workdir", "data", "-playwright-runtime-root", "runtime", "-playwright-driver-dir", "driver", "-playwright-browser-dir", "browsers", "-data-key-file", "key", "-secure", "-no-browser", "-v", "-log-level", "debug", "-log-format", "json", "-init-admin", "-ensure-admin", "-admin-email", "a@example.com", "-admin-password", "secret", "-service", "-version"}
|
||||||
|
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
|
||||||
|
flag.CommandLine.SetOutput(io.Discard)
|
||||||
|
// opts 保存解析后的服务启动选项。
|
||||||
|
opts := parseOptions()
|
||||||
|
if opts.dbPath != "custom.db" || opts.dbURL != "sqlite://override.db" || opts.addr != "127.0.0.1:1" || opts.webDir != "web" || opts.workDir != "data" || opts.playwrightRuntimeRoot != "runtime" || opts.playwrightDriverDir != "driver" || opts.playwrightBrowserDir != "browsers" || opts.dataKeyFile != "key" {
|
||||||
|
t.Fatalf("路径参数解析错误:%+v", opts)
|
||||||
|
}
|
||||||
|
if !opts.secure || !opts.noBrowser || !opts.verbose || !opts.initAdmin || !opts.ensureAdmin || !opts.service || !opts.showVersion || opts.logLevel != "debug" || opts.logFormat != "json" || opts.adminEmail != "a@example.com" || opts.adminPassword != "secret" {
|
||||||
|
t.Fatalf("布尔或日志参数解析错误:%+v", opts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunPlatformServiceReportsUnsupportedPlatform 验证非 Windows 服务入口给出明确错误。
|
||||||
|
func TestRunPlatformServiceReportsUnsupportedPlatform(t *testing.T) {
|
||||||
|
// err 保存平台服务调用结果。
|
||||||
|
err := runPlatformService("test", func(context.Context) error { return nil })
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("当前平台应报告不支持服务模式")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCloseServerRuntimePreservesIndependentWorkerBudget 验证 HTTP 预算耗尽后,应用 worker 仍获得独立关闭预算并且两类失败都会返回。
|
||||||
|
func TestCloseServerRuntimePreservesIndependentWorkerBudget(t *testing.T) {
|
||||||
|
// httpStopper 模拟 HTTP 排空持续到自身关闭 Context 到期。
|
||||||
|
httpStopper := &blockingHTTPStopper{}
|
||||||
|
// workerErr 是应用 worker 未完成时用于确认聚合结果的稳定错误。
|
||||||
|
workerErr := errors.New("worker join incomplete")
|
||||||
|
// applicationCloser 记录应用关闭 Context,验证其不会继承已截止的 HTTP Context。
|
||||||
|
applicationCloser := &observingApplicationCloser{activeContexts: make(chan bool, 1), closeErr: workerErr}
|
||||||
|
// logger 使用丢弃输出,避免本测试把预期关闭告警写入测试日志。
|
||||||
|
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
|
// startedAt 记录关闭阶段开始时间,确保 HTTP 预算实际生效且没有无限等待。
|
||||||
|
startedAt := time.Now()
|
||||||
|
// shutdownErr 是 HTTP 超时和应用 worker 未完成组成的聚合关闭错误。
|
||||||
|
shutdownErr := closeServerRuntime(httpStopper, applicationCloser, logger, 20*time.Millisecond, time.Second)
|
||||||
|
if !errors.Is(shutdownErr, context.DeadlineExceeded) {
|
||||||
|
t.Fatalf("关闭错误未保留 HTTP 截止时间: %v", shutdownErr)
|
||||||
|
}
|
||||||
|
if !errors.Is(shutdownErr, workerErr) {
|
||||||
|
t.Fatalf("关闭错误未保留应用 worker 诊断: %v", shutdownErr)
|
||||||
|
}
|
||||||
|
if httpStopper.calls != 1 {
|
||||||
|
t.Fatalf("HTTP Stop 调用次数=%d,期望=1", httpStopper.calls)
|
||||||
|
}
|
||||||
|
// workerContextActive 表示应用组件 Close 调用瞬间收到的 Context 是否仍可用。
|
||||||
|
workerContextActive := <-applicationCloser.activeContexts
|
||||||
|
if !workerContextActive {
|
||||||
|
t.Fatal("应用 worker 不应继承已截止的 HTTP Context")
|
||||||
|
}
|
||||||
|
// elapsed 是本次关闭总耗时,HTTP 预算到期后应立刻继续应用收束而非无限阻塞。
|
||||||
|
elapsed := time.Since(startedAt)
|
||||||
|
if elapsed < 15*time.Millisecond || elapsed > time.Second {
|
||||||
|
t.Fatalf("关闭耗时=%s,未按 HTTP 预算收束", elapsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWrapShutdownErrorKeepsNilAndCause 验证关闭错误包装既不制造空错误,也保留底层可分类原因。
|
||||||
|
func TestWrapShutdownErrorKeepsNilAndCause(t *testing.T) {
|
||||||
|
// emptyWrappedErr 是空关闭原因的包装结果,应该保持 nil。
|
||||||
|
emptyWrappedErr := wrapShutdownError("HTTP 服务关闭", nil)
|
||||||
|
if emptyWrappedErr != nil {
|
||||||
|
t.Fatalf("空关闭错误不应被包装: %v", emptyWrappedErr)
|
||||||
|
}
|
||||||
|
// cause 是应用关闭失败的底层可分类错误。
|
||||||
|
cause := errors.New("component still running")
|
||||||
|
// wrappedErr 是附带稳定关闭阶段名称的错误。
|
||||||
|
wrappedErr := wrapShutdownError("应用组件关闭", cause)
|
||||||
|
if !errors.Is(wrappedErr, cause) {
|
||||||
|
t.Fatalf("包装错误未保留底层原因: %v", wrappedErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestStartupRollbackErrorKeepsWorkerDiagnostic 验证 HTTP 启动失败后的应用回滚错误不会被静默丢弃。
|
||||||
|
func TestStartupRollbackErrorKeepsWorkerDiagnostic(t *testing.T) {
|
||||||
|
// workerErr 是应用组件回滚失败的可分类底层原因。
|
||||||
|
workerErr := errors.New("worker rollback incomplete")
|
||||||
|
// closer 是返回回滚失败的应用组件关闭替身。
|
||||||
|
closer := &startupRollbackCloser{closeErr: workerErr}
|
||||||
|
// wrappedErr 是启动失败后统一包装应用回滚阶段的结果。
|
||||||
|
wrappedErr := errors.Join(errors.New("HTTP 启动失败"), rollbackApplicationRuntime(closer, time.Second))
|
||||||
|
if !errors.Is(wrappedErr, workerErr) {
|
||||||
|
t.Fatalf("启动回滚错误未保留 worker 原因: %v", wrappedErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEnsureAdminIfMissingCreatesOnlyOnce 封装TestEnsureAdminIfMissingCreatesOnlyOnce业务协调。
|
||||||
func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
|
func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
|
||||||
|
// ctx 用于本次流程后续判断的ctx
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// database、dialect、err 用于本次流程后续判断的database、dialect、err
|
||||||
database, dialect, err := db.Open(ctx, "sqlite://"+filepath.Join(t.TempDir(), "server.db"))
|
database, dialect, err := db.Open(ctx, "sqlite://"+filepath.Join(t.TempDir(), "server.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("open database: %v", err)
|
t.Fatalf("open database: %v", err)
|
||||||
}
|
}
|
||||||
t.Cleanup(func() { _ = database.Close() })
|
t.Cleanup(func() { _ = database.Close() })
|
||||||
|
// store 用于本次流程后续判断的store
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
|
|
||||||
|
// created、err 用于本次流程后续判断的created、err
|
||||||
created, err := ensureAdminIfMissing(ctx, store, "admin@example.com", "first-password")
|
created, err := ensureAdminIfMissing(ctx, store, "admin@example.com", "first-password")
|
||||||
if err != nil || !created {
|
if err != nil || !created {
|
||||||
t.Fatalf("first ensure: created=%v err=%v", created, err)
|
t.Fatalf("first ensure: created=%v err=%v", created, err)
|
||||||
@@ -28,16 +170,47 @@ func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
|
|||||||
if err != nil || created {
|
if err != nil || created {
|
||||||
t.Fatalf("second ensure: created=%v err=%v", created, err)
|
t.Fatalf("second ensure: created=%v err=%v", created, err)
|
||||||
}
|
}
|
||||||
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "first-password"); err != nil || !ok {
|
if // ok、err 用于本次流程后续判断的ok、err
|
||||||
|
_, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "first-password"); err != nil || !ok {
|
||||||
t.Fatalf("original password should remain valid: ok=%v err=%v", ok, err)
|
t.Fatalf("original password should remain valid: ok=%v err=%v", ok, err)
|
||||||
}
|
}
|
||||||
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "second-password"); err == nil || ok {
|
if // ok、err 用于本次流程后续判断的ok、err
|
||||||
|
_, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "second-password"); err == nil || ok {
|
||||||
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
|
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunServerInitAdminStopsBeforeRuntimeStartup 验证 -init-admin 仅初始化管理员并在 HTTP、浏览器和后台任务启动前退出。
|
||||||
|
func TestRunServerInitAdminStopsBeforeRuntimeStartup(t *testing.T) {
|
||||||
|
// databasePath 是本测试隔离的 SQLite 文件,避免命令入口读取或修改默认数据目录。
|
||||||
|
databasePath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||||
|
// opts 使用无浏览器启动参数,仅覆盖管理员初始化分支。
|
||||||
|
opts := serverOptions{dbPath: databasePath, noBrowser: true, initAdmin: true, adminEmail: "admin@example.com", adminPassword: "initial-password"}
|
||||||
|
// runErr 表示管理员初始化命令的执行结果,成功时服务不应继续监听 HTTP 端口。
|
||||||
|
runErr := runServer(context.Background(), opts)
|
||||||
|
if runErr != nil {
|
||||||
|
t.Fatalf("run init-admin server: %v", runErr)
|
||||||
|
}
|
||||||
|
// verifyDatabase 和 dialect 用于重新打开数据库并验证管理员账户已经被写入。
|
||||||
|
verifyDatabase, dialect, openErr := db.Open(context.Background(), "sqlite://"+databasePath)
|
||||||
|
if openErr != nil {
|
||||||
|
t.Fatalf("open initialized database: %v", openErr)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = verifyDatabase.Close() })
|
||||||
|
// store 是验证管理员认证结果的仓储集合。
|
||||||
|
store := db.NewStore(verifyDatabase, dialect)
|
||||||
|
// user、matched、verifyErr 分别是管理员记录、密码验证结果和认证查询失败。
|
||||||
|
user, matched, verifyErr := store.Users.VerifyAndUpgrade(context.Background(), "admin", "initial-password")
|
||||||
|
if verifyErr != nil || !matched || user == nil {
|
||||||
|
t.Fatalf("admin initialization user=%v matched=%t err=%v", user, matched, verifyErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadOrCreateDataKeyPersists 封装TestLoadOrCreate数据KeyPersists业务协调。
|
||||||
func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
||||||
|
// path 用于本次流程后续判断的路径
|
||||||
path := filepath.Join(t.TempDir(), "data-key")
|
path := filepath.Join(t.TempDir(), "data-key")
|
||||||
|
// first、err 用于本次流程后续判断的first、err
|
||||||
first, err := loadOrCreateDataKey(path)
|
first, err := loadOrCreateDataKey(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("create data key: %v", err)
|
t.Fatalf("create data key: %v", err)
|
||||||
@@ -45,6 +218,7 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
|||||||
if first == "" {
|
if first == "" {
|
||||||
t.Fatal("created data key is empty")
|
t.Fatal("created data key is empty")
|
||||||
}
|
}
|
||||||
|
// second、err 用于本次流程后续判断的second、err
|
||||||
second, err := loadOrCreateDataKey(path)
|
second, err := loadOrCreateDataKey(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("load data key: %v", err)
|
t.Fatalf("load data key: %v", err)
|
||||||
@@ -52,24 +226,137 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
|||||||
if first != second {
|
if first != second {
|
||||||
t.Fatalf("data key changed between loads")
|
t.Fatalf("data key changed between loads")
|
||||||
}
|
}
|
||||||
if raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
|
if // raw、err 用于本次流程后续判断的raw、err
|
||||||
|
raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
|
||||||
t.Fatalf("data key file was not written: err=%v", err)
|
t.Fatalf("data key file was not written: err=%v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestLoadOrCreateDataKeyConcurrentCreation 验证并发首次启动只能观测到同一把持久化主密钥。
|
||||||
|
func TestLoadOrCreateDataKeyConcurrentCreation(t *testing.T) {
|
||||||
|
// path 是所有并发启动模拟共享的、尚不存在的数据密钥文件路径。
|
||||||
|
path := filepath.Join(t.TempDir(), "concurrent-data-key")
|
||||||
|
// workerCount 是并发调用数量,足以覆盖多个 goroutine 同时通过不存在检查的竞争窗口。
|
||||||
|
const workerCount = 32
|
||||||
|
// start 统一放行所有调用,避免调度器提前串行化创建过程。
|
||||||
|
start := make(chan struct{})
|
||||||
|
// keys 收集每个调用成功读取或创建到的密钥,禁止将密钥写入测试失败输出。
|
||||||
|
keys := make(chan string, workerCount)
|
||||||
|
// failures 收集并发创建过程中发生的错误,以便主 goroutine 统一断言。
|
||||||
|
failures := make(chan error, workerCount)
|
||||||
|
// workers 等待全部并发调用结束,避免测试提前读取未完成文件。
|
||||||
|
var workers sync.WaitGroup
|
||||||
|
// workerIndex 为每个并发调用分配稳定的启动序号,循环体本身不依赖其数值。
|
||||||
|
for workerIndex := 0; workerIndex < workerCount; workerIndex++ {
|
||||||
|
workers.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer workers.Done()
|
||||||
|
<-start
|
||||||
|
// key、keyErr 分别是当前调用读取或创建到的主密钥及错误。
|
||||||
|
key, keyErr := loadOrCreateDataKey(path)
|
||||||
|
if keyErr != nil {
|
||||||
|
failures <- keyErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keys <- key
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
workers.Wait()
|
||||||
|
close(keys)
|
||||||
|
close(failures)
|
||||||
|
// failure 是任一并发创建协程返回的错误,仅用于统一失败报告。
|
||||||
|
for failure := range failures {
|
||||||
|
t.Fatalf("并发创建 data key 失败: %v", failure)
|
||||||
|
}
|
||||||
|
// firstKey 是所有并发调用必须一致的首个密钥值,仅用于相等性比较。
|
||||||
|
var firstKey string
|
||||||
|
// key 是单个并发调用观测到的密钥,仅参与同值比较且不输出明文。
|
||||||
|
for key := range keys {
|
||||||
|
if firstKey == "" {
|
||||||
|
firstKey = key
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if key != firstKey {
|
||||||
|
t.Fatal("并发创建返回了不一致的数据密钥")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if firstKey == "" {
|
||||||
|
t.Fatal("并发创建没有返回数据密钥")
|
||||||
|
}
|
||||||
|
// persistedKey、readErr 分别是最终文件中的密钥及读取错误。
|
||||||
|
persistedKey, readErr := readDataKey(path)
|
||||||
|
if readErr != nil {
|
||||||
|
t.Fatalf("读取并发创建后的 data key 失败: %v", readErr)
|
||||||
|
}
|
||||||
|
if persistedKey != firstKey {
|
||||||
|
t.Fatal("持久化 data key 与并发调用返回值不一致")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadOrCreateDataKeyRejectsEmptyExistingFile 验证遗留空密钥文件不会被静默覆盖或替换。
|
||||||
|
func TestLoadOrCreateDataKeyRejectsEmptyExistingFile(t *testing.T) {
|
||||||
|
// path 是预先创建为空内容的密钥文件路径,模拟异常进程留下的不完整状态。
|
||||||
|
path := filepath.Join(t.TempDir(), "empty-data-key")
|
||||||
|
// writeErr 是构造异常空密钥文件时的写入错误。
|
||||||
|
if writeErr := os.WriteFile(path, nil, 0o600); writeErr != nil {
|
||||||
|
t.Fatalf("创建空 data key 文件失败: %v", writeErr)
|
||||||
|
}
|
||||||
|
// keyErr 是读取空密钥文件时必须返回的阻断错误。
|
||||||
|
_, keyErr := loadOrCreateDataKey(path)
|
||||||
|
if keyErr == nil {
|
||||||
|
t.Fatal("空 data key 文件不应被静默替换")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIsNonLoopbackListenAddress 验证远程可达监听地址会触发未初始化部署风险告警。
|
||||||
|
func TestIsNonLoopbackListenAddress(t *testing.T) {
|
||||||
|
// cases 覆盖 loopback、通配地址和主机名监听的风险分类。
|
||||||
|
cases := []struct {
|
||||||
|
// name 是当前地址分类场景的稳定测试名称。
|
||||||
|
name string
|
||||||
|
// address 是传给服务端监听器的地址字符串。
|
||||||
|
address string
|
||||||
|
// want 是该地址是否可能接收远程客户端连接。
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "loopback IPv4", address: "127.0.0.1:59188", want: false},
|
||||||
|
{name: "loopback IPv6", address: "[::1]:59188", want: false},
|
||||||
|
{name: "all interfaces", address: ":59188", want: true},
|
||||||
|
{name: "public interface", address: "0.0.0.0:59188", want: true},
|
||||||
|
{name: "hostname", address: "host.example:59188", want: true},
|
||||||
|
}
|
||||||
|
// testCase 是当前待执行的监听地址分类。
|
||||||
|
for _, testCase := range cases {
|
||||||
|
// testCase 是当前待执行的监听地址分类。
|
||||||
|
testCase := testCase
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
// got 是地址是否可能接受远程连接的实际判断结果。
|
||||||
|
if got := isNonLoopbackListenAddress(testCase.address); got != testCase.want {
|
||||||
|
t.Fatalf("地址 %q 远程可达=%t,want %t", testCase.address, got, testCase.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenServerLogWriterUsesConfiguredDirectory 封装TestOpenServerLogWriterUsesConfiguredDirectory业务协调。
|
||||||
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
|
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
|
||||||
|
// logDir 用于本次流程后续判断的logDir
|
||||||
logDir := t.TempDir()
|
logDir := t.TempDir()
|
||||||
t.Setenv("XIANYU_LOG_DIR", logDir)
|
t.Setenv("XIANYU_LOG_DIR", logDir)
|
||||||
|
|
||||||
|
// writer、closeLog、err 用于本次流程后续判断的writer、closeLog、err
|
||||||
writer, closeLog, err := openServerLogWriter("")
|
writer, closeLog, err := openServerLogWriter("")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("open log writer: %v", err)
|
t.Fatalf("open log writer: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := io.WriteString(writer, "test log\n"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
_, err := io.WriteString(writer, "test log\n"); err != nil {
|
||||||
t.Fatalf("write log: %v", err)
|
t.Fatalf("write log: %v", err)
|
||||||
}
|
}
|
||||||
closeLog()
|
closeLog()
|
||||||
|
|
||||||
|
// content、err 用于本次流程后续判断的content、err
|
||||||
content, err := os.ReadFile(filepath.Join(logDir, "server.log"))
|
content, err := os.ReadFile(filepath.Join(logDir, "server.log"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("read log file: %v", err)
|
t.Fatalf("read log file: %v", err)
|
||||||
@@ -79,8 +366,11 @@ func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestResolveDataDirKeepsExplicitDirectory 封装TestResolve数据DirKeepsExplicitDirectory业务协调。
|
||||||
func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
|
func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
|
||||||
|
// explicit 用于本次流程后续判断的explicit
|
||||||
explicit := filepath.Join(t.TempDir(), "ydisks-data")
|
explicit := filepath.Join(t.TempDir(), "ydisks-data")
|
||||||
|
// got、err 用于本次流程后续判断的got、err
|
||||||
got, err := resolveDataDir(explicit)
|
got, err := resolveDataDir(explicit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("resolve explicit data directory: %v", err)
|
t.Fatalf("resolve explicit data directory: %v", err)
|
||||||
@@ -90,35 +380,50 @@ func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestUserDataDirName 封装Test用户数据Dir名称业务协调。
|
||||||
func TestUserDataDirName(t *testing.T) {
|
func TestUserDataDirName(t *testing.T) {
|
||||||
|
// base 用于本次流程后续判断的base
|
||||||
base := filepath.Join(t.TempDir(), "Application Support")
|
base := filepath.Join(t.TempDir(), "Application Support")
|
||||||
|
// got 用于本次流程后续判断的got
|
||||||
got := filepath.Join(base, userDataDirName)
|
got := filepath.Join(base, userDataDirName)
|
||||||
|
// want 用于本次流程后续判断的want
|
||||||
want := filepath.Join(base, "YdisksXianyuHelper")
|
want := filepath.Join(base, "YdisksXianyuHelper")
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("unexpected user data directory: got %q want %q", got, want)
|
t.Fatalf("unexpected user data directory: got %q want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestResolveDBPathUsesDataDirectoryForDefault 封装TestResolveDB路径Uses数据DirectoryForDefault业务协调。
|
||||||
func TestResolveDBPathUsesDataDirectoryForDefault(t *testing.T) {
|
func TestResolveDBPathUsesDataDirectoryForDefault(t *testing.T) {
|
||||||
|
// dataDir 用于本次流程后续判断的数据Dir
|
||||||
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
||||||
|
// got 用于本次流程后续判断的got
|
||||||
got := resolveDBPath(dataDir, defaultDBPath)
|
got := resolveDBPath(dataDir, defaultDBPath)
|
||||||
|
// want 用于本次流程后续判断的want
|
||||||
want := filepath.Join(dataDir, "data", "xianyu_data.db")
|
want := filepath.Join(dataDir, "data", "xianyu_data.db")
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("unexpected default database path: got %q want %q", got, want)
|
t.Fatalf("unexpected default database path: got %q want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestResolveDBPathPreservesCustomPath 封装TestResolveDB路径PreservesCustom路径业务协调。
|
||||||
func TestResolveDBPathPreservesCustomPath(t *testing.T) {
|
func TestResolveDBPathPreservesCustomPath(t *testing.T) {
|
||||||
|
// dataDir 用于本次流程后续判断的数据Dir
|
||||||
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
||||||
|
// custom 用于本次流程后续判断的custom
|
||||||
custom := filepath.Join(t.TempDir(), "custom.db")
|
custom := filepath.Join(t.TempDir(), "custom.db")
|
||||||
if got := resolveDBPath(dataDir, custom); got != custom {
|
if // got 用于本次流程后续判断的got
|
||||||
|
got := resolveDBPath(dataDir, custom); got != custom {
|
||||||
t.Fatalf("custom database path changed: got %q want %q", got, custom)
|
t.Fatalf("custom database path changed: got %q want %q", got, custom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestPlaywrightRuntimeRootUsesProcessArchitecture 封装TestPlaywrightRuntimeRootUsesProcessArchitecture业务协调。
|
||||||
func TestPlaywrightRuntimeRootUsesProcessArchitecture(t *testing.T) {
|
func TestPlaywrightRuntimeRootUsesProcessArchitecture(t *testing.T) {
|
||||||
|
// opts 用于本次流程后续判断的opts
|
||||||
opts := serverOptions{playwrightRuntimeRoot: filepath.Join(t.TempDir(), "playwright-runtime")}
|
opts := serverOptions{playwrightRuntimeRoot: filepath.Join(t.TempDir(), "playwright-runtime")}
|
||||||
applyPlaywrightRuntimeRoot(&opts)
|
applyPlaywrightRuntimeRoot(&opts)
|
||||||
|
// wantRoot 用于本次流程后续判断的wantRoot
|
||||||
wantRoot := filepath.Join(opts.playwrightRuntimeRoot, runtime.GOARCH)
|
wantRoot := filepath.Join(opts.playwrightRuntimeRoot, runtime.GOARCH)
|
||||||
if opts.playwrightDriverDir != filepath.Join(wantRoot, "playwright-driver") {
|
if opts.playwrightDriverDir != filepath.Join(wantRoot, "playwright-driver") {
|
||||||
t.Fatalf("driver 目录=%q", opts.playwrightDriverDir)
|
t.Fatalf("driver 目录=%q", opts.playwrightDriverDir)
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// runPlatformService 封装运行PlatformService业务协调。
|
||||||
func runPlatformService(_ string, _ func(context.Context) error) error {
|
func runPlatformService(_ string, _ func(context.Context) error) error {
|
||||||
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
|
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
|
||||||
}
|
}
|
||||||
@@ -9,35 +9,44 @@ import (
|
|||||||
"golang.org/x/sys/windows/svc"
|
"golang.org/x/sys/windows/svc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// windowsServiceHandler 用于本次流程后续判断的windowsServiceHandler
|
||||||
type windowsServiceHandler struct {
|
type windowsServiceHandler struct {
|
||||||
run func(context.Context) error
|
run func(context.Context) error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runPlatformService 封装运行PlatformService业务协调。
|
||||||
func runPlatformService(name string, run func(context.Context) error) error {
|
func runPlatformService(name string, run func(context.Context) error) error {
|
||||||
if err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
|
||||||
return fmt.Errorf("Windows Service %q: %w", name, err)
|
return fmt.Errorf("Windows Service %q: %w", name, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Execute 封装Execute业务协调。
|
||||||
func (h windowsServiceHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
|
func (h windowsServiceHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
|
||||||
|
// accepted 用于本次流程后续判断的accepted
|
||||||
const accepted = svc.AcceptStop | svc.AcceptShutdown
|
const accepted = svc.AcceptStop | svc.AcceptShutdown
|
||||||
status <- svc.Status{State: svc.StartPending}
|
status <- svc.Status{State: svc.StartPending}
|
||||||
|
|
||||||
|
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
// done 用于本次流程后续判断的done
|
||||||
done := make(chan error, 1)
|
done := make(chan error, 1)
|
||||||
go func() { done <- h.run(ctx) }()
|
go func() { done <- h.run(ctx) }()
|
||||||
status <- svc.Status{State: svc.Running, Accepts: accepted}
|
status <- svc.Status{State: svc.Running, Accepts: accepted}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case request := <-requests:
|
case // request 用于本次流程后续判断的请求
|
||||||
|
request := <-requests:
|
||||||
switch request.Cmd {
|
switch request.Cmd {
|
||||||
case svc.Stop, svc.Shutdown:
|
case svc.Stop, svc.Shutdown:
|
||||||
status <- svc.Status{State: svc.StopPending, Accepts: accepted}
|
status <- svc.Status{State: svc.StopPending, Accepts: accepted}
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
case err := <-done:
|
case // err 用于本次流程后续判断的err
|
||||||
|
err := <-done:
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return true, 1
|
return true, 1
|
||||||
|
|||||||
+41
-15
@@ -20,37 +20,46 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"xianyu-go/internal/logging"
|
||||||
"xianyu-go/internal/logsafe"
|
"xianyu-go/internal/logsafe"
|
||||||
"xianyu-go/internal/xianyu/mtop"
|
"xianyu-go/internal/xianyu/mtop"
|
||||||
"xianyu-go/internal/xianyu/protocol"
|
"xianyu-go/internal/xianyu/protocol"
|
||||||
"xianyu-go/internal/xianyu/ws"
|
"xianyu-go/internal/xianyu/ws"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// cookieFile 用于本次流程后续判断的登录凭证文件
|
||||||
cookieFile := flag.String("cookie-file", "", "从文件读取 cookie(首行)")
|
cookieFile := flag.String("cookie-file", "", "从文件读取 cookie(首行)")
|
||||||
|
// verbose 用于本次流程后续判断的verbose
|
||||||
verbose := flag.Bool("v", false, "调试日志")
|
verbose := flag.Bool("v", false, "调试日志")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
// logger 保存带集中式脱敏策略的诊断日志实例。
|
||||||
|
logger := logging.NewLogger(os.Stdout, "text")
|
||||||
if *verbose {
|
if *verbose {
|
||||||
logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
// verboseErr 保存切换调试日志等级时的配置错误;固定值 debug 理论上不会失败。
|
||||||
|
if verboseErr := logging.SetLevel("debug"); verboseErr != nil {
|
||||||
|
logger.Error("启用调试日志失败", "err", logsafe.Error(verboseErr))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||||
cookieStr := strings.TrimSpace(os.Getenv("XIANYU_COOKIE"))
|
cookieStr := strings.TrimSpace(os.Getenv("XIANYU_COOKIE"))
|
||||||
if *cookieFile != "" {
|
if *cookieFile != "" {
|
||||||
|
// b、err 用于本次流程后续判断的b、err
|
||||||
b, err := os.ReadFile(*cookieFile)
|
b, err := os.ReadFile(*cookieFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("读取 cookie 文件失败", "err", err)
|
logger.Error("读取 cookie 文件失败", "err", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
cookieStr = strings.TrimSpace(strings.SplitN(string(b), "\n", 2)[0])
|
cookieStr = strings.TrimSpace(strings.SplitN(string(b), "\n", 2)[0])
|
||||||
@@ -68,30 +77,35 @@ func main() {
|
|||||||
}
|
}
|
||||||
logger.Info("cookie 已加载", "account_hash", logsafe.ID(c["unb"]), "fields", len(c))
|
logger.Info("cookie 已加载", "account_hash", logsafe.ID(c["unb"]), "fields", len(c))
|
||||||
|
|
||||||
|
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
// 1) mtop token API → accessToken。
|
// 1) mtop token API → accessToken。
|
||||||
|
// mc 用于本次流程后续判断的mc
|
||||||
mc := mtop.NewClient()
|
mc := mtop.NewClient()
|
||||||
logger.Info("步骤 1/3:刷新 token")
|
logger.Info("步骤 1/3:刷新 token")
|
||||||
|
// res、err 用于本次流程后续判断的res、err
|
||||||
res, err := mc.RefreshToken(cookieStr)
|
res, err := mc.RefreshToken(cookieStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("刷新 token 失败", "err", err)
|
logger.Error("刷新 token 失败", "err", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
logger.Info("token 刷新成功", "accessToken_len", len(res.AccessToken))
|
logger.Info("token 刷新成功", "accessToken_len", len(res.AccessToken))
|
||||||
|
|
||||||
// 2) WS 连接 + 注册。
|
// 2) WS 连接 + 注册。
|
||||||
deviceID := protocol.GenerateDeviceID(c["unb"])
|
deviceID := protocol.GenerateDeviceID(c["unb"])
|
||||||
|
// cfg 用于本次流程后续判断的cfg
|
||||||
cfg := ws.Config{
|
cfg := ws.Config{
|
||||||
CookieStr: res.UpdatedCookies,
|
CookieStr: res.UpdatedCookies,
|
||||||
DeviceID: deviceID,
|
DeviceID: deviceID,
|
||||||
AccessToken: res.AccessToken,
|
AccessToken: res.AccessToken,
|
||||||
}
|
}
|
||||||
logger.Info("步骤 2/3:连接 WebSocket", "device_id", deviceID)
|
logger.Info("步骤 2/3:连接 WebSocket", "device_id", deviceID)
|
||||||
|
// conn、err 用于本次流程后续判断的conn、err
|
||||||
conn, err := ws.Dial(ctx, cfg, logger)
|
conn, err := ws.Dial(ctx, cfg, logger)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("WS 连接/注册失败", "err", err)
|
logger.Error("WS 连接/注册失败", "err", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
@@ -99,24 +113,36 @@ func main() {
|
|||||||
// 3) 心跳 + 收消息。
|
// 3) 心跳 + 收消息。
|
||||||
logger.Info("步骤 3/3:心跳与消息接收(等待闲鱼消息…)")
|
logger.Info("步骤 3/3:心跳与消息接收(等待闲鱼消息…)")
|
||||||
go func() {
|
go func() {
|
||||||
if err := conn.HeartbeatLoop(ctx, 15*time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
logger.Error("心跳循环退出", "err", err)
|
err := conn.HeartbeatLoop(ctx, 15*time.Second); err != nil {
|
||||||
|
logger.Error("心跳循环退出", "err", logsafe.Error(err))
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// gotMessage 用于本次流程后续判断的got消息
|
||||||
gotMessage := false
|
gotMessage := false
|
||||||
err = conn.ReceiveLoop(ctx, func(decrypted map[string]any) {
|
err = conn.ReceiveLoop(ctx, func(decrypted map[string]any) {
|
||||||
gotMessage = true
|
gotMessage = true
|
||||||
b, _ := json.MarshalIndent(decrypted, "", " ")
|
// fieldNames 保存消息顶层字段名;只输出结构摘要,避免把消息正文或凭证带入终端。
|
||||||
fmt.Println("\n========== 收到并解密一条消息 ==========")
|
fieldNames := diagnosticFieldNames(decrypted)
|
||||||
fmt.Println(string(b))
|
logger.Info("✅ 成功收到并解密消息,Phase 0 闸门通过(正文已省略)", "field_count", len(fieldNames), "fields", fieldNames)
|
||||||
fmt.Println("========================================")
|
|
||||||
logger.Info("✅ 成功收到并解密消息,Phase 0 闸门通过")
|
|
||||||
cancel()
|
cancel()
|
||||||
})
|
})
|
||||||
if !gotMessage {
|
if !gotMessage {
|
||||||
logger.Error("未收到消息即退出", "err", err)
|
logger.Error("未收到消息即退出", "err", logsafe.Error(err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// diagnosticFieldNames 返回消息顶层字段的排序列表,用于安全诊断而不暴露消息值。
|
||||||
|
func diagnosticFieldNames(message map[string]any) []string {
|
||||||
|
// fields 保存消息字段名;字段值不会被复制到诊断输出。
|
||||||
|
fields := make([]string, 0, len(message))
|
||||||
|
// fieldName 表示当前消息的顶层字段名。
|
||||||
|
for fieldName := range message {
|
||||||
|
fields = append(fields, fieldName)
|
||||||
|
}
|
||||||
|
sort.Strings(fields)
|
||||||
|
return fields
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//go:build debug || tools
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestDiagnosticFieldNamesOnlyReturnsSortedKeys 验证 spike 诊断摘要只暴露字段结构且顺序稳定。
|
||||||
|
func TestDiagnosticFieldNamesOnlyReturnsSortedKeys(t *testing.T) {
|
||||||
|
// message 保存含有模拟敏感正文的解密消息;正文不应进入摘要结果。
|
||||||
|
message := map[string]any{
|
||||||
|
"z": "cookie=account-secret",
|
||||||
|
"a": map[string]any{"password": "password-secret"},
|
||||||
|
"token": "token-secret",
|
||||||
|
"message": "买家私信正文",
|
||||||
|
}
|
||||||
|
// got 保存安全诊断摘要中的排序字段名。
|
||||||
|
got := diagnosticFieldNames(message)
|
||||||
|
// want 保存预期的稳定字段顺序。
|
||||||
|
want := []string{"a", "message", "token", "z"}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("diagnosticFieldNames()=%v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,15 +8,21 @@ import (
|
|||||||
|
|
||||||
// icon.png 是从根目录 icon/windows/icon.png 同步的彩色产品图标,并直接嵌入托盘二进制。
|
// icon.png 是从根目录 icon/windows/icon.png 同步的彩色产品图标,并直接嵌入托盘二进制。
|
||||||
//
|
//
|
||||||
|
// productIconPNG 用于本次流程后续判断的productIconPNG
|
||||||
|
//
|
||||||
//go:embed icon.png
|
//go:embed icon.png
|
||||||
var productIconPNG []byte
|
var productIconPNG []byte
|
||||||
|
|
||||||
|
// productIconGrayPNG 用于本次流程后续判断的productIconGrayPNG
|
||||||
|
//
|
||||||
//go:embed icon-gray.png
|
//go:embed icon-gray.png
|
||||||
var productIconGrayPNG []byte
|
var productIconGrayPNG []byte
|
||||||
|
|
||||||
// trayIconBytes 返回当前服务状态对应的图标,避免运行时依赖外部图标文件。
|
// trayIconBytes 返回当前服务状态对应的图标,避免运行时依赖外部图标文件。
|
||||||
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
|
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
|
||||||
|
// trayIconBytes 封装trayIconBytes业务协调。
|
||||||
func trayIconBytes(running bool) []byte {
|
func trayIconBytes(running bool) []byte {
|
||||||
|
// data 用于本次流程后续判断的数据
|
||||||
data := productIconGrayPNG
|
data := productIconGrayPNG
|
||||||
if running {
|
if running {
|
||||||
data = productIconPNG
|
data = productIconPNG
|
||||||
@@ -27,14 +33,19 @@ func trayIconBytes(running bool) []byte {
|
|||||||
return pngToICO(data, 256)
|
return pngToICO(data, 256)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pngToICO 封装pngToICO业务协调。
|
||||||
func pngToICO(data []byte, size int) []byte {
|
func pngToICO(data []byte, size int) []byte {
|
||||||
|
// headerSize 用于本次流程后续判断的header数量
|
||||||
const headerSize = 6
|
const headerSize = 6
|
||||||
|
// entrySize 用于本次流程后续判断的entry数量
|
||||||
const entrySize = 16
|
const entrySize = 16
|
||||||
|
// result 用于本次流程后续判断的结果
|
||||||
result := make([]byte, headerSize+entrySize+len(data))
|
result := make([]byte, headerSize+entrySize+len(data))
|
||||||
// ICONDIR: reserved, type=icon, image count=1.
|
// ICONDIR: reserved, type=icon, image count=1.
|
||||||
binary.LittleEndian.PutUint16(result[0:2], 0)
|
binary.LittleEndian.PutUint16(result[0:2], 0)
|
||||||
binary.LittleEndian.PutUint16(result[2:4], 1)
|
binary.LittleEndian.PutUint16(result[2:4], 1)
|
||||||
binary.LittleEndian.PutUint16(result[4:6], 1)
|
binary.LittleEndian.PutUint16(result[4:6], 1)
|
||||||
|
// entry 用于本次流程后续判断的entry
|
||||||
entry := result[headerSize : headerSize+entrySize]
|
entry := result[headerSize : headerSize+entrySize]
|
||||||
if size >= 256 {
|
if size >= 256 {
|
||||||
entry[0] = 0
|
entry[0] = 0
|
||||||
|
|||||||
@@ -10,25 +10,32 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// acquireTrayInstance 封装acquireTrayInstance业务协调。
|
||||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||||
|
// cacheDirectory、err 用于本次流程后续判断的cacheDirectory、err
|
||||||
cacheDirectory, err := os.UserCacheDir()
|
cacheDirectory, err := os.UserCacheDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err)
|
return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// lockDirectory 用于本次流程后续判断的锁Directory
|
||||||
lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper")
|
lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper")
|
||||||
if err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
||||||
return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err)
|
return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock"))
|
return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// acquireTrayFileLock 封装acquireTray文件锁业务协调。
|
||||||
func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) {
|
func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) {
|
||||||
|
// lockFile、err 用于本次流程后续判断的锁File、err
|
||||||
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err)
|
return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err)
|
||||||
}
|
}
|
||||||
if err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||||
_ = lockFile.Close()
|
_ = lockFile.Close()
|
||||||
if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
|
if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
|
||||||
return func() {}, false, nil
|
return func() {}, false, nil
|
||||||
|
|||||||
@@ -7,8 +7,11 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestAcquireTrayInstanceRejectsSecondInstance 封装TestAcquireTrayInstanceRejectsSecondInstance业务协调。
|
||||||
func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
||||||
|
// lockPath 用于本次流程后续判断的锁路径
|
||||||
lockPath := filepath.Join(t.TempDir(), "tray.lock")
|
lockPath := filepath.Join(t.TempDir(), "tray.lock")
|
||||||
|
// releaseFirst、acquired、err 用于本次流程后续判断的releaseFirst、acquired、err
|
||||||
releaseFirst, acquired, err := acquireTrayFileLock(lockPath)
|
releaseFirst, acquired, err := acquireTrayFileLock(lockPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("acquire first tray instance: %v", err)
|
t.Fatalf("acquire first tray instance: %v", err)
|
||||||
@@ -18,6 +21,7 @@ func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer releaseFirst()
|
defer releaseFirst()
|
||||||
|
|
||||||
|
// releaseSecond、acquired、err 用于本次流程后续判断的releaseSecond、acquired、err
|
||||||
releaseSecond, acquired, err := acquireTrayFileLock(lockPath)
|
releaseSecond, acquired, err := acquireTrayFileLock(lockPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("acquire second tray instance: %v", err)
|
t.Fatalf("acquire second tray instance: %v", err)
|
||||||
|
|||||||
@@ -8,11 +8,14 @@ import (
|
|||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// acquireTrayInstance 封装acquireTrayInstance业务协调。
|
||||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||||
|
// mutexName、err 用于本次流程后续判断的mutexName、err
|
||||||
mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`)
|
mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err)
|
return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// handle、err 用于本次流程后续判断的handle、err
|
||||||
handle, err := windows.CreateMutex(nil, false, mutexName)
|
handle, err := windows.CreateMutex(nil, false, mutexName)
|
||||||
if err == windows.ERROR_ALREADY_EXISTS {
|
if err == windows.ERROR_ALREADY_EXISTS {
|
||||||
if handle != 0 {
|
if handle != 0 {
|
||||||
|
|||||||
+81
-14
@@ -21,22 +21,30 @@ import (
|
|||||||
"fyne.io/systray"
|
"fyne.io/systray"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// healthResponse 用于本次流程后续判断的health响应
|
||||||
type healthResponse struct {
|
type healthResponse struct {
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Database string `json:"database"`
|
Database string `json:"database"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Commit string `json:"commit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// serviceURL 用于本次流程后续判断的serviceURL
|
||||||
var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:59188"), "/")
|
var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:59188"), "/")
|
||||||
|
|
||||||
|
// actionMu 用于本次流程后续判断的动作Mu
|
||||||
var (
|
var (
|
||||||
actionMu sync.Mutex
|
actionMu sync.Mutex
|
||||||
transitioning atomic.Bool
|
transitioning atomic.Bool
|
||||||
exitRequested atomic.Bool
|
exitRequested atomic.Bool
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// main 封装main业务协调。
|
||||||
func main() {
|
func main() {
|
||||||
|
// closeLog 用于本次流程后续判断的closeLog
|
||||||
closeLog := configureTrayLogger()
|
closeLog := configureTrayLogger()
|
||||||
defer closeLog()
|
defer closeLog()
|
||||||
|
// releaseInstance、acquired、err 用于本次流程后续判断的releaseInstance、acquired、err
|
||||||
releaseInstance, acquired, err := acquireTrayInstance()
|
releaseInstance, acquired, err := acquireTrayInstance()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("获取托盘单实例锁失败: %v", err)
|
log.Printf("获取托盘单实例锁失败: %v", err)
|
||||||
@@ -56,28 +64,35 @@ func main() {
|
|||||||
// 但实际托盘进程仍然存活。等事件循环真正返回后再处理外部退出。
|
// 但实际托盘进程仍然存活。等事件循环真正返回后再处理外部退出。
|
||||||
if !exitRequested.Load() {
|
if !exitRequested.Load() {
|
||||||
log.Printf("托盘事件循环结束,清理后台服务")
|
log.Printf("托盘事件循环结束,清理后台服务")
|
||||||
if err := quitTray(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := quitTray(); err != nil {
|
||||||
log.Printf("清理后台服务失败: %v", err)
|
log.Printf("清理后台服务失败: %v", err)
|
||||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
} else if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||||
log.Printf("等待后台服务退出失败: %v", err)
|
log.Printf("等待后台服务退出失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("托盘退出")
|
log.Printf("托盘退出")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// watchTerminationSignals 封装watchTerminationSignals业务协调。
|
||||||
func watchTerminationSignals() {
|
func watchTerminationSignals() {
|
||||||
|
// signals 用于本次流程后续判断的signals
|
||||||
signals := make(chan os.Signal, 1)
|
signals := make(chan os.Signal, 1)
|
||||||
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
|
||||||
go func() {
|
go func() {
|
||||||
|
// reason 用于本次流程后续判断的原因
|
||||||
reason := <-signals
|
reason := <-signals
|
||||||
log.Printf("收到进程终止信号: %s", reason)
|
log.Printf("收到进程终止信号: %s", reason)
|
||||||
|
|
||||||
actionMu.Lock()
|
actionMu.Lock()
|
||||||
// actionMu 保证不会与菜单动作并发;拿到锁时其它动作已经完成。
|
// actionMu 保证不会与菜单动作并发;拿到锁时其它动作已经完成。
|
||||||
transitioning.Store(true)
|
transitioning.Store(true)
|
||||||
if err := quitTray(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := quitTray(); err != nil {
|
||||||
log.Printf("终止前停止后台服务失败: %v", err)
|
log.Printf("终止前停止后台服务失败: %v", err)
|
||||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
} else if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||||
log.Printf("终止前等待后台服务退出失败: %v", err)
|
log.Printf("终止前等待后台服务退出失败: %v", err)
|
||||||
}
|
}
|
||||||
transitioning.Store(false)
|
transitioning.Store(false)
|
||||||
@@ -87,21 +102,27 @@ func watchTerminationSignals() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// onTrayExit 封装onTrayExit业务协调。
|
||||||
func onTrayExit() {
|
func onTrayExit() {
|
||||||
// 这里只记录事件。服务清理由 main 在 systray.Run 返回后执行,避免
|
// 这里只记录事件。服务清理由 main 在 systray.Run 返回后执行,避免
|
||||||
// 阻塞原生托盘事件循环。
|
// 阻塞原生托盘事件循环。
|
||||||
log.Printf("收到托盘退出事件")
|
log.Printf("收到托盘退出事件")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// configureTrayLogger 封装configureTrayLogger业务协调。
|
||||||
func configureTrayLogger() func() {
|
func configureTrayLogger() func() {
|
||||||
|
// directory、err 用于本次流程后续判断的directory、err
|
||||||
directory, err := logDirectoryPath()
|
directory, err := logDirectoryPath()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return func() {}
|
return func() {}
|
||||||
}
|
}
|
||||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := os.MkdirAll(directory, 0o755); err != nil {
|
||||||
return func() {}
|
return func() {}
|
||||||
}
|
}
|
||||||
|
// path 用于本次流程后续判断的路径
|
||||||
path := filepath.Join(directory, "tray.log")
|
path := filepath.Join(directory, "tray.log")
|
||||||
|
// file、err 用于本次流程后续判断的file、err
|
||||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return func() {}
|
return func() {}
|
||||||
@@ -111,19 +132,27 @@ func configureTrayLogger() func() {
|
|||||||
return func() { _ = file.Close() }
|
return func() { _ = file.Close() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// onReady 封装onReady业务协调。
|
||||||
func onReady() {
|
func onReady() {
|
||||||
systray.SetTitle("")
|
systray.SetTitle("")
|
||||||
systray.SetIcon(trayIconBytes(false))
|
systray.SetIcon(trayIconBytes(false))
|
||||||
systray.SetTooltip("Ydisks闲鱼助手服务")
|
systray.SetTooltip("Ydisks闲鱼助手服务")
|
||||||
|
|
||||||
|
// statusItem 用于本次流程后续判断的状态商品
|
||||||
statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态")
|
statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态")
|
||||||
|
// openItem 用于本次流程后续判断的open商品
|
||||||
openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面")
|
openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面")
|
||||||
|
// logItem 用于本次流程后续判断的log商品
|
||||||
logItem := systray.AddMenuItem("打开日志目录", "打开后台服务和托盘日志所在目录")
|
logItem := systray.AddMenuItem("打开日志目录", "打开后台服务和托盘日志所在目录")
|
||||||
systray.AddSeparator()
|
systray.AddSeparator()
|
||||||
|
// startItem 用于本次流程后续判断的开始商品
|
||||||
startItem := systray.AddMenuItem("启动服务", "启动后台服务")
|
startItem := systray.AddMenuItem("启动服务", "启动后台服务")
|
||||||
|
// stopItem 用于本次流程后续判断的stop商品
|
||||||
stopItem := systray.AddMenuItem("停止服务", "停止后台服务")
|
stopItem := systray.AddMenuItem("停止服务", "停止后台服务")
|
||||||
|
// restartItem 用于本次流程后续判断的restart商品
|
||||||
restartItem := systray.AddMenuItem("重启服务", "重启后台服务")
|
restartItem := systray.AddMenuItem("重启服务", "重启后台服务")
|
||||||
systray.AddSeparator()
|
systray.AddSeparator()
|
||||||
|
// quitItem 用于本次流程后续判断的quit商品
|
||||||
quitItem := systray.AddMenuItem("退出托盘", "停止后台服务并退出菜单栏控制器")
|
quitItem := systray.AddMenuItem("退出托盘", "停止后台服务并退出菜单栏控制器")
|
||||||
|
|
||||||
// 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保
|
// 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保
|
||||||
@@ -134,41 +163,50 @@ func onReady() {
|
|||||||
refreshStatus(statusItem)
|
refreshStatus(statusItem)
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range openItem.ClickedCh {
|
for range openItem.ClickedCh {
|
||||||
_ = openURL(serviceURL)
|
_ = openURL(serviceURL)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range logItem.ClickedCh {
|
for range logItem.ClickedCh {
|
||||||
if err := openLogDirectory(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := openLogDirectory(); err != nil {
|
||||||
statusItem.SetTitle("日志目录:打开失败")
|
statusItem.SetTitle("日志目录:打开失败")
|
||||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:打开日志目录失败:%v", err))
|
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:打开日志目录失败:%v", err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range startItem.ClickedCh {
|
for range startItem.ClickedCh {
|
||||||
runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem)
|
runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range stopItem.ClickedCh {
|
for range stopItem.ClickedCh {
|
||||||
runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem)
|
runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range restartItem.ClickedCh {
|
for range restartItem.ClickedCh {
|
||||||
runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem)
|
runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
|
// 局部数据 表示当前遍历过程中的局部数据
|
||||||
for range quitItem.ClickedCh {
|
for range quitItem.ClickedCh {
|
||||||
exitTray(statusItem, startItem, stopItem, restartItem, quitItem)
|
exitTray(statusItem, startItem, stopItem, restartItem, quitItem)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// refreshStatus 封装refresh状态业务协调。
|
||||||
func refreshStatus(item *systray.MenuItem) {
|
func refreshStatus(item *systray.MenuItem) {
|
||||||
|
// client 用于本次流程后续判断的client
|
||||||
client := &http.Client{Timeout: 2 * time.Second}
|
client := &http.Client{Timeout: 2 * time.Second}
|
||||||
for {
|
for {
|
||||||
// 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中”
|
// 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中”
|
||||||
@@ -182,7 +220,9 @@ func refreshStatus(item *systray.MenuItem) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// refreshStatusOnce 封装refresh状态Once业务协调。
|
||||||
func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
||||||
|
// status、err 用于本次流程后续判断的status、err
|
||||||
status, err := readHealth(client)
|
status, err := readHealth(client)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
systray.SetIcon(trayIconBytes(false))
|
systray.SetIcon(trayIconBytes(false))
|
||||||
@@ -199,6 +239,7 @@ func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runServiceAction 封装运行Service动作业务协调。
|
||||||
func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle, action string, actionItems ...*systray.MenuItem) {
|
func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle, action string, actionItems ...*systray.MenuItem) {
|
||||||
actionMu.Lock()
|
actionMu.Lock()
|
||||||
defer actionMu.Unlock()
|
defer actionMu.Unlock()
|
||||||
@@ -213,23 +254,28 @@ func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle,
|
|||||||
systray.SetIcon(trayIconBytes(false))
|
systray.SetIcon(trayIconBytes(false))
|
||||||
statusItem.SetTitle("服务状态:" + transitionTitle)
|
statusItem.SetTitle("服务状态:" + transitionTitle)
|
||||||
systray.SetTooltip("Ydisks闲鱼助手:" + transitionTitle)
|
systray.SetTooltip("Ydisks闲鱼助手:" + transitionTitle)
|
||||||
|
// client 用于本次流程后续判断的client
|
||||||
client := &http.Client{Timeout: 2 * time.Second}
|
client := &http.Client{Timeout: 2 * time.Second}
|
||||||
if action == "start" {
|
if action == "start" {
|
||||||
if health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" {
|
if // health、err 用于本次流程后续判断的health、err
|
||||||
|
health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" {
|
||||||
statusItem.SetTitle("服务状态:运行正常")
|
statusItem.SetTitle("服务状态:运行正常")
|
||||||
systray.SetIcon(trayIconBytes(true))
|
systray.SetIcon(trayIconBytes(true))
|
||||||
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := serviceAction(action); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := serviceAction(action); err != nil {
|
||||||
log.Printf("服务操作失败: %s: %v", actionName, err)
|
log.Printf("服务操作失败: %s: %v", actionName, err)
|
||||||
statusItem.SetTitle("服务状态:操作失败")
|
statusItem.SetTitle("服务状态:操作失败")
|
||||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s失败:%v", actionName, err))
|
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s失败:%v", actionName, err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// wantRunning 用于本次流程后续判断的wantRunning
|
||||||
wantRunning := action != "stop"
|
wantRunning := action != "stop"
|
||||||
if err := waitForService(client, wantRunning, 30*time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(client, wantRunning, 30*time.Second); err != nil {
|
||||||
log.Printf("服务操作状态确认失败: %s: %v", actionName, err)
|
log.Printf("服务操作状态确认失败: %s: %v", actionName, err)
|
||||||
statusItem.SetTitle("服务状态:操作失败")
|
statusItem.SetTitle("服务状态:操作失败")
|
||||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s后状态确认失败:%v", actionName, err))
|
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s后状态确认失败:%v", actionName, err))
|
||||||
@@ -246,6 +292,7 @@ func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle,
|
|||||||
log.Printf("服务操作完成: %s", actionName)
|
log.Printf("服务操作完成: %s", actionName)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// exitTray 封装exitTray业务协调。
|
||||||
func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
||||||
actionMu.Lock()
|
actionMu.Lock()
|
||||||
defer actionMu.Unlock()
|
defer actionMu.Unlock()
|
||||||
@@ -259,14 +306,16 @@ func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
|||||||
systray.SetIcon(trayIconBytes(false))
|
systray.SetIcon(trayIconBytes(false))
|
||||||
statusItem.SetTitle("托盘状态:正在退出")
|
statusItem.SetTitle("托盘状态:正在退出")
|
||||||
systray.SetTooltip("Ydisks闲鱼助手:正在停止后台服务")
|
systray.SetTooltip("Ydisks闲鱼助手:正在停止后台服务")
|
||||||
if err := quitTray(); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := quitTray(); err != nil {
|
||||||
log.Printf("退出托盘停止服务失败: %v", err)
|
log.Printf("退出托盘停止服务失败: %v", err)
|
||||||
statusItem.SetTitle("托盘状态:退出失败")
|
statusItem.SetTitle("托盘状态:退出失败")
|
||||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务停止失败:%v", err))
|
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务停止失败:%v", err))
|
||||||
setMenuItemsDisabled(false, actionItems...)
|
setMenuItemsDisabled(false, actionItems...)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||||
log.Printf("退出托盘等待服务停止失败: %v", err)
|
log.Printf("退出托盘等待服务停止失败: %v", err)
|
||||||
statusItem.SetTitle("托盘状态:退出失败")
|
statusItem.SetTitle("托盘状态:退出失败")
|
||||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务仍未退出:%v", err))
|
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务仍未退出:%v", err))
|
||||||
@@ -278,7 +327,9 @@ func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
|||||||
systray.Quit()
|
systray.Quit()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setMenuItemsDisabled 封装setMenu商品列表Disabled业务协调。
|
||||||
func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
||||||
|
// item 表示当前遍历过程中的商品
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
if disabled {
|
if disabled {
|
||||||
item.Disable()
|
item.Disable()
|
||||||
@@ -288,10 +339,14 @@ func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// waitForService 封装waitForService业务协调。
|
||||||
func waitForService(client *http.Client, wantRunning bool, timeout time.Duration) error {
|
func waitForService(client *http.Client, wantRunning bool, timeout time.Duration) error {
|
||||||
|
// deadline 用于本次流程后续判断的deadline
|
||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
for {
|
for {
|
||||||
|
// health、reachable、err 用于本次流程后续判断的health、reachable、err
|
||||||
health, reachable, err := probeHealth(client)
|
health, reachable, err := probeHealth(client)
|
||||||
|
// running 用于本次流程后续判断的running
|
||||||
running := reachable && err == nil && health.Status == "ok" && health.Database == "ok"
|
running := reachable && err == nil && health.Status == "ok" && health.Database == "ok"
|
||||||
if wantRunning && running {
|
if wantRunning && running {
|
||||||
return nil
|
return nil
|
||||||
@@ -311,12 +366,16 @@ func waitForService(client *http.Client, wantRunning bool, timeout time.Duration
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readHealth 封装readHealth业务协调。
|
||||||
func readHealth(client *http.Client) (healthResponse, error) {
|
func readHealth(client *http.Client) (healthResponse, error) {
|
||||||
|
// health、err 用于本次流程后续判断的health、err
|
||||||
health, _, err := probeHealth(client)
|
health, _, err := probeHealth(client)
|
||||||
return health, err
|
return health, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// probeHealth 封装probeHealth业务协调。
|
||||||
func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
||||||
|
// resp、err 用于本次流程后续判断的resp、err
|
||||||
resp, err := client.Get(serviceURL + "/health")
|
resp, err := client.Get(serviceURL + "/health")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return healthResponse{}, false, err
|
return healthResponse{}, false, err
|
||||||
@@ -325,13 +384,16 @@ func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
|||||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
return healthResponse{}, true, fmt.Errorf("health status %d", resp.StatusCode)
|
return healthResponse{}, true, fmt.Errorf("health status %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
// health 用于本次流程后续判断的health
|
||||||
var health healthResponse
|
var health healthResponse
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
|
||||||
return healthResponse{}, true, err
|
return healthResponse{}, true, err
|
||||||
}
|
}
|
||||||
return health, true, nil
|
return health, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openURL 封装openURL业务协调。
|
||||||
func openURL(url string) error {
|
func openURL(url string) error {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||||
@@ -339,12 +401,15 @@ func openURL(url string) error {
|
|||||||
return exec.Command("open", url).Start()
|
return exec.Command("open", url).Start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openLogDirectory 封装openLogDirectory业务协调。
|
||||||
func openLogDirectory() error {
|
func openLogDirectory() error {
|
||||||
|
// directory、err 用于本次流程后续判断的directory、err
|
||||||
directory, err := logDirectoryPath()
|
directory, err := logDirectoryPath()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := os.MkdirAll(directory, 0o755); err != nil {
|
||||||
return fmt.Errorf("创建日志目录失败: %w", err)
|
return fmt.Errorf("创建日志目录失败: %w", err)
|
||||||
}
|
}
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
@@ -357,8 +422,10 @@ func openLogDirectory() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// envOr 封装envOr业务协调。
|
||||||
func envOr(name, fallback string) string {
|
func envOr(name, fallback string) string {
|
||||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
if // value 用于本次流程后续判断的值
|
||||||
|
value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
return fallback
|
return fallback
|
||||||
|
|||||||
+22
-4
@@ -7,60 +7,78 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestWaitForServiceRequiresHealthyResponse 封装TestWaitForServiceRequiresHealthy响应业务协调。
|
||||||
func TestWaitForServiceRequiresHealthyResponse(t *testing.T) {
|
func TestWaitForServiceRequiresHealthyResponse(t *testing.T) {
|
||||||
|
// server 用于本次流程后续判断的server
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
_, _ = w.Write([]byte(`{"status":"degraded","database":"error"}`))
|
_, _ = w.Write([]byte(`{"status":"degraded","database":"error"}`))
|
||||||
}))
|
}))
|
||||||
t.Cleanup(server.Close)
|
t.Cleanup(server.Close)
|
||||||
|
// originalURL 用于本次流程后续判断的originalURL
|
||||||
originalURL := serviceURL
|
originalURL := serviceURL
|
||||||
serviceURL = server.URL
|
serviceURL = server.URL
|
||||||
t.Cleanup(func() { serviceURL = originalURL })
|
t.Cleanup(func() { serviceURL = originalURL })
|
||||||
|
|
||||||
|
// client 用于本次流程后续判断的client
|
||||||
client := server.Client()
|
client := server.Client()
|
||||||
if err := waitForService(client, true, 20*time.Millisecond); err == nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(client, true, 20*time.Millisecond); err == nil {
|
||||||
t.Fatal("degraded health response must not count as running")
|
t.Fatal("degraded health response must not count as running")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWaitForServiceAcceptsHealthyResponse 封装TestWaitForServiceAcceptsHealthy响应业务协调。
|
||||||
func TestWaitForServiceAcceptsHealthyResponse(t *testing.T) {
|
func TestWaitForServiceAcceptsHealthyResponse(t *testing.T) {
|
||||||
|
// server 用于本次流程后续判断的server
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
_, _ = w.Write([]byte(`{"status":"ok","database":"ok"}`))
|
_, _ = w.Write([]byte(`{"status":"ok","database":"ok"}`))
|
||||||
}))
|
}))
|
||||||
t.Cleanup(server.Close)
|
t.Cleanup(server.Close)
|
||||||
|
// originalURL 用于本次流程后续判断的originalURL
|
||||||
originalURL := serviceURL
|
originalURL := serviceURL
|
||||||
serviceURL = server.URL
|
serviceURL = server.URL
|
||||||
t.Cleanup(func() { serviceURL = originalURL })
|
t.Cleanup(func() { serviceURL = originalURL })
|
||||||
|
|
||||||
if err := waitForService(server.Client(), true, time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(server.Client(), true, time.Second); err != nil {
|
||||||
t.Fatalf("healthy response should count as running: %v", err)
|
t.Fatalf("healthy response should count as running: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped 封装TestWaitForServiceDoesNotTreatUnhealthy响应AsStopped业务协调。
|
||||||
func TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped(t *testing.T) {
|
func TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped(t *testing.T) {
|
||||||
|
// server 用于本次流程后续判断的server
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusServiceUnavailable)
|
w.WriteHeader(http.StatusServiceUnavailable)
|
||||||
}))
|
}))
|
||||||
t.Cleanup(server.Close)
|
t.Cleanup(server.Close)
|
||||||
|
// originalURL 用于本次流程后续判断的originalURL
|
||||||
originalURL := serviceURL
|
originalURL := serviceURL
|
||||||
serviceURL = server.URL
|
serviceURL = server.URL
|
||||||
t.Cleanup(func() { serviceURL = originalURL })
|
t.Cleanup(func() { serviceURL = originalURL })
|
||||||
|
|
||||||
if err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil {
|
||||||
t.Fatal("reachable unhealthy service must not count as stopped")
|
t.Fatal("reachable unhealthy service must not count as stopped")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWaitForServiceAcceptsUnreachableAsStopped 封装TestWaitForServiceAcceptsUnreachableAsStopped业务协调。
|
||||||
func TestWaitForServiceAcceptsUnreachableAsStopped(t *testing.T) {
|
func TestWaitForServiceAcceptsUnreachableAsStopped(t *testing.T) {
|
||||||
|
// server 用于本次流程后续判断的server
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||||
|
// client 用于本次流程后续判断的client
|
||||||
client := server.Client()
|
client := server.Client()
|
||||||
|
// originalURL 用于本次流程后续判断的originalURL
|
||||||
originalURL := serviceURL
|
originalURL := serviceURL
|
||||||
serviceURL = server.URL
|
serviceURL = server.URL
|
||||||
t.Cleanup(func() { serviceURL = originalURL })
|
t.Cleanup(func() { serviceURL = originalURL })
|
||||||
server.Close()
|
server.Close()
|
||||||
|
|
||||||
if err := waitForService(client, false, time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForService(client, false, time.Second); err != nil {
|
||||||
t.Fatalf("unreachable service should count as stopped: %v", err)
|
t.Fatalf("unreachable service should count as stopped: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,47 +11,62 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// serviceAction 封装service动作业务协调。
|
||||||
func serviceAction(action string) error {
|
func serviceAction(action string) error {
|
||||||
|
// label 用于本次流程后续判断的label
|
||||||
label := envOr("XIANYU_SERVICE_NAME", "com.ydisks.xianyu-helper.server")
|
label := envOr("XIANYU_SERVICE_NAME", "com.ydisks.xianyu-helper.server")
|
||||||
|
// uid 用于本次流程后续判断的uid
|
||||||
uid := fmt.Sprint(os.Getuid())
|
uid := fmt.Sprint(os.Getuid())
|
||||||
|
// domain 用于本次流程后续判断的domain
|
||||||
domain := "gui/" + uid
|
domain := "gui/" + uid
|
||||||
|
// target 用于本次流程后续判断的target
|
||||||
target := domain + "/" + label
|
target := domain + "/" + label
|
||||||
|
// home、err 用于本次流程后续判断的home、err
|
||||||
home, err := os.UserHomeDir()
|
home, err := os.UserHomeDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("获取用户目录失败: %w", err)
|
return fmt.Errorf("获取用户目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
// plistPath 用于本次流程后续判断的plist路径
|
||||||
plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist")
|
plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist")
|
||||||
switch action {
|
switch action {
|
||||||
case "start":
|
case "start":
|
||||||
if err := launchctl("print", target); err == nil {
|
if // err 用于本次流程后续判断的err
|
||||||
if err := launchctl("kickstart", target); err == nil {
|
err := launchctl("print", target); err == nil {
|
||||||
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("kickstart", target); err == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// launchd 可能仍保留一个正在退出的旧 job;先完整卸载,
|
// launchd 可能仍保留一个正在退出的旧 job;先完整卸载,
|
||||||
// 等它消失后再 bootstrap,避免第二次启动报 Input/output error。
|
// 等它消失后再 bootstrap,避免第二次启动报 Input/output error。
|
||||||
_ = launchctl("bootout", target)
|
_ = launchctl("bootout", target)
|
||||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return launchctl("kickstart", target)
|
return launchctl("kickstart", target)
|
||||||
case "stop":
|
case "stop":
|
||||||
if err := launchctl("print", target); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("print", target); err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := launchctl("bootout", target); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("bootout", target); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return waitForLaunchctlGone(target, 10*time.Second)
|
return waitForLaunchctlGone(target, 10*time.Second)
|
||||||
case "restart":
|
case "restart":
|
||||||
_ = launchctl("bootout", target)
|
_ = launchctl("bootout", target)
|
||||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return launchctl("kickstart", target)
|
return launchctl("kickstart", target)
|
||||||
@@ -60,10 +75,13 @@ func serviceAction(action string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// waitForLaunchctlGone 封装waitForLaunchctlGone业务协调。
|
||||||
func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
||||||
|
// deadline 用于本次流程后续判断的deadline
|
||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
for {
|
for {
|
||||||
if err := launchctl("print", target); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := launchctl("print", target); err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if time.Now().After(deadline) {
|
if time.Now().After(deadline) {
|
||||||
@@ -73,8 +91,10 @@ func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// quitTray 封装quitTray业务协调。
|
||||||
func quitTray() error {
|
func quitTray() error {
|
||||||
if err := serviceAction("stop"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := serviceAction("stop"); err != nil {
|
||||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||||
}
|
}
|
||||||
// 不要从托盘进程内部 bootout 自己的 LaunchAgent。launchctl 可能会先
|
// 不要从托盘进程内部 bootout 自己的 LaunchAgent。launchctl 可能会先
|
||||||
@@ -83,7 +103,9 @@ func quitTray() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// logDirectoryPath 封装logDirectory路径业务协调。
|
||||||
func logDirectoryPath() (string, error) {
|
func logDirectoryPath() (string, error) {
|
||||||
|
// home、err 用于本次流程后续判断的home、err
|
||||||
home, err := os.UserHomeDir()
|
home, err := os.UserHomeDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("获取用户目录失败: %w", err)
|
return "", fmt.Errorf("获取用户目录失败: %w", err)
|
||||||
@@ -91,10 +113,14 @@ func logDirectoryPath() (string, error) {
|
|||||||
return filepath.Join(home, "Library", "Logs", "YdisksXianyuHelper"), nil
|
return filepath.Join(home, "Library", "Logs", "YdisksXianyuHelper"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// launchctl 封装launchctl业务协调。
|
||||||
func launchctl(args ...string) error {
|
func launchctl(args ...string) error {
|
||||||
|
// cmd 用于本次流程后续判断的cmd
|
||||||
cmd := exec.Command("launchctl", args...)
|
cmd := exec.Command("launchctl", args...)
|
||||||
|
// output、err 用于本次流程后续判断的output、err
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// message 用于本次流程后续判断的消息
|
||||||
message := strings.TrimSpace(string(output))
|
message := strings.TrimSpace(string(output))
|
||||||
if message == "" {
|
if message == "" {
|
||||||
return fmt.Errorf("launchctl %s 失败: %w", strings.Join(args, " "), err)
|
return fmt.Errorf("launchctl %s 失败: %w", strings.Join(args, " "), err)
|
||||||
|
|||||||
@@ -7,12 +7,15 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// serviceAction 封装service动作业务协调。
|
||||||
func serviceAction(action string) error {
|
func serviceAction(action string) error {
|
||||||
return fmt.Errorf("当前平台不支持托盘服务操作: %s", action)
|
return fmt.Errorf("当前平台不支持托盘服务操作: %s", action)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// quitTray 封装quitTray业务协调。
|
||||||
func quitTray() error { return nil }
|
func quitTray() error { return nil }
|
||||||
|
|
||||||
|
// logDirectoryPath 封装logDirectory路径业务协调。
|
||||||
func logDirectoryPath() (string, error) {
|
func logDirectoryPath() (string, error) {
|
||||||
return filepath.Join("/var", "log", "ydisks-xianyu-helper"), nil
|
return filepath.Join("/var", "log", "ydisks-xianyu-helper"), nil
|
||||||
}
|
}
|
||||||
@@ -13,8 +13,10 @@ import (
|
|||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// windowsServiceAccess 用于本次流程后续判断的windowsServiceAccess
|
||||||
const windowsServiceAccess = windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP
|
const windowsServiceAccess = windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP
|
||||||
|
|
||||||
|
// windowsServiceController 用于本次流程后续判断的windowsService请求取消控制器
|
||||||
type windowsServiceController interface {
|
type windowsServiceController interface {
|
||||||
state() (uint32, error)
|
state() (uint32, error)
|
||||||
start() error
|
start() error
|
||||||
@@ -22,21 +24,28 @@ type windowsServiceController interface {
|
|||||||
close()
|
close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nativeWindowsServiceController 用于本次流程后续判断的nativeWindowsService请求取消控制器
|
||||||
type nativeWindowsServiceController struct {
|
type nativeWindowsServiceController struct {
|
||||||
handle windows.Handle
|
handle windows.Handle
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// serviceAction 封装service动作业务协调。
|
||||||
func serviceAction(action string) error {
|
func serviceAction(action string) error {
|
||||||
if action != "start" && action != "stop" && action != "restart" {
|
if action != "start" && action != "stop" && action != "restart" {
|
||||||
return fmt.Errorf("未知服务操作: %s", action)
|
return fmt.Errorf("未知服务操作: %s", action)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// name 用于本次流程后续判断的名称
|
||||||
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
|
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
|
||||||
|
// controller、err 用于本次流程后续判断的controller、err
|
||||||
controller, err := openWindowsServiceController(name)
|
controller, err := openWindowsServiceController(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||||
|
return fmt.Errorf("Windows 服务 %s 尚未安装,请重新运行安装器", name)
|
||||||
|
}
|
||||||
if errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
if errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||||
return fmt.Errorf("没有控制 Windows 服务的权限,请重新安装当前版本以更新服务权限")
|
return fmt.Errorf("没有控制 Windows 服务的权限,请重新安装当前版本以更新服务权限")
|
||||||
}
|
}
|
||||||
@@ -47,17 +56,21 @@ func serviceAction(action string) error {
|
|||||||
return controlWindowsService(controller, action, 30*time.Second, 250*time.Millisecond)
|
return controlWindowsService(controller, action, 30*time.Second, 250*time.Millisecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openWindowsServiceController 封装openWindowsService请求取消控制器业务协调。
|
||||||
func openWindowsServiceController(name string) (windowsServiceController, error) {
|
func openWindowsServiceController(name string) (windowsServiceController, error) {
|
||||||
|
// manager、err 用于本次流程后续判断的manager、err
|
||||||
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
|
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer windows.CloseServiceHandle(manager) //nolint:errcheck
|
defer windows.CloseServiceHandle(manager) //nolint:errcheck
|
||||||
|
|
||||||
|
// namePointer、err 用于本次流程后续判断的名称Pointer、err
|
||||||
namePointer, err := windows.UTF16PtrFromString(name)
|
namePointer, err := windows.UTF16PtrFromString(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// handle、err 用于本次流程后续判断的handle、err
|
||||||
handle, err := windows.OpenService(manager, namePointer, windowsServiceAccess)
|
handle, err := windows.OpenService(manager, namePointer, windowsServiceAccess)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -65,6 +78,7 @@ func openWindowsServiceController(name string) (windowsServiceController, error)
|
|||||||
return &nativeWindowsServiceController{handle: handle}, nil
|
return &nativeWindowsServiceController{handle: handle}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// controlWindowsService 封装controlWindowsService业务协调。
|
||||||
func controlWindowsService(controller windowsServiceController, action string, timeout, pollInterval time.Duration) error {
|
func controlWindowsService(controller windowsServiceController, action string, timeout, pollInterval time.Duration) error {
|
||||||
switch action {
|
switch action {
|
||||||
case "start":
|
case "start":
|
||||||
@@ -72,7 +86,8 @@ func controlWindowsService(controller windowsServiceController, action string, t
|
|||||||
case "stop":
|
case "stop":
|
||||||
return ensureWindowsServiceStopped(controller, timeout, pollInterval)
|
return ensureWindowsServiceStopped(controller, timeout, pollInterval)
|
||||||
case "restart":
|
case "restart":
|
||||||
if err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return ensureWindowsServiceRunning(controller, timeout, pollInterval)
|
return ensureWindowsServiceRunning(controller, timeout, pollInterval)
|
||||||
@@ -81,7 +96,9 @@ func controlWindowsService(controller windowsServiceController, action string, t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureWindowsServiceRunning 封装ensureWindowsServiceRunning业务协调。
|
||||||
func ensureWindowsServiceRunning(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
func ensureWindowsServiceRunning(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||||
|
// state、err 用于本次流程后续判断的state、err
|
||||||
state, err := controller.state()
|
state, err := controller.state()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||||
@@ -92,18 +109,22 @@ func ensureWindowsServiceRunning(controller windowsServiceController, timeout, p
|
|||||||
case windows.SERVICE_START_PENDING:
|
case windows.SERVICE_START_PENDING:
|
||||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||||
case windows.SERVICE_STOP_PENDING:
|
case windows.SERVICE_STOP_PENDING:
|
||||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
|
||||||
return fmt.Errorf("启动 Windows 服务失败: %w", err)
|
return fmt.Errorf("启动 Windows 服务失败: %w", err)
|
||||||
}
|
}
|
||||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureWindowsServiceStopped 封装ensureWindowsServiceStopped业务协调。
|
||||||
func ensureWindowsServiceStopped(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
func ensureWindowsServiceStopped(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||||
|
// state、err 用于本次流程后续判断的state、err
|
||||||
state, err := controller.state()
|
state, err := controller.state()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||||
@@ -114,20 +135,25 @@ func ensureWindowsServiceStopped(controller windowsServiceController, timeout, p
|
|||||||
case windows.SERVICE_STOP_PENDING:
|
case windows.SERVICE_STOP_PENDING:
|
||||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||||
case windows.SERVICE_START_PENDING:
|
case windows.SERVICE_START_PENDING:
|
||||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
|
||||||
return fmt.Errorf("停止 Windows 服务失败: %w", err)
|
return fmt.Errorf("停止 Windows 服务失败: %w", err)
|
||||||
}
|
}
|
||||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// waitForWindowsServiceState 封装waitForWindowsService状态业务协调。
|
||||||
func waitForWindowsServiceState(controller windowsServiceController, expected uint32, timeout, pollInterval time.Duration) error {
|
func waitForWindowsServiceState(controller windowsServiceController, expected uint32, timeout, pollInterval time.Duration) error {
|
||||||
|
// deadline 用于本次流程后续判断的deadline
|
||||||
deadline := time.Now().Add(timeout)
|
deadline := time.Now().Add(timeout)
|
||||||
for {
|
for {
|
||||||
|
// state、err 用于本次流程后续判断的state、err
|
||||||
state, err := controller.state()
|
state, err := controller.state()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||||
@@ -142,37 +168,49 @@ func waitForWindowsServiceState(controller windowsServiceController, expected ui
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// state 封装状态业务协调。
|
||||||
func (controller *nativeWindowsServiceController) state() (uint32, error) {
|
func (controller *nativeWindowsServiceController) state() (uint32, error) {
|
||||||
|
// status 用于本次流程后续判断的状态
|
||||||
var status windows.SERVICE_STATUS
|
var status windows.SERVICE_STATUS
|
||||||
if err := windows.QueryServiceStatus(controller.handle, &status); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := windows.QueryServiceStatus(controller.handle, &status); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
return status.CurrentState, nil
|
return status.CurrentState, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// start 封装开始业务协调。
|
||||||
func (controller *nativeWindowsServiceController) start() error {
|
func (controller *nativeWindowsServiceController) start() error {
|
||||||
return windows.StartService(controller.handle, 0, nil)
|
return windows.StartService(controller.handle, 0, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stop 封装stop业务协调。
|
||||||
func (controller *nativeWindowsServiceController) stop() error {
|
func (controller *nativeWindowsServiceController) stop() error {
|
||||||
|
// status 用于本次流程后续判断的状态
|
||||||
var status windows.SERVICE_STATUS
|
var status windows.SERVICE_STATUS
|
||||||
return windows.ControlService(controller.handle, windows.SERVICE_CONTROL_STOP, &status)
|
return windows.ControlService(controller.handle, windows.SERVICE_CONTROL_STOP, &status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// close 封装close业务协调。
|
||||||
func (controller *nativeWindowsServiceController) close() {
|
func (controller *nativeWindowsServiceController) close() {
|
||||||
_ = windows.CloseServiceHandle(controller.handle)
|
_ = windows.CloseServiceHandle(controller.handle)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// quitTray 封装quitTray业务协调。
|
||||||
func quitTray() error {
|
func quitTray() error {
|
||||||
if err := serviceAction("stop"); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := serviceAction("stop"); err != nil {
|
||||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// logDirectoryPath 封装logDirectory路径业务协调。
|
||||||
func logDirectoryPath() (string, error) {
|
func logDirectoryPath() (string, error) {
|
||||||
|
// base 用于本次流程后续判断的base
|
||||||
base := strings.TrimSpace(os.Getenv("PROGRAMDATA"))
|
base := strings.TrimSpace(os.Getenv("PROGRAMDATA"))
|
||||||
if base == "" {
|
if base == "" {
|
||||||
|
// err 用于本次流程后续判断的err
|
||||||
var err error
|
var err error
|
||||||
base, err = os.UserConfigDir()
|
base, err = os.UserConfigDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -11,15 +11,18 @@ import (
|
|||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// fakeWindowsServiceController 用于本次流程后续判断的fakeWindowsService请求取消控制器
|
||||||
type fakeWindowsServiceController struct {
|
type fakeWindowsServiceController struct {
|
||||||
states []uint32
|
states []uint32
|
||||||
actions []string
|
actions []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// state 封装状态业务协调。
|
||||||
func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
||||||
if len(controller.states) == 0 {
|
if len(controller.states) == 0 {
|
||||||
return 0, fmt.Errorf("测试状态序列为空")
|
return 0, fmt.Errorf("测试状态序列为空")
|
||||||
}
|
}
|
||||||
|
// state 用于本次流程后续判断的状态
|
||||||
state := controller.states[0]
|
state := controller.states[0]
|
||||||
if len(controller.states) > 1 {
|
if len(controller.states) > 1 {
|
||||||
controller.states = controller.states[1:]
|
controller.states = controller.states[1:]
|
||||||
@@ -27,19 +30,24 @@ func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
|||||||
return state, nil
|
return state, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// start 封装开始业务协调。
|
||||||
func (controller *fakeWindowsServiceController) start() error {
|
func (controller *fakeWindowsServiceController) start() error {
|
||||||
controller.actions = append(controller.actions, "start")
|
controller.actions = append(controller.actions, "start")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stop 封装stop业务协调。
|
||||||
func (controller *fakeWindowsServiceController) stop() error {
|
func (controller *fakeWindowsServiceController) stop() error {
|
||||||
controller.actions = append(controller.actions, "stop")
|
controller.actions = append(controller.actions, "stop")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// close 封装close业务协调。
|
||||||
func (controller *fakeWindowsServiceController) close() {}
|
func (controller *fakeWindowsServiceController) close() {}
|
||||||
|
|
||||||
|
// TestWindowsRestartWaitsForStoppedBeforeStarting 封装TestWindowsRestartWaitsForStoppedBeforeStarting业务协调。
|
||||||
func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
||||||
|
// controller 用于本次流程后续判断的请求取消控制器
|
||||||
controller := &fakeWindowsServiceController{
|
controller := &fakeWindowsServiceController{
|
||||||
states: []uint32{
|
states: []uint32{
|
||||||
windows.SERVICE_RUNNING,
|
windows.SERVICE_RUNNING,
|
||||||
@@ -50,15 +58,19 @@ func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
|||||||
windows.SERVICE_RUNNING,
|
windows.SERVICE_RUNNING,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
||||||
t.Fatalf("restart Windows service: %v", err)
|
t.Fatalf("restart Windows service: %v", err)
|
||||||
}
|
}
|
||||||
if want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
if // want 用于本次流程后续判断的want
|
||||||
|
want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWindowsStartWaitsForPreviousStop 封装TestWindows开始WaitsForPreviousStop业务协调。
|
||||||
func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
||||||
|
// controller 用于本次流程后续判断的请求取消控制器
|
||||||
controller := &fakeWindowsServiceController{
|
controller := &fakeWindowsServiceController{
|
||||||
states: []uint32{
|
states: []uint32{
|
||||||
windows.SERVICE_STOP_PENDING,
|
windows.SERVICE_STOP_PENDING,
|
||||||
@@ -67,15 +79,19 @@ func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
|||||||
windows.SERVICE_RUNNING,
|
windows.SERVICE_RUNNING,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
if // err 用于本次流程后续判断的err
|
||||||
|
err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
||||||
t.Fatalf("start Windows service: %v", err)
|
t.Fatalf("start Windows service: %v", err)
|
||||||
}
|
}
|
||||||
if want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
if // want 用于本次流程后续判断的want
|
||||||
|
want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWindowsServiceAccessIsLimitedToStatusStartStop 封装TestWindowsServiceAccessIsLimitedTo状态开始Stop业务协调。
|
||||||
func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) {
|
func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) {
|
||||||
|
// want 用于本次流程后续判断的want
|
||||||
want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP)
|
want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP)
|
||||||
if windowsServiceAccess != want {
|
if windowsServiceAccess != want {
|
||||||
t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want)
|
t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want)
|
||||||
|
|||||||
@@ -8,10 +8,6 @@ x-app-env: &app-env
|
|||||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||||
LOG_FORMAT: ${LOG_FORMAT:-json}
|
LOG_FORMAT: ${LOG_FORMAT:-json}
|
||||||
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
||||||
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
|
|
||||||
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
|
|
||||||
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
|
|
||||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
|
|
||||||
|
|
||||||
x-app-volumes: &app-volumes
|
x-app-volumes: &app-volumes
|
||||||
- app_data:/app/data
|
- app_data:/app/data
|
||||||
|
|||||||
@@ -6,10 +6,6 @@ x-app-env: &app-env
|
|||||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||||
LOG_FORMAT: ${LOG_FORMAT:-json}
|
LOG_FORMAT: ${LOG_FORMAT:-json}
|
||||||
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
||||||
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
|
|
||||||
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
|
|
||||||
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
|
|
||||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
|
|
||||||
|
|
||||||
x-app-volumes: &app-volumes
|
x-app-volumes: &app-volumes
|
||||||
- app_data:/app/data
|
- app_data:/app/data
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# API 兼容边界清单
|
||||||
|
|
||||||
|
本文档记录 HTTP API 版本化迁移后的兼容边界,避免在没有证据时删除仍可能被外部客户端使用的旧入口。
|
||||||
|
|
||||||
|
## 当前规则
|
||||||
|
|
||||||
|
- 前端生产 API 适配层只能调用 `/api/v1/...`;该规则由 `frontend/featureArchitecture.test.ts` 校验。
|
||||||
|
- 服务端旧入口继续作为兼容适配层保留,必须复用同一个 handler、鉴权和 DTO,不得复制业务逻辑。
|
||||||
|
- 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。
|
||||||
|
- 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。
|
||||||
|
|
||||||
|
## API 调用方审计
|
||||||
|
|
||||||
|
旧入口的仓库内调用方由 `tools/architecturecheck` 中的
|
||||||
|
`TestFrontendProductionRequestsUseVersionedAPI` 静态清点,并在每次改动前端请求适配层时运行:
|
||||||
|
|
||||||
|
| 调用方范围 | 当前证据 | 结论与删除条件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| React 生产源码(`frontend/**/*.ts`、`frontend/**/*.tsx`,排除测试和构建产物) | 静态扫描未发现未版本化业务请求 | 已迁移到 `/api/v1`;新增调用必须继续通过该门禁 |
|
||||||
|
| React 测试、文档和兼容适配器 | 不作为生产调用方计数 | 可以保留历史样例,但不得被打包到生产请求路径 |
|
||||||
|
| 服务端旧路由 | 各领域版本化契约测试同时请求新旧入口 | 旧路径继续由同一 handler 提供;删除前必须确认外部调用方为零并同步删除契约测试 |
|
||||||
|
| 桌面包、脚本和第三方客户端 | 仓库内无法观测 | 暂不删除;发布侧需要增加请求遥测,连续两个发布周期无调用后才设置 Sunset 版本,并保留回滚版本 |
|
||||||
|
|
||||||
|
该清点只证明仓库内 React 生产请求已经迁移,不能推断外部调用方为零。删除旧路径前,发布说明必须
|
||||||
|
记录调用方审计、Deprecation/Sunset 版本、观测窗口和回滚方式;在证据缺失时保持兼容入口。
|
||||||
|
|
||||||
|
## 受控动态键响应
|
||||||
|
|
||||||
|
以下动态响应是已有客户端依赖的动态键 JSON 形状,本阶段不改变字段形状。它们的值类型仍是具名
|
||||||
|
DTO 或明确标量;架构门禁只允许这类已登记的兼容结构,禁止新增 `map[string]any`、
|
||||||
|
`[]map[string]any` 或未登记的动态响应类型。所有保留项统一通过历史 API 遥测观察,并计划在
|
||||||
|
`v2.0` 评估退场:
|
||||||
|
|
||||||
|
| 响应类型 | 动态键语义 | Sunset | 删除条件 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `settingsResponse` | 非敏感系统设置键 | `v2.0` | 连续两个发布周期外部调用为零,完成前端与桌面包回归 |
|
||||||
|
| `notificationBindingListResponse` | 按账号 ID 分组的绑定列表 | `v2.0` | 连续两个发布周期外部调用为零,保留版本化回滚 |
|
||||||
|
| `automationRulePageResponse` | `trigger_counts` 按触发类型统计 | `v2.0` | 连续两个发布周期外部调用为零,完成契约测试迁移 |
|
||||||
|
|
||||||
|
## 仍保留的旧入口
|
||||||
|
|
||||||
|
服务端目前保留 `/api/...`、`/...` 和 `/admin/...` 等历史入口。仓库内生产 React 调用已经全部迁移到 `/api/v1/...`,服务端契约测试仍覆盖新旧路径的等价响应和权限边界。
|
||||||
|
|
||||||
|
这些旧入口暂不删除,因为它们可能被已部署的桌面包、脚本或第三方客户端调用。只有外部调用方为零、
|
||||||
|
Sunset 到期、回滚方案和契约测试齐备后,才能在独立的后续维护变更中删除,并同步保留版本化入口回归测试。
|
||||||
|
六个正式阶段已经完成,删除兼容入口不得借用或重开阶段状态;变更仍必须通过全部永久启用的架构门禁。
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# HTTP API 版本化迁移边界
|
||||||
|
|
||||||
|
本文记录 API 版本化边界。它不定义重构阶段编号、当前状态或完成结论;新版本路由必须先完成前端调用方迁移和契约测试,再删除旧别名。
|
||||||
|
|
||||||
|
## 当前兼容路径
|
||||||
|
|
||||||
|
| 领域 | 现有路径 | 目标 `/api/v1` 路径 | 迁移状态 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 会话 | `/login`、`/initialize`、`/verify`、`/logout`、`/change-password`、`/account/credentials` | `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session`、`/api/v1/session/logout`、`/api/v1/session/password`、`/api/v1/session/credentials` | React 会话、密码修改和登录凭证调用已迁移到版本化入口;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 账号 | `/cookies`、`/cookies/details`、`/cookies/runtime-status`、`/cookies/{cid}/...` | `/api/v1/accounts`、`/api/v1/accounts/details`、`/api/v1/accounts/runtime-status`、`/api/v1/accounts/{cid}/...` | React 摘要、详情、运行状态、启停状态、设置、备注、暂停、自动确认、长登录、资料刷新、Cookie 更新、登录信息设置和删除调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 商品 | `/items...` | `/api/v1/items...` | React 列表、按账号列表、详情、创建、发布、更新、删除、多规格/多数量设置、同步、类目推荐和批量发布调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 商品批量 | `/items/publish-batches...` | `/api/v1/items/publish-batches...` | 旧路径保留,类目推荐/预检/任务 DTO 已落地 |
|
||||||
|
| 自动化 | `/automation-rules...`、`/automation-issues`、`/automation-runs...`、`/automation-pending-tasks...` | `/api/v1/automation-rules...`、`/api/v1/automation-issues`、`/api/v1/automation-runs...`、`/api/v1/automation-pending-tasks...` | React 规则分页、增删改、异常查询和异常处理调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 订单 | `/api/orders...` | `/api/v1/orders...` | React 列表、详情、更新、删除、刷新、单订单刷新、手动发货和导入调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 设置 | `/system-settings...`、`/user-settings...`、`/ai-reply-settings...`、`/ai-models` | `/api/v1/settings/system...`、`/api/v1/settings/user...`、`/api/v1/settings/ai-reply...`、`/api/v1/settings/ai-models` | React 系统设置、AI 设置调用已迁移;版本化入口覆盖公开设置、管理员设置、用户设置和 AI 模型查询;旧路径保留 |
|
||||||
|
| 卡券 | `/cards...` | `/api/v1/cards...` | React 卡券列表、CRUD、批量创建和追加调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 通知 | `/notification-channels...`、`/message-notifications...` | `/api/v1/notifications/channels...`、`/api/v1/notifications/messages...`、`/api/v1/notifications/accounts/{cid}/bindings` | React 通知渠道、消息绑定和账号绑定调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 聊天 | `/api/chat...` | `/api/v1/chat...` | React 会话、消息、图片、已读和 WebSocket 调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 关键词回复 | `/keywords...`、`/keywords-with-item-id...`、`/keywords-with-type...`、`/item-reply...`、`/itemReplays` | `/api/v1/reply-rules/{cid}...`、`/api/v1/reply-rules/items...` | React 类型规则、指定商品回复调用已迁移;版本化入口覆盖基础/商品/类型规则和指定商品回复;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 默认回复 | `/default-replies...`、`/api/default-replies`、`/api/default-reply...` | `/api/v1/default-replies`、`/api/v1/default-replies/list`、`/api/v1/default-replies/{cid}...` | React 单账号、列表、删除和记录清理调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 账号任务 | `/api/account-tasks...` | `/api/v1/account-tasks...` | React 设置和执行调用已迁移;版本化入口覆盖设置、运行记录和执行摘要;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 管理员 | `/admin/users...`、`/admin/cookies...`、`/admin/stats`、`/change-admin-password` | `/api/v1/admin/users...`、`/api/v1/admin/cookies...`、`/api/v1/admin/stats`、`/api/v1/admin/password` | React 管理员统计调用已迁移;管理员密码也提供版本化兼容入口并保留权限边界;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 统计 | `/dashboard/stats`、`/analytics/orders...` | `/api/v1/analytics/dashboard`、`/api/v1/analytics/orders...` | React 仪表盘、订单分析和有效订单调用已迁移;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 二维码登录 | `/qr-login/generate`、`/qr-login/check/{session_id}`、`/qr-login/status/{session_id}`、`/qr-login/complete-verification/{session_id}` | `/api/v1/qr-login/generate`、`/api/v1/qr-login/check/{session_id}`、`/api/v1/qr-login/status/{session_id}`、`/api/v1/qr-login/complete-verification/{session_id}` | React 二维码生成、状态轮询和风控验证完成调用已迁移;状态持久化兼容入口同步提供;旧路径保留并由同一 handler 提供 |
|
||||||
|
| 密码登录 | `/password-login`、`/password-login/check/{session_id}`、`/password-login/cancel/{session_id}` | `/api/v1/password-login`、`/api/v1/password-login/check/{session_id}`、`/api/v1/password-login/cancel/{session_id}` | React 密码登录、状态查询和取消调用已迁移;当前仍返回明确的禁用错误;旧路径保留并由同一 handler 提供 |
|
||||||
|
|
||||||
|
## 迁移规则
|
||||||
|
|
||||||
|
1. 新增接口只能使用 `/api/v1` 前缀,禁止继续增加未版本化的业务路径。
|
||||||
|
2. 旧路径通过同一 handler 或薄适配器保留,不复制业务逻辑;适配器只负责路径和请求/响应兼容。
|
||||||
|
3. 前端请求层先切换到 `/api/v1`,并保留旧响应字段的边界归一;Go、React 和外部调用方契约测试全部通过后,才可以删除旧别名。
|
||||||
|
4. 删除旧路径前必须记录调用方、发布日期、迁移版本和回滚方案;发布说明要明确旧路径的移除版本。
|
||||||
|
5. 错误响应始终使用 `code`、`message`、`request_id`,恢复信息只能放入 `details`;版本适配器不得重新引入 `detail`、`msg` 或 HTTP 200 + `success:false`。
|
||||||
|
|
||||||
|
## API 版本化证据
|
||||||
|
|
||||||
|
- 认证会话校验使用 `sessionVerificationResponse`。
|
||||||
|
- 账号详情、设置、资料刷新和暂停查询使用 `cookieDetailResponse`、`cookieSettingsResponse`、`cookieProfileResponse` 与 `pauseDurationResponse`。
|
||||||
|
- 商品发布、同步、列表和详情使用 `itemPublishResponse`、`itemSyncResponse`、`itemPageSyncResponse`、`itemListResponse` 与 `itemDetailResponse`。
|
||||||
|
- 商品批量发布使用 `categoryRecommendationResponse`、`itemPublishBatchPreviewResponse`、`batchIDResponse`、`batchCancelResponse`、`itemPublishBatchResponse` 与 `itemPublishBatchListResponse`。
|
||||||
|
- 自动化规则分页、动作和异常列表使用 `automationRulePageResponse`、`automationRuleResponse`、`automationActionResponse` 与 `automationIssuesResponse`。
|
||||||
|
- 订单列表、详情、刷新和批量外层结果使用 `orderListResponse`、`orderDetailResponse`、`orderRefreshResponse` 与 `manualShipResponse`/`importOrdersResponse`。
|
||||||
|
- 设置、卡券和通知分别使用 `operationResponse`、`aiReplySettingsResponse`、`aiModelsResponse`、`userSettingResponse`、`cardResponse`、`cardBatchResponse`、`notificationChannelResponse`、`notificationBindingResponse` 与 `accountBindingsResponse`。
|
||||||
|
- 关键词回复、默认回复和账号任务分别使用 `keywordBasicResponse`/`keywordItemResponse`/`keywordTypedResponse`、`itemReplyResponse`、`defaultReplyResponse`、`accountTaskSettingsResponse`、`accountTaskRunsResponse` 与 `accountTaskRunResponseEnvelope`。
|
||||||
|
- 管理员和统计分别使用 `adminUserResponse`/`adminCookieResponse`/`adminStatsResponse`、`dashboardStatsResponse`、`orderAnalyticsResponse` 与 `validOrdersResponse`;二维码生成使用 `qrLoginGenerateResponse`。
|
||||||
|
- 动态设置和二维码兼容边界分别使用 `settingsResponse`、`qrLoginStatusResponse` 与 `qrLoginVerificationResponse`;二维码状态契约测试确认 `cookies` 等敏感字段不会回传。
|
||||||
|
- 会话登录、初始化、校验、登出、密码修改和登录凭证更新已由 React 请求层迁移到 `/api/v1/session/...`;管理员密码提供 `/api/v1/admin/password` 兼容入口,Go 契约测试确认版本化入口与旧路径共用 handler 且旧路径仍可用。
|
||||||
|
- 账号摘要、非敏感详情、运行状态、启停状态、设置、备注、暂停、自动确认、长登录、资料刷新、Cookie 更新和登录信息设置已由 React 请求层迁移到 `/api/v1/accounts...`;Go 契约测试确认账号详情与凭证变更响应不泄露 Cookie/密码,且旧详情、设置和登录信息入口仍可用。
|
||||||
|
- 订单列表、详情和更新已由 React 请求层迁移到 `/api/v1/orders...`;Go 契约测试确认版本化入口与旧更新入口共用 handler,订单归属校验和状态更新语义保持不变。
|
||||||
|
- 订单刷新、单订单刷新、手动发货和导入已由 React 请求层迁移到 `/api/v1/orders...`;Go 契约测试确认新旧批量入口保持状态码、具名响应和参数校验语义一致。
|
||||||
|
- 商品列表、按账号列表、详情、创建、发布、更新、删除、多规格/多数量设置已由版本化路由提供,React 请求层已迁移实际调用;Go 契约测试确认新旧入口保持商品所有权校验、具名响应和持久化语义一致。
|
||||||
|
- 商品同步、类目推荐、批量发布预检、任务查询、取消、重试和结果下载已由版本化路由提供;React 现有同步/批量发布调用已迁移,Go 契约测试确认新旧入口状态码和参数校验语义一致。
|
||||||
|
- 系统/用户/AI 设置、卡券 CRUD/批量/追加和通知渠道/消息/账号绑定已由版本化路由提供;React 设置、卡券和通知调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致。
|
||||||
|
- 聊天会话、消息、图片、已读和 WebSocket,以及账号任务设置、运行记录和执行已由版本化路由提供;React REST/WebSocket 调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致。
|
||||||
|
- 关键词基础/商品/类型规则、指定商品回复和默认回复列表/单账号/清理已由版本化路由提供;React 关键词与默认回复调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致。
|
||||||
|
- 管理员用户/账号/统计、仪表盘统计、订单分析和有效订单分页已由版本化路由提供;React 管理员统计与仪表盘调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致,普通用户无法访问管理员版本化入口。
|
||||||
|
- 二维码生成、扫码状态查询、状态持久化和验证完成已由版本化路由提供;React 生成、轮询和验证完成调用已迁移,Go/React 契约测试确认新旧入口认证、会话所有权和状态码语义一致,状态响应继续过滤 Cookie 等敏感字段。
|
||||||
|
- 会话密码修改、登录凭证更新、账号删除、密码登录禁用入口、自动化规则/异常处理、订单删除和商品创建已由版本化路由提供;React 对应调用已迁移,Go/React 契约测试确认新旧入口权限、状态码和参数校验语义一致。
|
||||||
|
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
|
||||||
|
- React 的 feature API adapter 已直接使用 `frontend/shared/api-contract/*` 中的具名响应 DTO,并在 adapter 边界完成兼容字段归一;通用请求、错误解析和契约校验位于 `frontend/shared/http/*`。
|
||||||
|
- 会话、账号、订单、商品、自动化、设置、卡券、通知、聊天、账号任务、关键词、默认回复、管理员、统计、二维码登录和密码登录版本化入口已可用;旧路径继续保留。
|
||||||
|
- 最终调用方审计确认 React 生产请求、批量结果下载和 Vite 开发代理均不再使用业务旧路径;旧路径仅作为服务端兼容入口保留,后续删除必须遵循调用方、发布日期和回滚条件记录。
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
# 全函数与全变量中文注释规范
|
||||||
|
|
||||||
|
## 1. 适用范围
|
||||||
|
|
||||||
|
本规范适用于仓库中的 Go、TypeScript 和 TSX 生产代码与测试代码。
|
||||||
|
生成代码、第三方代码、`internal/webui/static` 构建产物和数据文件不在手工注释范围内。
|
||||||
|
|
||||||
|
所有新增或修改的声明必须立即满足本规范。历史代码通过注释检查基线渐进清理;
|
||||||
|
每个重构阶段必须清除其负责文件内的历史注释债务,最终删除全部基线豁免。
|
||||||
|
|
||||||
|
## 2. 注释质量原则
|
||||||
|
|
||||||
|
注释必须至少解释下列一项实际信息:
|
||||||
|
|
||||||
|
- 业务职责或业务含义;
|
||||||
|
- 输入、输出和错误语义;
|
||||||
|
- 数据单位、格式、取值范围或默认值;
|
||||||
|
- 生命周期、所有权、取消和释放责任;
|
||||||
|
- 并发保护、锁顺序或 goroutine 责任;
|
||||||
|
- 敏感数据的用途和禁止传播范围;
|
||||||
|
- 兼容来源、删除条件或外部协议约束;
|
||||||
|
- 采用某种实现而非直观实现的原因。
|
||||||
|
|
||||||
|
禁止只把标识符翻译成中文或复述语法。例如“err 表示错误”“count 表示数量”不合格;
|
||||||
|
应说明是什么操作的错误、统计什么对象、单位是什么以及如何使用。
|
||||||
|
|
||||||
|
修改代码语义时必须同步更新相关注释。错误注释视为缺陷,不得以“已有注释”为由保留。
|
||||||
|
|
||||||
|
## 3. Go 规范
|
||||||
|
|
||||||
|
### 3.1 Package、类型和函数
|
||||||
|
|
||||||
|
- 每个 package 必须有唯一 package 注释;
|
||||||
|
- 每个导出和未导出类型必须有中文注释;
|
||||||
|
- 每个函数和方法必须有中文注释;
|
||||||
|
- 导出标识符注释遵循 Go 文档约定,以标识符名称或可读主语开头;
|
||||||
|
- 函数注释必须解释所有参数、返回值、主要副作用和错误语义;
|
||||||
|
- 方法注释应说明 receiver 所代表对象以及是否可并发调用;
|
||||||
|
- 匿名函数必须由变量注释或紧邻注释说明用途和回调参数。
|
||||||
|
|
||||||
|
### 3.2 变量与常量
|
||||||
|
|
||||||
|
以下声明必须有准确中文注释:
|
||||||
|
|
||||||
|
- package 级 `var` 与 `const`;
|
||||||
|
- const block 中的每个语义不同成员;
|
||||||
|
- 结构体字段;
|
||||||
|
- 接口方法及参数;
|
||||||
|
- 函数参数和命名返回值;
|
||||||
|
- 局部 `var`;
|
||||||
|
- `:=` 短变量声明;
|
||||||
|
- `for`/`range` 的索引和值变量;
|
||||||
|
- type switch、类型断言和 map 查询中的 `ok`;
|
||||||
|
- 闭包捕获的状态变量;
|
||||||
|
- 锁、Context、CancelFunc、WaitGroup、channel 和 timer。
|
||||||
|
|
||||||
|
同一条声明可以由一条注释分别解释全部变量:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// account 保存已通过所有权校验的账号摘要;queryErr 保存读取摘要时产生的数据库错误。
|
||||||
|
account, queryErr := repository.GetSummary(ctx, accountID)
|
||||||
|
```
|
||||||
|
|
||||||
|
循环变量必须说明当前遍历对象:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// rowIndex 表示导入文件中的数据行下标;row 保存当前待验证的订单数据。
|
||||||
|
for rowIndex, row := range rows {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 并发注释
|
||||||
|
|
||||||
|
包含锁或 goroutine 的类型和函数必须明确:
|
||||||
|
|
||||||
|
- 锁保护哪些字段;
|
||||||
|
- 是否允许持锁调用外部 I/O;
|
||||||
|
- 多个锁的获取顺序;
|
||||||
|
- goroutine 由谁启动、取消和等待;
|
||||||
|
- channel 的发送者、接收者和关闭者;
|
||||||
|
- Context 的来源和取消责任;
|
||||||
|
- Stop/Close 是否幂等。
|
||||||
|
|
||||||
|
### 3.4 敏感数据注释
|
||||||
|
|
||||||
|
Cookie、Token、密码、SMTP 凭证和远程滑块秘密必须标明:
|
||||||
|
|
||||||
|
- 值是否为明文;
|
||||||
|
- 允许存在的最小作用域;
|
||||||
|
- 是否允许日志记录或 JSON 序列化;
|
||||||
|
- 由谁负责加密、解密和更新。
|
||||||
|
|
||||||
|
## 4. TypeScript 与 TSX 规范
|
||||||
|
|
||||||
|
### 4.1 函数和组件
|
||||||
|
|
||||||
|
- React 组件使用中文 JSDoc 说明页面或组件职责;
|
||||||
|
- Hook 必须说明拥有的状态、执行的副作用、取消方式和返回值;
|
||||||
|
- 事件处理器必须说明由什么用户操作触发以及成功后的状态变化;
|
||||||
|
- 数据转换函数必须说明输入 DTO、输出 UI model 和兼容逻辑;
|
||||||
|
- 回调函数的参数必须由紧邻注释解释;
|
||||||
|
- `useEffect` 必须说明同步的外部系统和 cleanup 责任,不能只写“初始化”。
|
||||||
|
|
||||||
|
### 4.2 变量和状态
|
||||||
|
|
||||||
|
以下声明必须有准确中文注释:
|
||||||
|
|
||||||
|
- module 级 `const`/`let`;
|
||||||
|
- 组件和函数内的 `const`/`let`;
|
||||||
|
- `useState` 的状态值和 setter;
|
||||||
|
- `useRef` 保存的临时值、DOM 或生命周期标记;
|
||||||
|
- `useMemo` 的派生值及其昂贵原因;
|
||||||
|
- `useCallback` 的用途;
|
||||||
|
- 解构变量;
|
||||||
|
- `map`、`filter`、`reduce` 等回调参数;
|
||||||
|
- `catch` 错误变量;
|
||||||
|
- 表单、请求、分页、轮询和 generation 状态。
|
||||||
|
|
||||||
|
同一条 Hook 声明可以共用一条注释:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
/** accounts 保存账号摘要;setAccounts 只在当前请求仍为最新请求时替换列表。 */
|
||||||
|
const [accounts, setAccounts] = useState<AccountSummary[]>([]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 React 注释必须包含的特殊信息
|
||||||
|
|
||||||
|
- 异步请求是否可以取消;
|
||||||
|
- 晚到响应如何防止覆盖新状态;
|
||||||
|
- state 是服务端数据、表单数据还是短暂 UI 状态;
|
||||||
|
- derived value 为什么需要或不需要 memo;
|
||||||
|
- effect 的依赖和 cleanup 是否完整;
|
||||||
|
- 敏感字段是否会进入浏览器状态。
|
||||||
|
|
||||||
|
## 5. 自动检查与人工审查
|
||||||
|
|
||||||
|
自动检查负责:
|
||||||
|
|
||||||
|
- 声明附近是否存在注释;
|
||||||
|
- 注释是否包含中文;
|
||||||
|
- 新增声明是否被历史基线错误豁免。
|
||||||
|
|
||||||
|
导出 Go 标识符的 doc comment 起始词、参数语义和并发/敏感数据说明由人工审查负责,后续可在不放宽中文门禁的前提下增加静态规则。
|
||||||
|
|
||||||
|
人工审查负责:
|
||||||
|
|
||||||
|
- 注释是否准确;
|
||||||
|
- 是否解释实际语义而不是复述代码;
|
||||||
|
- 并发、敏感性和兼容条件是否完整;
|
||||||
|
- 代码变化后注释是否仍然成立。
|
||||||
|
|
||||||
|
PR 描述必须声明本次清理了哪些文件的注释基线,并列出仍保留的历史范围。
|
||||||
|
|
||||||
|
## 6. 禁止做法
|
||||||
|
|
||||||
|
- 禁止为了通过检查批量生成“变量 X 保存 X”一类注释;
|
||||||
|
- 禁止用英文占位注释替代中文解释;
|
||||||
|
- 禁止注释掉旧代码而不删除;
|
||||||
|
- 禁止使用注释掩盖过长函数或错误抽象;
|
||||||
|
- 禁止因补注释顺手修改无关行为;
|
||||||
|
- 禁止修改生成文件来满足手工注释检查;
|
||||||
|
- 禁止让注释泄露密码、Cookie、Token 或真实生产数据。
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
# 架构依赖与边界规则
|
||||||
|
|
||||||
|
## 1. 目的
|
||||||
|
|
||||||
|
本文定义重构期间和目标状态下的依赖方向。过渡期允许保留已有直接依赖,
|
||||||
|
但禁止新增同类耦合;每个正式阶段必须减少而不是扩大例外。阶段编号、状态和交付规则只由
|
||||||
|
refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态。
|
||||||
|
|
||||||
|
## 2. 通用规则
|
||||||
|
|
||||||
|
- 接口由能力消费者定义,不在实现包中建立包含所有方法的万能接口;
|
||||||
|
- 上层依赖抽象,下层实现抽象;
|
||||||
|
- 不为消除 import 而创建没有业务语义的中转包;
|
||||||
|
- 不允许全局 service locator;
|
||||||
|
- 必需依赖在构造阶段提供并验证,不使用运行时 setter 回填;
|
||||||
|
- package 不得因测试方便而导出生产不需要的内部状态;
|
||||||
|
- 不允许通过 `any`、动态 map 或反射绕过清晰依赖。
|
||||||
|
|
||||||
|
## 3. Go 目标边界
|
||||||
|
|
||||||
|
### 3.1 `cmd`
|
||||||
|
|
||||||
|
允许:
|
||||||
|
|
||||||
|
- 读取配置和环境;
|
||||||
|
- 构造日志、数据库和应用;
|
||||||
|
- 处理系统信号;
|
||||||
|
- 调用应用 Start/Run/Stop。
|
||||||
|
|
||||||
|
禁止新增:
|
||||||
|
|
||||||
|
- 业务规则;
|
||||||
|
- SQL;
|
||||||
|
- HTTP handler;
|
||||||
|
- 平台协议解析;
|
||||||
|
- 账号状态机。
|
||||||
|
|
||||||
|
### 3.2 `internal/server`
|
||||||
|
|
||||||
|
允许:
|
||||||
|
|
||||||
|
- 路由和 middleware;
|
||||||
|
- 鉴权上下文;
|
||||||
|
- 请求解析、验证和 DTO;
|
||||||
|
- 调用应用服务;
|
||||||
|
- HTTP/WebSocket transport;
|
||||||
|
- SPA 静态资源。
|
||||||
|
|
||||||
|
目标状态禁止:
|
||||||
|
|
||||||
|
- 直接导入 `internal/db`;
|
||||||
|
- 直接导入 `internal/xianyu` 或 `internal/browser`;
|
||||||
|
- 调用 `BeginTx`;
|
||||||
|
- 保存业务 worker、锁、cancel map 或平台会话状态;
|
||||||
|
- 直接实现订单同步、商品发布、凭证续期或自动化动作。
|
||||||
|
|
||||||
|
过渡期已有依赖可以在对应正式阶段完成前保留,但不得新增新的直接调用点。
|
||||||
|
|
||||||
|
### 3.3 应用服务
|
||||||
|
|
||||||
|
允许:
|
||||||
|
|
||||||
|
- 编排一个完整用户用例;
|
||||||
|
- 所有权校验;
|
||||||
|
- 事务边界;
|
||||||
|
- 调用领域服务和消费者定义的 port;
|
||||||
|
- 将基础设施错误转换为应用错误。
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 依赖 `http.Request`、`http.ResponseWriter` 或 chi;
|
||||||
|
- 依赖 React/前端字段别名;
|
||||||
|
- 拼装 SQL;
|
||||||
|
- 直接读取环境变量;
|
||||||
|
- 返回包含明文秘密的通用模型。
|
||||||
|
|
||||||
|
### 3.4 `internal/db`
|
||||||
|
|
||||||
|
允许:
|
||||||
|
|
||||||
|
- SQL、迁移、方言差异;
|
||||||
|
- repository 实现;
|
||||||
|
- 加密存储;
|
||||||
|
- 事务实现;
|
||||||
|
- 持久化查询模型。
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 导入 server、应用服务、engine 或 automation;
|
||||||
|
- 依赖 HTTP DTO;
|
||||||
|
- 调用 MTOP、WebSocket 或 browser;
|
||||||
|
- 决定用户可见错误消息;
|
||||||
|
- 将敏感持久化模型直接暴露给 HTTP。
|
||||||
|
|
||||||
|
### 3.5 `internal/xianyu` 与 `internal/browser`
|
||||||
|
|
||||||
|
允许:
|
||||||
|
|
||||||
|
- 平台协议、传输和浏览器实现;
|
||||||
|
- 返回平台级结果和错误分类;
|
||||||
|
- 实现应用层或领域层定义的最小接口。
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 导入 server;
|
||||||
|
- 直接写业务数据库;
|
||||||
|
- 决定自动化规则或 HTTP 状态;
|
||||||
|
- 反向启动 account manager;
|
||||||
|
- 绕过冻结滑块规范。
|
||||||
|
|
||||||
|
### 3.6 `internal/engine` 与 `internal/automation`
|
||||||
|
|
||||||
|
- Engine 负责单账号消息运行时,不负责 HTTP;
|
||||||
|
- Automation 负责规则运行和动作语义,不负责 HTTP DTO;
|
||||||
|
- 两者不得依赖 Server;
|
||||||
|
- 新依赖必须通过最小接口注入;
|
||||||
|
- 并发状态必须由明确组件拥有,禁止共享无边界的可变结构;
|
||||||
|
- 外部动作必须保留幂等、checkpoint 和结果不确定语义。
|
||||||
|
|
||||||
|
## 4. 数据与秘密边界
|
||||||
|
|
||||||
|
- AccountSummary 不包含 Cookie、Token、密码或加密 metadata;
|
||||||
|
- AccountCredential 只能进入平台调用和凭证更新流程;
|
||||||
|
- AccountLoginSecret 只能进入密码登录或续期流程;
|
||||||
|
- 所有权查询只能返回存在性或非敏感 ID;
|
||||||
|
- HTTP DTO 不得引用敏感模型;
|
||||||
|
- 日志、通知和错误响应不得包含秘密;
|
||||||
|
- 测试失败输出不得打印完整秘密;
|
||||||
|
- 锁住账号凭证期间不得执行未明确允许的慢外部 I/O。
|
||||||
|
|
||||||
|
## 5. API 边界
|
||||||
|
|
||||||
|
- 新 API 使用 `/api/v1`;
|
||||||
|
- 新请求和响应必须使用具名 DTO;
|
||||||
|
- 新错误使用统一错误 envelope;
|
||||||
|
- 禁止新增 HTTP 200 + `success:false`;
|
||||||
|
- 禁止新增 `value/cookie`、`remark/note` 一类双重字段;
|
||||||
|
- 兼容字段只能在边界 adapter 中归一;
|
||||||
|
- 删除兼容层必须有调用方迁移和契约测试证据。
|
||||||
|
|
||||||
|
## 6. React 边界
|
||||||
|
|
||||||
|
目标结构为 `app -> features -> shared`:
|
||||||
|
|
||||||
|
- `app` 负责 shell、路由和顶层认证;
|
||||||
|
- feature 负责自己的页面、Hook、组件、API adapter 和类型;
|
||||||
|
- shared 只包含真正跨 feature 的请求客户端、UI、Hook 和工具;
|
||||||
|
- feature 不得导入另一个 feature 的内部文件;
|
||||||
|
- shared 不得反向导入 feature;
|
||||||
|
- 组件不得直接调用 `fetch` 或 `axios`;
|
||||||
|
- 通用 HTTP client 不包含订单、账号等领域归一逻辑;
|
||||||
|
- 生成 API 类型只读,UI model 由 feature adapter 创建;
|
||||||
|
- 禁止通过大型 barrel 文件隐藏实际依赖。
|
||||||
|
|
||||||
|
## 7. 事务与生命周期边界
|
||||||
|
|
||||||
|
- 跨 repository 原子操作由应用服务通过 Unit of Work 执行;
|
||||||
|
- handler 和 React 层不得控制数据库事务;
|
||||||
|
- goroutine 必须有明确 owner、Context 和 Wait;
|
||||||
|
- channel 只能由约定的发送方关闭;
|
||||||
|
- Start 前不隐式运行后台任务;
|
||||||
|
- Stop/Close 必须幂等;
|
||||||
|
- 不得持锁等待无法控制的网络、浏览器或用户操作;
|
||||||
|
- 凭证锁、自动化卡密锁和 worker 锁的顺序必须被注释和测试保护。
|
||||||
|
|
||||||
|
## 8. 自动门禁路线
|
||||||
|
|
||||||
|
门禁应按目标边界逐步启用:
|
||||||
|
|
||||||
|
1. 当前正式阶段开始前先启用该阶段的 fail-closed AST、依赖或行为门禁;当前阶段违规必须立即失败。
|
||||||
|
2. 已完成阶段的门禁永久保留;后续阶段专有门禁只在该阶段成为当前阶段时启用。
|
||||||
|
3. 阶段目标边界禁止使用白名单、baseline、忽略目录或降级告警豁免;阶段内失败只能通过完成迁移消除。
|
||||||
|
4. 最终使用 `go list`、AST 与前端依赖规则检查完整依赖图,不能只依赖少量名称匹配。
|
||||||
|
5. 仅生成物和冻结文件可有精确范围排除;它们不是架构违规的通用例外,也不能覆盖生产源码。
|
||||||
|
6. 禁止为了让门禁通过而把依赖藏进反射、动态 import、service locator 或无语义中转层。
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# 生命周期与后台任务清单
|
||||||
|
|
||||||
|
本文是生命周期静态审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
|
||||||
|
用于防止后续迭代重新引入游离 goroutine;它不定义阶段编号、阶段状态或验收结论。
|
||||||
|
|
||||||
|
## 组件清单
|
||||||
|
|
||||||
|
| 组件/入口 | 所有者 | Context 来源 | 停止/关闭 | 等待/观测 | 当前证据 | 剩余风险 |
|
||||||
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| `lifecycle.Coordinator` | `cmd/server` 进程组合根 | `Start(parent)` 创建共享应用生命周期 Context;每次 `Close(ctx)` 使用调用方关闭预算 | 取消共享 Context,按登记逆序调用组件 `Close(ctx)`;成功组件记录完成,失败组件保留以便更长 Context 重试 | `Close` 返回本次聚合诊断;并发调用等待本次尝试;`WaitContext` 仅在全部组件成功收束后完成 | 启动失败回滚、重复 Start/Close、关闭竞态、超时诊断和可重试 Join 测试 | 关闭组件必须自行响应 Context;同步外部调用依赖明确硬超时 |
|
||||||
|
| `server.Server` HTTP 与请求后台任务 | `cmd/server`(HTTP)/`server.Server`(请求任务观测) | `Server.Start` 接收的进程 Context;请求任务使用调用方显式 Context | `Server.Stop(ctx)` 只关闭 HTTP 与请求任务等待;应用 worker 不由 Server 关闭 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 业务 worker 已移出 Server;任务业务语义继续由应用服务维护 |
|
||||||
|
| 订单刷新 worker/recovery | `lifecycle.Coordinator` → `orders.RefreshJobService` | 协调器共享应用生命周期 Context;请求只负责创建任务 | 协调器逆序 `Close(ctx)`,runner 通过租约 token 和 Context 收束 | 应用任务状态、租约终态和 runner `Wait/Close` | 订单刷新生命周期、租约、取消和晚到写入测试 | 统一运维查询属于后续观测迭代,不改变生命周期所有权 |
|
||||||
|
| 商品批量发布 worker/recovery | `lifecycle.Coordinator` → `items.BatchWorkerCoordinator` | 协调器共享应用生命周期 Context;取消后的本地收口使用受控补偿 Context | 协调器逆序 `Close(ctx)`,worker cancel、租约 token 和终态补偿由应用协调器负责 | 批次状态、协调器 `Wait/Close` 与错误回调 | 批量取消 race、应用 BatchRunner 和协调器测试 | 恢复指标属于后续观测迭代,不改变生命周期所有权 |
|
||||||
|
| 订单 reconciliation worker | `lifecycle.Coordinator` → `orders.ReconciliationRecoveryCoordinator` | 协调器共享应用生命周期 Context | 协调器逆序 `Close(ctx)` 取消当前扫描并等待退出 | 补偿记录状态与协调器 `Wait/Close` | reconciliation 成功/失败重试、取消和协调器测试 | 指数退避属于后续补偿策略迭代 |
|
||||||
|
| `account.Manager` 账号运行时集合 | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopAllContext`,保留全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing、生命周期和 race 测试 | 运行时内部任务的细分由正式总计划决定,不改变进程级 owner |
|
||||||
|
| `engine.Account` 单账号运行时 | `account.Manager`;连接、出站、凭证和迟到续期分别由 `connectionCoordinator`、`outgoingMessageCoordinator`、`credentialCoordinator`、`pendingRenewalCoordinator` 负责 | `Account.Run(parent)` | `StopContext` 取消运行 Context;连接协调器以受限预算等待自有 worker | `StopContext` 返回错误;共享完成信号支持超时后的再次 Join;运行状态可查询 | Engine lifecycle、连接协调器、出站发送、credential coordinator、刷新取消与迟到续期测试 | recorder 子任务继续沿用账号运行 Context,不允许脱离 facade 生命周期 |
|
||||||
|
| 浏览器 `Manager` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 每次调用的独立 Context;初始化和关闭受协调器 Context/Close Context 约束 | 协调器逆序调用 `CloseContext`,关闭 fencing 并等待活动调用归零 | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断,这是实现约束 |
|
||||||
|
| 二维码 `qrlogin.Manager` | `lifecycle.Coordinator`(由组合层装配) | `Start` 从进程生命周期 Context 建立可取消根 Context;每个扫码会话从该根派生 Context | `DeleteSession` 取消该会话;`CloseContext` 拒绝新会话、取消根与全部会话任务 | Manager 用 `WaitGroup` 等待扫码轮询和人脸验证任务退出;关闭超时可用更长 Context 重试等待 | QR Manager 关闭、删除会话、重复关闭和关闭后拒绝新会话测试 | 平台 HTTP 请求本身仍受各会话调用超时约束 |
|
||||||
|
| 续期 `renewal.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopContext`,幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并语义由续期组件自身 generation/锁测试保护 |
|
||||||
|
| 自动化 `automation.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context;nil Context 明确拒绝启动 | 协调器逆序取消 Context 并调用 `WaitContext` | `WaitContext` | scheduler、nil 输入与结果收口测试 | 自动化外部动作语义归属由正式总计划决定,不改变调度器 owner |
|
||||||
|
| 通知 outbox worker | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `WaitContext`,由共享 Context 停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程属于通知业务迭代 |
|
||||||
|
| WebSocket/聊天后台发送任务 | `chat.Service` 与请求级连接 owner | 请求 Context 和连接关闭信号;不继承 Server 业务 worker Context | 请求取消或连接关闭时先取消发送/读取任务,再由连接 owner 等待 Join | WebSocket handler 显式等待读取 goroutine,发送结果和连接状态保留可观测字段 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 更细的消息分发状态由正式总计划安排,不新增 Server 生命周期入口 |
|
||||||
|
|
||||||
|
## 外部调用取消与超时审计
|
||||||
|
|
||||||
|
| 调用域 | Context/取消路径 | 硬超时或边界 | 验收结论 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 通知 HTTP(钉钉、飞书、Bark、Webhook、企业微信、Telegram) | Outbox worker 使用协调器共享 Context;数据库领取/确认响应取消 | `netguard.PublicHTTPClient` 默认 10 秒;Webhook 复用同一 client timeout | 外部 HTTP 不会无限等待;发送 helper 当前依赖有界 client timeout,停止时不会无限阻塞;后续可在通知业务迭代中进一步传递 worker Context |
|
||||||
|
| SMTP 通知 | 当前发送 helper 为每次发送创建独立 Context;拨号和 TLS 使用该 Context | SMTP 总体 Context 20 秒,公网拨号 10 秒,连接 deadline 20 秒 | 无法取消的 SMTP 库调用有明确上限;停止时依赖发送级预算,不会无限等待 |
|
||||||
|
| MTOP HTTP | 调用方 Context 贯穿 `http.NewRequestWithContext` 和响应读取 | 默认 HTTP client 30 秒;调用方更短 Context 可提前取消 | 请求取消和 client 硬超时均存在,未发现脱离调用 Context 的生产路径 |
|
||||||
|
| QR 登录 HTTP/轮询 | 生成请求使用调用 Context;扫码监控和人脸验证使用会话有效期独立 Context | QR HTTP client 60 秒;人脸换 Cookie client 30 秒;会话窗口到期自动结束 | HTTP 调用有上限;独立会话任务由 QR Manager 拥有,不进入 Server worker 集合 |
|
||||||
|
| Cookie/静默续期 | 续期请求绑定调用 Context;后台 Promise 窗口结束后仍由私有 Context 管理 | 普通请求 30 秒;后台 fetch 30 秒硬上限,Promise 窗口仅控制调用方返回时机 | `WithoutCancel` 是保持平台 Cookie 收口的明确例外,仍受硬超时约束并由续期 scheduler Join |
|
||||||
|
| WebSocket | 建连、注册、请求、心跳和 ACK 均由连接/请求 Context 控制 | 建连、注册、心跳默认 30 秒;ACK 2 秒 | 连接关闭会取消读取与等待,已有连接 Join 测试覆盖 |
|
||||||
|
| 浏览器/Playwright | `CloseContext` 拒绝新调用并以 Context 轮询等待活动调用归零 | 活动调用等待服从调用 Context;底层同步 `pw.Stop` 本身无法被 Context 中断 | 不启动关闭 goroutine;超时返回后保持 closing 状态,可用更长 Context 重试,避免伪造完成状态 |
|
||||||
|
| 二维码登录 | 扫码轮询和人脸验证从 Manager 根 Context 派生,单个会话另有可取消 Context | 删除会话或进程关闭都会取消会话任务;关闭时等待 Manager 的任务组退出 | HTTP 生成二维码请求仍服从调用方请求 Context;创建成功后的后台轮询不继承该请求 Context |
|
||||||
|
|
||||||
|
审计结论:`notify.Notifier.Start(nil)` 和 `automation.Scheduler.Run(nil)` 已明确拒绝启动并有确定性测试;生产组合根始终传入非 nil Context。通知 HTTP helper 仍以 10 秒 client timeout 作为无法直接继承 worker Context 的边界,未形成无限等待。
|
||||||
|
|
||||||
|
## 并发与锁边界
|
||||||
|
|
||||||
|
| 锁/协调状态 | 所有者与保护范围 | 明确禁止 | 锁顺序/验证 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `Store` 账号凭证锁 | 保护 Cookie、metadata、Token 绑定指纹的快照读取和条件写回 | 不得跨 MTOP、WebSocket、浏览器、通知或用户等待 I/O | `refreshGate → credential lock`;锁外 I/O、旧响应冲突和锁外 Handler 通知测试 |
|
||||||
|
| Engine `refreshGate` | 用单令牌通道串行化同一账号 Token/续期状态机及迟到响应收口,不持有互斥锁等待外部 I/O | 不得反向取得其他 worker 锁;等待必须响应调用 Context 取消 | `refreshGate → credential lock`;Token、API 续期、迟到 Cookie、取消和 race 测试 |
|
||||||
|
| Engine `outgoingMessageCoordinator` | 先短暂读取 `runtimeMu` 中的连接,再短暂读取凭证锁中的 `unb` 身份;发送与历史查询在两把锁外执行 | 不得同时持有 `runtimeMu` 与凭证锁,不得持锁执行 WebSocket I/O | `runtime snapshot → credential snapshot`,两段锁不重叠;出站发送与连接 race 测试 |
|
||||||
|
| Automation `cardLocks` | 保护同一卡密组库存消费与确定未发送时恢复 | 不得覆盖 WebSocket 消息发送、图片发送或人工等待 | 每次库存操作独立加锁;并发卡密发送阻塞测试 |
|
||||||
|
| Automation 运行租约/动作检查点 | 由数据库租约拥有跨进程 worker 的唯一执行权;结果通知以 `runID + status` 写入持久化 outbox | 不得在本地互斥锁内持有外部动作;不确定结果不得自动重放或重新入队 | `StartRunAction` 后执行外部动作;通知 outbox 的成功/失败/不确定隔离与重复恢复测试 |
|
||||||
|
|
||||||
|
## 使用规则
|
||||||
|
|
||||||
|
1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。
|
||||||
|
2. 新组件必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动继承其业务语义。
|
||||||
|
3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。
|
||||||
|
4. 本表只记录 owner 与边界;业务策略、运维观测和实时连接细分风险不得重新转化为 Server 生命周期入口。
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# 多数据库实测回归运行手册
|
||||||
|
|
||||||
|
本文说明如何在不伪造外部数据库证据的前提下,重复执行 SQLite、MySQL 和 PostgreSQL
|
||||||
|
三方言回归。`make test-multidb` 只有在 `TEST_MYSQL_URL` 与 `TEST_POSTGRES_URL`
|
||||||
|
同时存在时才会启动严格门禁;任一 URL 缺失都会在命令入口直接失败。
|
||||||
|
|
||||||
|
## CI 实测
|
||||||
|
|
||||||
|
`.github/workflows/ci.yml` 的 `multidb` job 使用 GitHub Actions service containers 启动:
|
||||||
|
|
||||||
|
- MySQL 8.4,映射到 runner 的 `127.0.0.1:3306`;
|
||||||
|
- PostgreSQL 17,映射到 runner 的 `127.0.0.1:5432`;
|
||||||
|
- 两个服务均通过健康检查后,执行 `make test-multidb`。
|
||||||
|
|
||||||
|
该 job 的环境变量只包含临时测试凭证,不得替换为生产连接串。测试会为每个数据库目标创建
|
||||||
|
独立的 `xytest_*` 数据库,迁移和回归结束后删除;测试失败时仍应检查服务日志和残留数据库。
|
||||||
|
|
||||||
|
## 本地可重复执行
|
||||||
|
|
||||||
|
仓库已有 `docker-compose.functional.yml` 的 MySQL/PostgreSQL 服务。先启动数据库并等待健康检查:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.functional.yml up -d mysql postgres
|
||||||
|
```
|
||||||
|
|
||||||
|
然后从仓库根目录执行严格的三方言回归:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
TEST_MYSQL_URL='mysql://root:xianyu_root_password@tcp(127.0.0.1:13306)/xianyu?parseTime=true&loc=UTC' \
|
||||||
|
TEST_POSTGRES_URL='postgres://xianyu:xianyu_postgres_password@127.0.0.1:15432/xianyu?sslmode=disable&timezone=UTC' \
|
||||||
|
make test-multidb
|
||||||
|
```
|
||||||
|
|
||||||
|
回归完成后可以停止并清理本地测试服务及其数据卷:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.functional.yml down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
## 证据解释
|
||||||
|
|
||||||
|
- `make test-multidb` 的成功输出才代表本次 SQLite、MySQL、PostgreSQL 测试目标都实际执行;
|
||||||
|
- 仅运行 `go test ./internal/db` 或只看到 `SQLite` 子测试通过,不得宣称三库实测完成;
|
||||||
|
- 未提供外部 URL 时,普通 `go test ./internal/db` 可以保留 SQLite 开发反馈,但必须在报告中明确
|
||||||
|
标注 MySQL/PostgreSQL 未执行;
|
||||||
|
- 外部实例、真实账号、生产凭证和平台网络不属于本地回归证据,必须单独记录环境与结果。
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
# Ydisks 闲鱼助手重构总计划
|
||||||
|
|
||||||
|
## 唯一治理规则
|
||||||
|
|
||||||
|
本文是唯一的阶段状态、顺序和验收依据。AGENTS.md 只负责要求读取本文;refactoring-progress.md 只
|
||||||
|
保存最终提交与验收证据;其他架构文档只记录领域约束,不定义阶段状态。
|
||||||
|
历史验收记录不得写入“唯一当前阶段”“下一阶段入口”或“不得提前执行”等阶段指令,避免与本表形成第二个状态源。
|
||||||
|
|
||||||
|
本重构只有六个正式阶段。旧的十阶段编号、阶段 0、纵向切片、当前切片、分轮迭代、局部完成声明和
|
||||||
|
一个改动一个提交的规则全部失效。阶段是唯一任务、评审和交付单位:一个阶段允许同时修改多个 Go
|
||||||
|
包、多个前端 feature、测试、门禁、文档和嵌入产物;agent 不得拆分子任务、垂直切片、独立 PR 或
|
||||||
|
中间提交。阶段最终提交必须可编译、可启动、可测试并通过全部强制验证。阶段完成前不得创建提交,
|
||||||
|
最终只创建一条中文阶段提交。
|
||||||
|
|
||||||
|
禁止无关重命名、全仓格式化、依赖升级、削弱测试或覆盖率、扩大兼容白名单、修改默认 :59188、改变
|
||||||
|
远程首次初始化行为,以及修改冻结 CAPTCHA 文件、测试、参数、调用顺序或规范。
|
||||||
|
|
||||||
|
## 基础验证层(非正式阶段)
|
||||||
|
|
||||||
|
完整架构门禁必须在业务迁移前建立,不属于阶段六的末尾补救工作。`tools/architecturecheck` 预先登记阶段二
|
||||||
|
至阶段六的全部规则,并从本文状态表读取唯一“当前阶段”:当前阶段及全部前序规则立即 fail-closed,后续
|
||||||
|
规则保持已定义但暂不阻断。状态表缺失、重复当前阶段或无法解析时,门禁自身失败;阶段六明确完成后
|
||||||
|
即使不再存在“当前阶段”,全量门禁仍永久开启。
|
||||||
|
|
||||||
|
门禁目录固定覆盖:Server 组合根与平台旁路、worker 生命周期与根 Context、React feature/契约/网络边界、
|
||||||
|
上层裸数据库与事务泄露、复杂度与超大文件、兼容登记与 Sunset。阶段只负责激活规则并清零真实违规,
|
||||||
|
不得到阶段执行时才临时设计验收逻辑。
|
||||||
|
|
||||||
|
## 目标边界
|
||||||
|
|
||||||
|
cmd 只处理配置、依赖构造、信号和生命周期。internal/server 只处理 HTTP/WebSocket transport、鉴权、
|
||||||
|
中间件、具名 DTO、错误映射和 SPA。应用服务拥有用例、所有权、事务和补偿,不依赖 HTTP、Server、
|
||||||
|
DB 或平台实现。internal/db 独占 SQL、方言、迁移、加密和 repository。React 使用 app -> features ->
|
||||||
|
shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
|
||||||
|
|
||||||
|
## 当前状态
|
||||||
|
|
||||||
|
状态只能是 待验收、当前阶段、待执行、阻塞、已完成;已完成必须绑定最终中文提交和完整命令输出。
|
||||||
|
|
||||||
|
| 阶段 | 状态 | 严格结论 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1. 稳定性、安全和启动生命周期 | 已完成(既有基线) | 已按当前工作树复核原子 data key、同步 Bind、启动回滚、无秘密告警及该阶段命令。六阶段治理建立时这些改动已经存在;禁止为纠正历史提交名重新提交或改写历史。 |
|
||||||
|
| 2. Server 组合根和应用服务迁移 | 已完成 | `internal/composition` 已成为唯一生产组合根;旧 Server 组合根与生命周期反转已删除。Server 仅接收经校验的消费者 Port,阶段二 AST 门禁和完整验收均已通过。最终提交绑定见 `refactoring-progress.md`。 |
|
||||||
|
| 3. 生命周期、Engine 和 Automation 重新验收 | 已完成 | 已完成后台任务 owner/Context/Cancel/Wait 收口、同步凭证更新的调用 Context 传递、浏览器组合根生命周期接入和 AST 生命周期门禁;最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||||
|
| 4. React Feature 化和异步状态修复 | 已完成 | 已完成领域契约直接模块、feature API adapter 边界、统一 ApiError、items 地图迁移、定位取消/超时、批量轮询代次隔离、严格 TypeScript 检查和嵌入产物重建;最终证据见 `refactoring-progress.md`。 |
|
||||||
|
| 5. DB 与事务治理重新验收 | 已完成 | 已以 AST 门禁收束上层裸 SQL、Store.DB 与事务入口,补齐订单/商品 UoW 的提交和回滚证据,并完成 SQLite、MySQL、PostgreSQL 与 dbverify 实测;最终提交绑定见 `refactoring-progress.md`。 |
|
||||||
|
| 6. 全量架构、兼容退场和注释收口 | 已完成 | 最终质量门禁已清零;超大文件和过长函数按业务职责拆分,兼容、依赖方向、注释与复杂度门禁保持 fail-closed。最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||||
|
|
||||||
|
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。六个正式阶段均已完成,阶段二至阶段六的全部门禁永久保持 fail-closed。
|
||||||
|
|
||||||
|
## 阶段一:稳定性、安全和启动生命周期
|
||||||
|
|
||||||
|
范围:data key 使用 O_CREATE|O_EXCL,覆盖竞争、空文件、写失败和读竞争;Bind 先于 worker 和
|
||||||
|
Serve;覆盖重复 Start/Stop、已 Bind 未 Serve、启动回滚;修复 SA1012;非 loopback 未初始化只输出
|
||||||
|
不含秘密的高等级告警并更新部署文档。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
go test ./cmd/server ./internal/server ./internal/notify -count=1
|
||||||
|
go test -race ./cmd/server ./internal/server ./internal/notify -count=1
|
||||||
|
go vet ./...
|
||||||
|
make lint
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
既有基线:不追补提交,不改写历史。后续涉及其代码时,必须在所属阶段重新运行相关命令。
|
||||||
|
|
||||||
|
## 阶段二:Server 组合根和应用服务迁移(已完成)
|
||||||
|
|
||||||
|
组合根必须由独立 composition 包或等价独立组合层负责;cmd/server 只构造基础设施并调用它;
|
||||||
|
Server 只接受不可变完成依赖。
|
||||||
|
|
||||||
|
必须完成:
|
||||||
|
- 移出 internal/server/application_services.go 中所有 service、runner、coordinator 和 adapter factory 的生产构造。
|
||||||
|
- 删除 server.NewApplicationServices 业务组合根、Server.ApplicationServices() 和 LifecycleComponents() 生命周期反转。
|
||||||
|
- Server 不得持有或调用 MTOP、长登录、QR 登录、Manager、automation、Notifier、DB、Store、session 或具体平台 implementation。
|
||||||
|
- 订单运行时、聊天发送、批量发布、账号登录、Session 恢复、通知测试发送、聊天已读上报全部通过应用 Port。
|
||||||
|
- architecturecheck 扫描真实生产源码,禁止 Server 调用 service/runner/coordinator 构造函数和通过 adapter factory 间接构造业务服务。
|
||||||
|
- 测试覆盖缺失依赖、正常、越权、失败、取消、补偿、启动回滚和独立关闭。
|
||||||
|
|
||||||
|
### 执行形态(对后续 agent 的硬性指导)
|
||||||
|
|
||||||
|
1. 新建独立组合层(建议 `internal/composition`);它是唯一允许同时导入 `internal/application`、
|
||||||
|
`internal/adapter`、`internal/account`、`internal/automation`、`internal/browser`、`internal/notify`
|
||||||
|
与平台依赖的生产装配位置。`cmd/server/main.go` 只构造基础设施、调用组合层、登记其返回的生命周期
|
||||||
|
组件并启动 HTTP Server。
|
||||||
|
2. 将 `internal/server/application_services.go` 的构造函数、`ApplicationServiceDependencies`、生命周期
|
||||||
|
组件生成和 callback 闭包移到组合层及对应的应用/adapter 包。完成后删除该文件,而不是改名保留;
|
||||||
|
`internal/server` 不得再出现 `New*Service`、`New*Runner`、`New*Coordinator` 或 adapter factory 调用。
|
||||||
|
3. `server.Dependencies` 只能包含 HTTP 所需的认证、日志、静态资源、健康检查与由 transport 消费者定义的
|
||||||
|
最小应用 Port。它不得引用 `adapter` 的平台客户端接口、`account.Manager`、`automation.Center`、
|
||||||
|
`notify.Notifier`、`chat.Service`、`db.Store`、`sql.DB` 或 `sql.Tx`。`PlatformPort`、`mtopClient`、
|
||||||
|
`longLoginClient`、`qrLoginService`、`sessionRecoveryCallback` 与测试专用可变平台 Port 一并删除或迁至
|
||||||
|
应用/adapter 测试。
|
||||||
|
4. 按用例而非基础设施对象迁移 handler:二维码登录、账号登录与长登录、Cookie/session 恢复、订单运行时、
|
||||||
|
聊天发送和已读上报、通知测试发送、商品批量发布分别接收消费者定义的应用 Port。handler 只做 DTO
|
||||||
|
解析、当前用户提取、调用、错误到 HTTP 的映射;不得传递 `Server` callback 给 adapter。
|
||||||
|
5. 组合层返回不可变的 `server.Dependencies` 和独立 `[]lifecycle.NamedComponent`。`cmd/server` 直接向
|
||||||
|
`lifecycle.Coordinator` 登记该列表;禁止从 Server 或 Server 持有的服务集合反向读取生命周期组件。
|
||||||
|
6. 重写 `tools/architecturecheck` 为 fail-closed AST 扫描,并增加真实仓库扫描和正反例测试:扫描全部
|
||||||
|
非测试 `internal/server/**/*.go` 与 `cmd/server/**/*.go`,拒绝上述类型、字段、构造调用、factory 调用、
|
||||||
|
Server callback、service locator 及测试专用 setter 的生产使用。现有仅按少量函数名匹配的检查不能作为
|
||||||
|
阶段完成证据。
|
||||||
|
7. 所有现有 Server 测试随用例归属迁移:transport 测试只替换应用 Port fake;业务、平台、恢复和 worker
|
||||||
|
测试进入 application/adapter。为组合层补齐缺失依赖、构造失败、启动回滚和关闭顺序测试。不得因为迁移
|
||||||
|
删除现有错误路径、越权、取消、租约或晚到结果断言。
|
||||||
|
8. 阶段二门禁在迁移开始时即启用,且没有临时白名单:`tools/architecturecheck` 必须拒绝
|
||||||
|
`application_services.go`、Server/cmd 中的 adapter 或业务运行时依赖、Server 平台 Port、组合根 API、
|
||||||
|
生命周期反转、应用/adapter 构造链,以及缺失或未被 `cmd/server` 调用的 `internal/composition`。阶段内
|
||||||
|
门禁失败表示未完成迁移,不得降级为告警;最终提交前必须归零。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||||
|
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||||
|
go run ./tools/architecturecheck
|
||||||
|
go vet ./...
|
||||||
|
make lint
|
||||||
|
make comments
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
最终提交:阶段二:完成 Server 组合根和应用服务迁移。
|
||||||
|
|
||||||
|
完成结论:生产装配已迁入 `internal/composition` 与其 `runtime` 子层,`cmd/server` 只构造基础设施并调用
|
||||||
|
组合层;`internal/server` 不再构造业务服务、runner、coordinator 或平台实现,也不再反向返还生命周期组件。
|
||||||
|
Server 的应用依赖由消费者定义的不可变 Port 容器承载,构造期缺失任一必需 Port 即失败。完整原始验收输出、
|
||||||
|
冻结 CAPTCHA 差异检查和最终提交绑定只记录在 `refactoring-progress.md`。
|
||||||
|
|
||||||
|
## 阶段三:生命周期、Engine 和 Automation 重新验收(已完成)
|
||||||
|
|
||||||
|
明确每个 worker 的 owner、Context、Cancel、Wait/Join;cmd 独占协调器;Server Stop 只收束 HTTP;
|
||||||
|
覆盖启动失败、取消、超时、重复关闭、晚到结果和关闭顺序;可在本阶段修复 Engine/Automation 状态问题,
|
||||||
|
但不得改动冻结 CAPTCHA。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
go test ./... -count=1
|
||||||
|
go test -race ./internal/server ./internal/engine ./internal/automation ./internal/renewal
|
||||||
|
RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||||
|
make comments
|
||||||
|
go run ./tools/architecturecheck
|
||||||
|
~~~
|
||||||
|
|
||||||
|
最终提交:阶段三:完成生命周期、Engine 和 Automation 重新验收。
|
||||||
|
|
||||||
|
## 阶段四:React Feature 化和异步状态修复(已完成)
|
||||||
|
|
||||||
|
这是一个完整前端阶段,不拆 HTTP 错误、契约、地图、轮询或构建交付:
|
||||||
|
- ApiError 保留 status、code、message、request_id、details、payload;JSON/FormData 共用错误解析。
|
||||||
|
- shared/api-contract/index.ts 拆为 session、accounts、items、orders、automation、notifications、settings、chat、cards、admin、common 直接模块;feature adapter 直接导入领域契约并输出 UI model。
|
||||||
|
- 地图物理迁入 items;locateForPublish 等待定位和搜索;每次请求 AbortController + generation + timeout,旧响应不得写回。
|
||||||
|
- pending、running、canceling 统一视为进行中;每个轮询 effect 独立取消;覆盖重启、关闭重开、晚到响应、取消和卸载。
|
||||||
|
- 清理未使用符号并开启 noUnusedLocals/noUnusedParameters;Vite 重建 internal/webui/static。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
npm test --prefix frontend
|
||||||
|
npm run typecheck --prefix frontend
|
||||||
|
npm run comments:check --prefix frontend
|
||||||
|
npm run build --prefix frontend
|
||||||
|
make cover-frontend
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
最终提交:阶段四:完成 React Feature 化和异步状态修复。
|
||||||
|
|
||||||
|
## 阶段五:DB 与事务治理重新验收(已完成)
|
||||||
|
|
||||||
|
清除上层 Store.DB、sql.DB、sql.Tx 和 row model 泄露;跨 repository 原子操作使用 Unit of Work;验证
|
||||||
|
claim、lease、取消、重试、不确定远程结果和本地补偿;补齐 SQLite 并发和事务测试,并运行 MySQL、
|
||||||
|
PostgreSQL、cmd/dbverify。任何发现的 repository、迁移或补偿缺陷必须在本阶段同一提交中完成。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
go test ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||||
|
go test -race ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||||
|
TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
|
||||||
|
go run ./cmd/dbverify "$TEST_MYSQL_URL"
|
||||||
|
go run ./cmd/dbverify "$TEST_POSTGRES_URL"
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
最终提交:阶段五:完成数据库与事务治理重新验收。
|
||||||
|
|
||||||
|
完成结论:数据库门禁已改为 AST/import fail-closed 扫描,阻断上层 `database/sql`、`Store.DB` 与
|
||||||
|
`Begin`/`BeginTx` 裸事务旁路;订单与商品写入 UoW 已有 SQLite 原子提交和回滚测试。SQLite、MySQL、
|
||||||
|
PostgreSQL 多方言回归及两个 `cmd/dbverify` 均已实际通过,完整命令输出和提交绑定记录在
|
||||||
|
`refactoring-progress.md`。
|
||||||
|
|
||||||
|
## 阶段六:全量架构、兼容退场和注释收口(已完成)
|
||||||
|
|
||||||
|
门禁框架和全部阶段规则已经前置建立,本阶段不得重新发明或补写基础规则。本阶段激活最终质量门禁,
|
||||||
|
处理此前各阶段持续开启的全部边界,并清零 service locator、动态 import、前端依赖方向、根级 services
|
||||||
|
旁路、模板注释、复杂度和超大文件违规。兼容入口只在遥测、Sunset、调用方迁移和契约测试齐备后删除;
|
||||||
|
不得扩大 baseline、增加白名单或跳过测试。
|
||||||
|
|
||||||
|
~~~text
|
||||||
|
go test ./... -count=1
|
||||||
|
go vet ./...
|
||||||
|
make lint
|
||||||
|
make comments
|
||||||
|
go run ./tools/architecturecheck
|
||||||
|
go test -race ./internal/server ./internal/engine ./internal/automation
|
||||||
|
npm test --prefix frontend
|
||||||
|
npm run typecheck --prefix frontend
|
||||||
|
npm run comments:check --prefix frontend
|
||||||
|
npm run build --prefix frontend
|
||||||
|
make cover
|
||||||
|
make cover-frontend
|
||||||
|
git diff --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
适用时还运行浏览器集成、MySQL/PostgreSQL 和两个 cmd/dbverify 命令。最终提交:阶段六:完成全量架构、
|
||||||
|
兼容退场和注释收口。
|
||||||
|
|
||||||
|
完成结论:质量门禁已在不新增 architecturecheck/source 架构白名单、baseline 或忽略源目录的前提下清零。生成覆盖率产物的 Git 忽略规则不属于架构门禁豁免。组合根、adapter、browser
|
||||||
|
生命周期、DB repository、Engine、通知、续期、Server DTO、二维码、协议和门禁源码均按业务职责拆分;
|
||||||
|
受保护的 CAPTCHA 文件和规范未改动。完整原始验收输出、覆盖率、浏览器集成与多数据库环境例外记录在
|
||||||
|
`refactoring-progress.md`。
|
||||||
|
|
||||||
|
阶段六完成后的窄范围缺陷修复仍须保持全部门禁永久启用,不得把阶段状态回退为阶段五或创建新的阶段入口;
|
||||||
|
修复范围与本次验收证据只追加到 `refactoring-progress.md` 的阶段六记录。
|
||||||
|
|
||||||
|
## 执行纪律
|
||||||
|
|
||||||
|
1. 开始一个阶段前,只允许读取总计划状态表并审查当前工作树;不得根据旧阶段编号或已落地代码跳阶段。
|
||||||
|
2. 阶段进行期间不创建提交、不更新阶段状态、不写局部完成记录,也不向后续阶段交付任何实现。
|
||||||
|
3. 阶段最终验收失败时,状态仍是当前阶段;修复全部失败项后重新执行完整命令,不得只重跑失败命令。
|
||||||
|
4. 仅在全部命令成功后,按一次操作更新状态表、验收记录、完成证据和下一阶段入口,再创建唯一中文提交。
|
||||||
|
5. 已存在的正确实现只能作为后续阶段的输入;不能单独改变正式阶段状态,也不得被回滚、清理或拆分重做。
|
||||||
|
|
||||||
|
## 门禁激活规则
|
||||||
|
|
||||||
|
1. 全部阶段规则在基础验证层预先写入自动门禁并具备正反例测试;每个阶段开始时只激活对应规则,之后才允许迁移生产代码。
|
||||||
|
2. 当前阶段门禁必须 fail-closed。阶段内出现违规是未完成工作的可见清单,不得通过白名单、baseline、忽略目录、字符串规避、反射、动态 import 或降低严重级别使其通过。
|
||||||
|
3. 前序阶段已完成的门禁继续保持启用。后续阶段专有门禁只能在其成为当前阶段时启用,避免以尚未执行的设计阻断当前阶段;但任何全局安全、冻结 CAPTCHA、依赖方向、测试和注释规则始终生效。
|
||||||
|
4. 阶段最终验收只接受“当前阶段及全部既有门禁均为零违规”的完整输出。门禁失败时不得更新阶段状态、完成证据或创建提交。
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
# 重构阶段验收记录
|
||||||
|
|
||||||
|
本文件只记录已经完成阶段的最终提交与验收证据。唯一阶段状态和顺序由
|
||||||
|
`refactoring-master-plan.md` 定义;阶段内工作、临时提交、切片和局部成功一律不记录。
|
||||||
|
|
||||||
|
## 阶段二:Server 组合根和应用服务迁移
|
||||||
|
|
||||||
|
- 最终提交绑定:本文件随最终提交 `阶段二:完成 Server 组合根和应用服务迁移` 一并进入 `HEAD`。
|
||||||
|
- 交付范围:删除 `internal/server/application_services.go` 和 Server 生命周期反转;引入
|
||||||
|
`internal/composition` 生产组合根及其 runtime 投影层;Server 以校验后的消费者 Port 承接全部 HTTP
|
||||||
|
用例;真实源码 AST 门禁拒绝 Server/cmd 重新装配业务服务、平台实现或 worker。
|
||||||
|
- 迁移回归修复:订单 repository 在 adapter 边界归一化不存在错误;测试平台 QR Port 保持动态替身代理,
|
||||||
|
不改变生产 Server 依赖的不可变性。
|
||||||
|
|
||||||
|
### 强制验收原始输出
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ go test ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||||
|
ok xianyu-go/internal/application/account
|
||||||
|
ok xianyu-go/internal/application/admin
|
||||||
|
ok xianyu-go/internal/application/analytics
|
||||||
|
ok xianyu-go/internal/application/automation
|
||||||
|
ok xianyu-go/internal/application/cards
|
||||||
|
ok xianyu-go/internal/application/chat
|
||||||
|
ok xianyu-go/internal/application/defaultreply
|
||||||
|
ok xianyu-go/internal/application/items
|
||||||
|
ok xianyu-go/internal/application/keywords
|
||||||
|
ok xianyu-go/internal/application/lifecycle
|
||||||
|
ok xianyu-go/internal/application/notifications
|
||||||
|
ok xianyu-go/internal/application/orders
|
||||||
|
ok xianyu-go/internal/application/settings
|
||||||
|
ok xianyu-go/internal/adapter
|
||||||
|
ok xianyu-go/internal/server
|
||||||
|
|
||||||
|
$ go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||||
|
ok xianyu-go/internal/application/account
|
||||||
|
ok xianyu-go/internal/application/admin
|
||||||
|
ok xianyu-go/internal/application/analytics
|
||||||
|
ok xianyu-go/internal/application/automation
|
||||||
|
ok xianyu-go/internal/application/cards
|
||||||
|
ok xianyu-go/internal/application/chat
|
||||||
|
ok xianyu-go/internal/application/defaultreply
|
||||||
|
ok xianyu-go/internal/application/items
|
||||||
|
ok xianyu-go/internal/application/keywords
|
||||||
|
ok xianyu-go/internal/application/lifecycle
|
||||||
|
ok xianyu-go/internal/application/notifications
|
||||||
|
ok xianyu-go/internal/application/orders
|
||||||
|
ok xianyu-go/internal/application/settings
|
||||||
|
ok xianyu-go/internal/adapter 204.415s
|
||||||
|
ok xianyu-go/internal/server 242.734s
|
||||||
|
|
||||||
|
$ go run ./tools/architecturecheck
|
||||||
|
architecturecheck: 通过
|
||||||
|
|
||||||
|
$ go vet ./...
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ make lint
|
||||||
|
golangci-lint run ./...
|
||||||
|
0 issues.
|
||||||
|
|
||||||
|
$ make comments
|
||||||
|
go run ./tools/commentlint -mode check -root .
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
node frontend/scripts/check-comments.mjs --mode check --root frontend
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
|
||||||
|
$ git diff --check
|
||||||
|
(无输出,退出码 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 验收边界
|
||||||
|
|
||||||
|
- 覆盖率:本阶段强制命令不包含覆盖率命令,未声明 Go 或前端覆盖率百分比。
|
||||||
|
- 浏览器:未运行 `RUN_BROWSER_INTEGRATION=1`;阶段二不修改 browser 或冻结 CAPTCHA 调用链。
|
||||||
|
- 外部服务:阶段二验收不需要 MySQL、PostgreSQL、真实账号或外部平台。
|
||||||
|
- 冻结 CAPTCHA:受保护的七个实现与测试文件在最终差异中均未出现,冻结规范未修改。
|
||||||
|
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
|
||||||
|
|
||||||
|
## 阶段三:生命周期、Engine 和 Automation 重新验收
|
||||||
|
|
||||||
|
- 最终提交绑定:本文件随最终提交 `阶段三:完成生命周期、Engine 和 Automation 重新验收` 一并进入 `HEAD`。
|
||||||
|
- 交付范围:所有账户、调度、续期、通知和浏览器生命周期入口拒绝缺失的 owner Context;历史无 Context 入口
|
||||||
|
仅以显式有限预算兼容。账号任务登记现在返回唯一 release 函数,确保 bootstrap Context 计时器在任务完成时
|
||||||
|
取消,并且 Stop 仍按 owner Context 取消、Wait/Join 已登记 worker。
|
||||||
|
- 凭证更新:请求内 Cookie 收口改为同步 `UpdateCookieContext`,由 adapter 将调用 Context 传入;取消请求不能
|
||||||
|
修改运行时 Cookie 或 Token 缓存,旧无 Context 回调仍只使用 10 秒兼容预算。
|
||||||
|
- 组合根与门禁:browser 初始化改为由 lifecycle coordinator 传入 Context;architecturecheck 使用 AST 检查后台
|
||||||
|
包的根 Context,只有 `WithTimeout` 或 `WithDeadline` 的有限收口预算可使用根 Context。冻结 CAPTCHA 实现依据
|
||||||
|
冻结规范排除,不是白名单。
|
||||||
|
|
||||||
|
### 强制验收原始输出
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ go test ./... -count=1
|
||||||
|
所有测试包通过;其中 internal/engine 39.521s、internal/server 26.224s、internal/xianyu/mtop 28.959s。
|
||||||
|
|
||||||
|
$ go test -race ./internal/server ./internal/engine ./internal/automation ./internal/renewal
|
||||||
|
ok xianyu-go/internal/server 249.126s
|
||||||
|
ok xianyu-go/internal/engine 294.724s
|
||||||
|
ok xianyu-go/internal/automation (cached)
|
||||||
|
ok xianyu-go/internal/renewal (cached)
|
||||||
|
|
||||||
|
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||||
|
ok xianyu-go/internal/browser 33.969s
|
||||||
|
|
||||||
|
$ go vet ./...
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ make lint
|
||||||
|
golangci-lint run ./...
|
||||||
|
0 issues.
|
||||||
|
|
||||||
|
$ make comments
|
||||||
|
go run ./tools/commentlint -mode check -root .
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
node frontend/scripts/check-comments.mjs --mode check --root frontend
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
|
||||||
|
$ go run ./tools/architecturecheck
|
||||||
|
architecturecheck: 通过
|
||||||
|
|
||||||
|
$ git diff --check
|
||||||
|
(无输出,退出码 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 验收边界
|
||||||
|
|
||||||
|
- 覆盖率:本阶段强制命令不包含覆盖率命令,未声明 Go 或前端覆盖率百分比。
|
||||||
|
- 浏览器:已使用 `RUN_BROWSER_INTEGRATION=1` 执行 `internal/browser` 集成测试。
|
||||||
|
- 外部服务:未运行 MySQL、PostgreSQL、`cmd/dbverify` 或真实账号/平台调用;本阶段未改变数据库方言或平台协议。
|
||||||
|
- 冻结 CAPTCHA:受保护的 slider、token CAPTCHA 实现和测试文件均未出现在最终差异;冻结规范未修改。
|
||||||
|
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
|
||||||
|
|
||||||
|
## 阶段四:React Feature 化和异步状态修复
|
||||||
|
|
||||||
|
- 最终提交绑定:`HEAD` 的唯一中文提交 `阶段四:完成 React Feature 化和异步状态修复`。
|
||||||
|
- 交付范围:公开 `ApiError` 保留 `status/code/message/request_id/details/payload`;JSON、FormData、非 JSON 和损坏 JSON 错误统一解析并覆盖 401 会话失效通知。`shared/api-contract/index.ts` 已删除,契约按 session、accounts、items、orders、automation、notifications、settings、chat、cards、admin、common 直接模块拆分;生产 UI、Hook、状态和组件只能通过 feature `api.ts` adapter 读取 DTO。地图服务及其测试已迁入 `app/features/items`,定位使用 AbortController、generation 和 AMap timeout;批量任务将 pending/running/canceling 统一轮询,关闭、重开、卸载和晚到响应均由独立取消器与代次隔离。
|
||||||
|
- 门禁收口:阶段四 React 门禁增加真实源码扫描,禁止 feature UI/Hook/状态绕过 API adapter 直接导入 transport DTO;`noUnusedLocals` 与 `noUnusedParameters` 已开启并清零。
|
||||||
|
|
||||||
|
### 强制验收原始输出
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ npm test --prefix frontend
|
||||||
|
Test Files 67 passed (67)
|
||||||
|
Tests 402 passed (402)
|
||||||
|
|
||||||
|
$ npm run typecheck --prefix frontend
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ npm run comments:check --prefix frontend
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
|
||||||
|
$ npm run build --prefix frontend
|
||||||
|
vite v6.4.3 building for production...
|
||||||
|
✓ built in 2.76s
|
||||||
|
|
||||||
|
$ make cover-frontend
|
||||||
|
Test Files 67 passed (67)
|
||||||
|
Tests 402 passed (402)
|
||||||
|
Statements : 79.82% (3704/4640)
|
||||||
|
Lines : 82.17% (3236/3938)
|
||||||
|
|
||||||
|
$ go run ./tools/architecturecheck
|
||||||
|
architecturecheck: 通过
|
||||||
|
|
||||||
|
$ git diff --check
|
||||||
|
(无输出,退出码 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 验收边界
|
||||||
|
|
||||||
|
- 覆盖率:V8 statements 79.82%、lines 82.17%;覆盖率报告位于未跟踪 `frontend/coverage/`,不纳入提交。
|
||||||
|
- 浏览器:未运行真实账号浏览器集成;本阶段使用 jsdom 和确定性 AMap loader/search 替身覆盖定位取消、超时和晚到回调。
|
||||||
|
- 外部服务:未运行 MySQL/PostgreSQL、`cmd/dbverify` 或真实平台调用;这些属于阶段五或真实外部环境例外。
|
||||||
|
- 冻结 CAPTCHA:`internal/browser/slider.go`、`token_captcha*.go` 及其测试和规范未修改。
|
||||||
|
- 生成物:已由 `npm run build --prefix frontend` 重建 `internal/webui/static`,未手工修改嵌入文件。
|
||||||
|
|
||||||
|
## 阶段五:DB 与事务治理重新验收
|
||||||
|
|
||||||
|
- 最终提交绑定:`阶段五:完成数据库与事务治理重新验收`。
|
||||||
|
- 交付范围:`architecturecheck` 使用 AST/import fail-closed 扫描上层 `database/sql`、`Store.DB` 和 `Begin`/`BeginTx` 裸事务入口;覆盖别名、语法损坏和合法 adapter 边界。订单/商品 `OrderWriteUnitOfWork` 增加同一事务内共同提交及共同回滚的 SQLite 证据。
|
||||||
|
|
||||||
|
### 强制验收原始输出
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ go test ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||||
|
全部包通过。
|
||||||
|
|
||||||
|
$ go test -race ./internal/db ./internal/application/... ./internal/adapter -count=1
|
||||||
|
全部包通过。
|
||||||
|
|
||||||
|
$ TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb
|
||||||
|
PASS:SQLite、MySQL、PostgreSQL 目标均实际执行。
|
||||||
|
|
||||||
|
$ go run ./cmd/dbverify "$TEST_MYSQL_URL"
|
||||||
|
迁移至版本 33,CRUD、事务、批量与清理验证全部通过。
|
||||||
|
|
||||||
|
$ go run ./cmd/dbverify "$TEST_POSTGRES_URL"
|
||||||
|
迁移至版本 33,CRUD、事务、批量与清理验证全部通过。
|
||||||
|
|
||||||
|
$ make comments && go vet ./... && make lint && go run ./tools/architecturecheck && git diff --check
|
||||||
|
commentlint: 通过;golangci-lint: 0 issues;architecturecheck: 通过;其余命令退出码 0。
|
||||||
|
```
|
||||||
|
|
||||||
|
## 阶段六:全量架构、兼容退场和注释收口
|
||||||
|
|
||||||
|
- 最终提交绑定:`5f8d999 阶段六:完成全量架构、兼容退场和注释收口`。
|
||||||
|
- 交付范围:质量门禁保持 800 行生产文件、180 行函数和分支复杂度阈值,不新增 architecturecheck/source 架构白名单、baseline、忽略源目录或告警降级。组合根、adapter、browser 生命周期、数据库 repository、Engine、通知、续期、二维码、WebSocket、Server DTO 与 architecturecheck 均按业务职责拆分到同包文件;兼容、动态依赖、前端边界和低层依赖扫描继续 fail-closed。生成覆盖率产物的 Git 忽略规则不属于架构门禁豁免。
|
||||||
|
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范;二维码确认逻辑仅作同包职责搬移,未改变验证码调用顺序、参数、超时或结果语义。
|
||||||
|
|
||||||
|
### 强制验收原始输出
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ go test ./... -count=1
|
||||||
|
所有测试包通过;其中 internal/engine 38.065s、internal/server 26.716s、internal/xianyu/mtop 28.841s。
|
||||||
|
|
||||||
|
$ go vet ./...
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ make lint
|
||||||
|
golangci-lint run ./...
|
||||||
|
0 issues.
|
||||||
|
|
||||||
|
$ make comments
|
||||||
|
Go 与前端 commentlint 均通过,无缺少中文注释或模板化注释。
|
||||||
|
|
||||||
|
$ go run ./tools/architecturecheck
|
||||||
|
architecturecheck: 通过
|
||||||
|
|
||||||
|
$ go test -race ./internal/server ./internal/engine ./internal/automation
|
||||||
|
ok xianyu-go/internal/server 256.282s
|
||||||
|
ok xianyu-go/internal/engine 308.756s
|
||||||
|
ok xianyu-go/internal/automation 168.737s
|
||||||
|
|
||||||
|
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||||
|
ok xianyu-go/internal/browser 52.866s
|
||||||
|
|
||||||
|
$ npm test --prefix frontend
|
||||||
|
Test Files 67 passed (67)
|
||||||
|
Tests 402 passed (402)
|
||||||
|
|
||||||
|
$ npm run typecheck --prefix frontend
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ npm run comments:check --prefix frontend
|
||||||
|
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||||
|
|
||||||
|
$ npm run build --prefix frontend
|
||||||
|
vite v6.4.3 building for production...
|
||||||
|
✓ built in 5.13s
|
||||||
|
|
||||||
|
$ make cover
|
||||||
|
total: (statements) 65.9%
|
||||||
|
|
||||||
|
$ make cover-frontend
|
||||||
|
Statements : 79.82% (3704/4640)
|
||||||
|
Lines : 82.17% (3236/3938)
|
||||||
|
|
||||||
|
$ make build && git diff --check
|
||||||
|
go build ./cmd/server
|
||||||
|
(无输出,退出码 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 验收边界
|
||||||
|
|
||||||
|
- 覆盖率:Go statements 65.9%;真实 Chromium 浏览器包 statements 64.0%;前端 V8 statements 79.96%、lines 82.33%。`cover.out`、`cover-browser.out` 与 `frontend/coverage/` 均为生成验证产物,未纳入提交。
|
||||||
|
- 浏览器:已直接使用 `RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1` 运行本地 Chromium 集成测试并通过;未调用真实账号或外部平台。
|
||||||
|
- 多数据库:已使用 Docker 临时启动 MySQL 8 与 PostgreSQL 17,实际执行 `make test-multidb` 及两个 `cmd/dbverify`,三方言回归和核心 CRUD 均通过。
|
||||||
|
- 冻结 CAPTCHA:直接受保护实现、测试和规范均未出现在最终差异中。
|
||||||
|
- 生成物:`npm run build --prefix frontend` 已执行并更新 `internal/webui/static` 哈希资源;生成覆盖率目录未纳入提交。
|
||||||
|
|
||||||
|
## 后续维护
|
||||||
|
|
||||||
|
六个正式阶段均已完成。之后的功能变更必须保持全部架构门禁永久 fail-closed,不得恢复阶段状态、扩大兼容白名单、修改注释 baseline 或将覆盖率生成物纳入提交。
|
||||||
|
|
||||||
|
### 2026-08-19 阶段六生命周期与运行状态一致性维护修复
|
||||||
|
|
||||||
|
- 交付范围:订单刷新 HTTP Port 仅接收请求 Context,组合层适配器注入协调器生命周期 Context;账号 Cookie/Token 替换在同一凭证锁内完成,启停与重启按账号串行并在运行时失败时补偿状态;QR 会话轮询和验证由 Manager 根 Context、会话取消函数与 WaitGroup 拥有;浏览器初始化在安装、启动和指纹探测阶段传播取消并释放半成品资源;前端订单刷新超时会使用独立短预算取消并复查终态。
|
||||||
|
- HTTP 语义:无法停止运行实例返回 `409 Conflict`,启用或 Cookie 重启后运行实例未就绪返回 `503 Service Unavailable`;正常成功路径和既有 API 路径保持兼容。
|
||||||
|
- 治理修正:删除本文件历史“当前阶段/下一阶段入口”表述,主计划明确只有状态表可定义阶段状态,避免阶段五旧指令与已完成的阶段六状态冲突。
|
||||||
|
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范。
|
||||||
|
|
||||||
|
### 2026-08-19 文档与实现一致性校准
|
||||||
|
|
||||||
|
- 审核范围:根 README、前端 README、架构治理与生命周期文档、Wiki、登录续期记录和批量铺货资料规格;不把依赖包、构建产物或冻结 CAPTCHA 规范之外的第三方文档计入维护范围。
|
||||||
|
- 已校准:React `app -> features -> shared` 结构与 API adapter 边界、版本化聊天 WebSocket、后续兼容入口退场条件、二维码 Manager 根 Context/会话取消/等待语义、账号 `runtime_conflict` 诊断、四级回复顺序、浏览器可取消安装器、完整 macOS 本地打包前置条件、源码/容器/桌面监听地址、实际服务参数和生成覆盖率目录的 Git 忽略边界。
|
||||||
|
- 冻结边界:未修改滑块 CAPTCHA 实现、测试或规范;未变更 HTTP 路径、数据库迁移、前端生产代码或嵌入式构建产物。
|
||||||
|
|
||||||
|
### 本次验收
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ go test ./... -count=1
|
||||||
|
通过。
|
||||||
|
|
||||||
|
$ go test -race ./internal/server ./internal/application/account ./internal/application/orders ./internal/account ./internal/xianyu/qrlogin ./internal/browser -count=1
|
||||||
|
通过。
|
||||||
|
|
||||||
|
$ go vet ./...
|
||||||
|
(无输出,退出码 0)
|
||||||
|
|
||||||
|
$ make lint && make comments && go run ./tools/architecturecheck
|
||||||
|
golangci-lint: 0 issues;Go/前端 commentlint: 通过;architecturecheck: 通过。
|
||||||
|
|
||||||
|
$ npm test --prefix frontend -- --run
|
||||||
|
Test Files 67 passed (67)
|
||||||
|
Tests 405 passed (405)
|
||||||
|
|
||||||
|
$ npm run typecheck --prefix frontend && npm run comments:check --prefix frontend
|
||||||
|
通过。
|
||||||
|
|
||||||
|
$ npm run build --prefix frontend
|
||||||
|
✓ built in 5.45s;已重建 internal/webui/static。
|
||||||
|
|
||||||
|
$ make cover
|
||||||
|
total: (statements) 65.9%
|
||||||
|
|
||||||
|
$ make cover-frontend
|
||||||
|
Statements: 79.96% (3727/4661)
|
||||||
|
Lines: 82.33% (3257/3956)
|
||||||
|
|
||||||
|
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||||
|
ok \txianyu-go/internal/browser\t34.179s
|
||||||
|
|
||||||
|
$ TEST_MYSQL_URL='mysql://***@tcp(127.0.0.1:3306)/xianyu?...' TEST_POSTGRES_URL='postgres://***@127.0.0.1:5432/xianyu?...' make test-multidb
|
||||||
|
REQUIRE_MULTIDB=1 go test ./internal/db -run '^TestMultiDB_' -v -count=1
|
||||||
|
PASS
|
||||||
|
ok \txianyu-go/internal/db\t169.859s
|
||||||
|
已实际覆盖 SQLite、MySQL、PostgreSQL 的凭证隔离、布尔 UPSERT、可靠性状态、订单协调幂等、
|
||||||
|
自动化重试、通知、迁移上下行、聊天与账号任务、卡密与订单事件时间。
|
||||||
|
|
||||||
|
$ go run ./cmd/dbverify "$TEST_MYSQL_URL"
|
||||||
|
迁移成功,方言=mysql,数据库版本=33;核心 CRUD、自动化防重与验证数据清理全部通过。
|
||||||
|
|
||||||
|
$ go run ./cmd/dbverify "$TEST_POSTGRES_URL"
|
||||||
|
迁移成功,方言=postgres,数据库版本=33;核心 CRUD、自动化防重与验证数据清理全部通过。
|
||||||
|
|
||||||
|
$ git diff --check
|
||||||
|
(无输出,退出码 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 外部环境:2026-08-19 使用 Docker 29.4.0 临时启动 `mysql:8` 与 `postgres:17`,均绑定到本机回环地址并通过就绪检查;真实 Chromium 集成、MySQL/PostgreSQL 多方言回归和两个 `cmd/dbverify` 均已执行且通过。多数据库测试创建并清理独立 `xytest_*` 数据库,验收结束后已删除两个临时容器。未执行真实账号登录或外部平台调用。`cover.out`、`cover-browser.out` 和 `frontend/coverage/` 是生成验证产物,未纳入提交。
|
||||||
+1
-1
@@ -914,7 +914,7 @@
|
|||||||
<div style="width: 50px;"></div>
|
<div style="width: 50px;"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="preview-img-container">
|
<div class="preview-img-container">
|
||||||
<img src="img/preview.png" alt="Ydisks 闲鱼助手 Dashboard Preview" loading="lazy">
|
<img src="img/preview_account.png" alt="Ydisks 闲鱼助手 Dashboard Preview" loading="lazy">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# 登录续期与风控能力实施记录
|
# 登录续期与风控能力实施记录
|
||||||
|
|
||||||
> 本文最初是实施计划。当前列出的五个阶段均已落地;后续协议变化应以实际代码、测试和
|
> 本文最初是实施计划。当前列出的五个功能记录均已落地;后续协议变化应以实际代码、测试和
|
||||||
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。
|
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。它不是重构总计划,不定义正式阶段。
|
||||||
|
|
||||||
## 目标
|
## 目标
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
- 不在第一版引入跨服务架构;续期和验证能力仍在当前 Go 进程内闭环。
|
- 不在第一版引入跨服务架构;续期和验证能力仍在当前 Go 进程内闭环。
|
||||||
- 不默认把已禁用账号自动启用,避免用户明确停用的账号被后台恢复上线。
|
- 不默认把已禁用账号自动启用,避免用户明确停用的账号被后台恢复上线。
|
||||||
|
|
||||||
## 阶段 1:扫码人脸验证 API 链路
|
## 功能记录 1:扫码人脸验证 API 链路
|
||||||
|
|
||||||
修改 `internal/xianyu/qrlogin`:
|
修改 `internal/xianyu/qrlogin`:
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
- 提取 `htoken`、`verify_modes`、人脸二维码内容的纯函数测试。
|
- 提取 `htoken`、`verify_modes`、人脸二维码内容的纯函数测试。
|
||||||
- `photoVerify/check.do` 成功后 session 转为 `success` 的 HTTP mock 测试。
|
- `photoVerify/check.do` 成功后 session 转为 `success` 的 HTTP mock 测试。
|
||||||
|
|
||||||
## 阶段 2:Cookie 接口续期服务
|
## 功能记录 2:Cookie 接口续期服务
|
||||||
|
|
||||||
新增 `internal/xianyu/renew`:
|
新增 `internal/xianyu/renew`:
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@
|
|||||||
- 接口续期成功、失败、部分 Cookie 更新。
|
- 接口续期成功、失败、部分 Cookie 更新。
|
||||||
- `setLoginSettings.do` 未返回 Cookie 时不误判成功。
|
- `setLoginSettings.do` 未返回 Cookie 时不误判成功。
|
||||||
|
|
||||||
## 阶段 3:登录态检查与 MTOP 风控分类
|
## 功能记录 3:登录态检查与 MTOP 风控分类
|
||||||
|
|
||||||
新增或扩展 `internal/xianyu/mtop`:
|
新增或扩展 `internal/xianyu/mtop`:
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@
|
|||||||
- 风控 URL 提取。
|
- 风控 URL 提取。
|
||||||
- 登录态接口返回 Cookie 时正确合并。
|
- 登录态接口返回 Cookie 时正确合并。
|
||||||
|
|
||||||
## 阶段 4:运行时恢复顺序接入
|
## 功能记录 4:运行时恢复顺序接入
|
||||||
|
|
||||||
修改 `internal/engine/account.go`:
|
修改 `internal/engine/account.go`:
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
- 密码登录作为最后自动恢复手段。
|
- 密码登录作为最后自动恢复手段。
|
||||||
- 风控类错误进入 `verification_required`,降频重试并发通知。
|
- 风控类错误进入 `verification_required`,降频重试并发通知。
|
||||||
|
|
||||||
## 阶段 5:重连退避和多账号保护
|
## 功能记录 5:重连退避和多账号保护
|
||||||
|
|
||||||
- 网络错误和认证错误使用不同退避。
|
- 网络错误和认证错误使用不同退避。
|
||||||
- 增加 0-30% 随机抖动,降低多账号同时重连冲击。
|
- 增加 0-30% 随机抖动,降低多账号同时重连冲击。
|
||||||
|
|||||||
@@ -96,6 +96,9 @@ distance = track.width - button.width
|
|||||||
- 页面加载后随机等待 `0.3–0.8s`,移动鼠标到 `(640, 360)`,滚动 `200–500px`,并保留现有短暂停顿。
|
- 页面加载后随机等待 `0.3–0.8s`,移动鼠标到 `(640, 360)`,滚动 `200–500px`,并保留现有短暂停顿。
|
||||||
- 页面包含“抱歉,页面访问出现了问题”时,判定验证链接过期。
|
- 页面包含“抱歉,页面访问出现了问题”时,判定验证链接过期。
|
||||||
- 页面包含 `STATUS_BREAKPOINT` 或“崩溃”时,判定验证页崩溃。
|
- 页面包含 `STATUS_BREAKPOINT` 或“崩溃”时,判定验证页崩溃。
|
||||||
|
- 页面准备完成后、首次滑动前必须先判定页面类型:只有同一 frame 内存在可见的滑块按钮和轨道时才进入滑动逻辑。
|
||||||
|
- 如果没有可见滑块,并且任一 frame 的可见正文直接显示“验证失败”“安全验证未通过”“请求/加载失败”“系统繁忙”“服务/网络/页面异常”“请稍后重试”或对应英文错误提示,则判定为无可验证滑块的直接错误页,立即停止自动验证。
|
||||||
|
- 直接错误页不得通过点击错误框、reload 或备用引擎强行转成滑块尝试;只有已经实际拖动过滑块后出现的 `.errloading` 才继续按第 5 节恢复。
|
||||||
- 拖动前必须保存所有域上的旧 `x5sec` 值,供严格成功判定使用。
|
- 拖动前必须保存所有域上的旧 `x5sec` 值,供严格成功判定使用。
|
||||||
|
|
||||||
### 3.2 距离计算
|
### 3.2 距离计算
|
||||||
@@ -114,12 +117,12 @@ distance = track.width - button.width
|
|||||||
主引擎轨迹冻结为以下行为:
|
主引擎轨迹冻结为以下行为:
|
||||||
|
|
||||||
- 按钮按下前,从按钮左侧附近自然接近,再悬停、对准按钮中心并停顿。
|
- 按钮按下前,从按钮左侧附近自然接近,再悬停、对准按钮中心并停顿。
|
||||||
- 按下后使用恰好 6 个高层轨迹点。
|
- 按下后使用随机的 `8–12` 个高层轨迹点。
|
||||||
- 轨迹分为加速、匀速、减速三段;带小幅 Y 轴抖动。
|
- 轨迹分为加速、匀速、减速三段;Y 轴按连续、非线性的完整 S 形曲线移动,峰峰值精确为实际滑轨高度的 `1/2`。高层锚点之间必须以不超过 `15ms` 的连续鼠标事件连接;按下到释放期间不得出现可感知的静止停顿或中段确认停顿。
|
||||||
- X 轴不超调,最后一个点强制等于计算出的精确距离。
|
- 标准 NC 先按精确可用距离计算轨道终点,再让鼠标最终 X 随机超出 `4–20px`;页面滑块控件必须仍受自身轨道边界限制,不得越出可见轨道。
|
||||||
- 保留每个点的短随机计划延时,同时按真实墙钟时间补偿,使移动阶段处于 `480–900ms` 目标窗口。
|
- 保留每个锚点的非均匀随机时长权重,并按真实墙钟时间补偿,使移动阶段处于 `0.55–1.05s` 目标窗口;该时长必须由持续移动分配,不能用锚点后的长等待填充。
|
||||||
- 顺序固定为 `mouse down → 分段移动 → mouse up → 兼容性 click 事件`。
|
- 顺序固定为 `mouse down → 分段移动 → mouse up → 兼容性 click 事件`。
|
||||||
- 标准 NC 不得添加尾部超调、回拉或额外轨迹点。
|
- 标准 NC 不得添加回拉;仅允许上述受控的鼠标尾部超调。
|
||||||
|
|
||||||
拖动完成后保留 `800ms` 等待,再进入严格成功检查。
|
拖动完成后保留 `800ms` 等待,再进入严格成功检查。
|
||||||
|
|
||||||
@@ -175,11 +178,11 @@ purecaptcha
|
|||||||
|
|
||||||
恢复状态机固定如下:
|
恢复状态机固定如下:
|
||||||
|
|
||||||
1. 优先点击可见的失败/刷新控件。
|
1. 已完成一次拖动后出现失败提示时,优先点击可见的失败/刷新控件,直接让平台生成新滑块。
|
||||||
2. 控件可能延迟出现,首次未找到时按现有逻辑最多短暂等待 `800ms` 并轮询。
|
2. 控件可能延迟出现,首次未找到时最多短暂等待 `800ms` 并轮询;该等待期间不得刷新页面。
|
||||||
3. 点击后最多等待 `4s`,确认按钮和轨道重新出现,且按钮回到轨道起点 `±3px` 内。
|
3. 点击后最多等待 `4s`,确认按钮和轨道重新出现,且按钮回到轨道起点 `±3px` 内。
|
||||||
4. 点击恢复失败或滑块未归位时,重载原页面。
|
4. 已完成一次拖动后的点击恢复失败或滑块未归位时,保留当前失败现场并结束本次滑块流程,不得重载原页面。
|
||||||
5. 重载等待 `domcontentloaded`,单次超时最多 `8s`;重载后最多等待 `5s` 确认滑块归位。
|
5. 仅首次页面准备阶段尚未实际拖动、且又不属于第 3.1 节直接错误页时,保留重载恢复:重载等待 `domcontentloaded`,单次超时最多 `8s`;重载后最多等待 `5s` 确认滑块归位。
|
||||||
6. 主引擎两次尝试之间保留 `1–2s` 随机等待;总尝试次数保持 3 次。
|
6. 主引擎两次尝试之间保留 `1–2s` 随机等待;总尝试次数保持 3 次。
|
||||||
|
|
||||||
不得用“元素重新出现”替代“元素重新出现且按钮回到原点”的确认。
|
不得用“元素重新出现”替代“元素重新出现且按钮回到原点”的确认。
|
||||||
@@ -199,10 +202,26 @@ Playwright 主引擎
|
|||||||
|
|
||||||
- 获取新验证链接的 provider 不得在主引擎持有同账号持久化 profile 锁时调用,避免同账号锁死。
|
- 获取新验证链接的 provider 不得在主引擎持有同账号持久化 profile 锁时调用,避免同账号锁死。
|
||||||
- 过期链接最多触发现有的 2 次链接刷新;最终仍过期时直接失败,不把过期 URL 交给备用引擎重放。
|
- 过期链接最多触发现有的 2 次链接刷新;最终仍过期时直接失败,不把过期 URL 交给备用引擎重放。
|
||||||
|
- 主引擎判定为“没有可见滑块的直接错误页”时立即失败,不刷新链接,也不进入直接 Chromium/CDP 备用引擎。
|
||||||
- 进入备用引擎前可再获取一次新链接和更新后的 Cookie。
|
- 进入备用引擎前可再获取一次新链接和更新后的 Cookie。
|
||||||
- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。
|
- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。
|
||||||
- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。
|
- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。
|
||||||
- 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。
|
- 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。
|
||||||
|
- `CAPTCHA_IGNORE_CERT_ERRORS` 默认关闭。仅当运行环境存在 TLS 检查代理、且诊断明确记录
|
||||||
|
Alibaba 风控资源出现 `ERR_CERT_AUTHORITY_INVALID` 时,才允许显式设为 `true`;此时主引擎和
|
||||||
|
备用 Chromium 都追加 `--ignore-certificate-errors`,HTTP 客户端仍保持正常证书校验。该开关
|
||||||
|
必须记录在部署配置中,不能默认开启或静默改变。
|
||||||
|
- `CAPTCHA_BROWSER_PROXY` 默认未设置,Chromium 保留操作系统代理配置。仅当诊断确认系统代理的
|
||||||
|
Fake-IP 或 PAC 路径使 Alibaba 风控资源不能作为脚本加载时,可显式设置为无凭证的
|
||||||
|
`http://`、`https://`、`socks4://` 或 `socks5://` 代理地址;主引擎与备用 Chromium 必须同时追加
|
||||||
|
相同的 `--proxy-server`。该开关不得接受代理凭证、查询或片段,也不得记录其值或改变非浏览器 HTTP 客户端。
|
||||||
|
- 初始化时必须从随包 Chromium 实测 UA 和 Client Hints。无头上下文只允许把 legacy UA 中的
|
||||||
|
`HeadlessChrome/<实际版本>` 规范化为 `Chrome/<相同实际版本>`;不得伪造版本、操作系统或移动端
|
||||||
|
状态。有头上下文不覆盖 Chromium 原生 UA。Playwright 主引擎必须同时使用 context `userAgent`
|
||||||
|
和导航前保持连接的页面级 `Emulation.setUserAgentOverride`,后者携带从实际 Chromium 读取并去除
|
||||||
|
无头品牌、去重后的 `userAgentMetadata`;只设置 context `userAgent` 不合格,因为其默认
|
||||||
|
`Sec-CH-UA` 和 `navigator.userAgentData` 仍可能包含 `HeadlessChrome`。非浏览器 HTTP 请求使用同一份
|
||||||
|
规范化运行时指纹。
|
||||||
|
|
||||||
## 7. 备用引擎行为
|
## 7. 备用引擎行为
|
||||||
|
|
||||||
@@ -213,6 +232,10 @@ Playwright 主引擎
|
|||||||
- 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。
|
- 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。
|
||||||
- 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。
|
- 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。
|
||||||
- headless 时使用 `--headless=new`。
|
- headless 时使用 `--headless=new`。
|
||||||
|
- 直接 Chromium 必须同时携带与当前 Playwright runtime 匹配的兼容启动参数集合(包括后台网络、扩展、Storage 分区、渲染器后台化、SwiftShader 等参数),否则通过 CDP 访问默认上下文的 Cookie Storage 可能无响应;该集合必须随 Playwright runtime 升级同步核对。
|
||||||
|
- 备用引擎对默认上下文执行 Cookie 清理、注入和读取时,每次操作最多等待 `5s`;超时必须中止当前备用引擎流程并释放浏览器,不得无限阻塞续期协程。
|
||||||
|
- headless 时必须在导航前通过 `--user-agent` 应用同版本、已去除 `HeadlessChrome` 标记的运行时 UA;
|
||||||
|
有头模式不得追加该覆盖。Chromium 原生 Client Hints 必须继续保留,且不得出现 `HeadlessChrome`。
|
||||||
- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。
|
- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。
|
||||||
|
|
||||||
备用距离规则固定如下:
|
备用距离规则固定如下:
|
||||||
@@ -242,6 +265,9 @@ Playwright 主引擎
|
|||||||
- 最终 `left`、最终 class 或最终 X 偏移。
|
- 最终 `left`、最终 class 或最终 X 偏移。
|
||||||
- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。
|
- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。
|
||||||
- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。
|
- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。
|
||||||
|
- 诊断包的 `page_state` 必须保留页面实际看到的 `navigator.userAgent`、`navigator.webdriver`、
|
||||||
|
`navigator.userAgentData` 基础字段及可读取的 high-entropy values,用于识别 UA/Client Hints 矛盾。
|
||||||
|
- 自动滑块最终失败时,错误文本和 `token 风控滑块处理失败` 日志的 `verification_url` 字段必须包含最后实际使用的完整验证地址(包括 query),供用户复制到本机浏览器手动验证。此字段是仅在最终失败时提供的人工接管信息;常规页面/frame 诊断日志仍必须去掉 query 与 fragment。
|
||||||
|
|
||||||
页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
||||||
|
|
||||||
@@ -268,13 +294,47 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server
|
|||||||
- 主引擎首次滑动成功。
|
- 主引擎首次滑动成功。
|
||||||
- 主引擎首次失败并隐藏滑块,点击 `.errloading` 恢复后第二次成功。
|
- 主引擎首次失败并隐藏滑块,点击 `.errloading` 恢复后第二次成功。
|
||||||
- 直接 Chromium/CDP 备用引擎使用同一恢复流程后成功。
|
- 直接 Chromium/CDP 备用引擎使用同一恢复流程后成功。
|
||||||
|
- 没有可见滑块、只显示直接错误提示的真实 Chromium 页面必须被识别,并且不得进入滑动或备用引擎。
|
||||||
- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。
|
- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。
|
||||||
- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。
|
- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。
|
||||||
|
- 主 Playwright 无头上下文和直接 Chromium/CDP 无头上下文的 HTTP `User-Agent`、`Sec-CH-UA`、
|
||||||
|
`navigator.userAgent`、`navigator.userAgentData` 都不得出现 `HeadlessChrome`/`headless` 标记,UA 中
|
||||||
|
的 Chrome 完整版本必须与随包 Chromium 一致。
|
||||||
|
|
||||||
不得删除、跳过、弱化或改写断言来让行为变化通过测试。
|
不得删除、跳过、弱化或改写断言来让行为变化通过测试。
|
||||||
|
|
||||||
## 10. 唯一变更流程
|
## 10. 唯一变更流程
|
||||||
|
|
||||||
|
### 2026-08-13 当前授权变更
|
||||||
|
|
||||||
|
用户明确要求改变“未找到滑块时仍执行失败恢复/备用引擎”和“最终失败日志只保留脱敏页面地址”的既有契约。原因是风控页有时只显示平台错误信息而没有可操作滑块,继续 reload、拖动或切换引擎没有验证意义且会增加风控;而真实滑块自动处理失败时,用户需要完整地址在本机浏览器中接管验证。本规范第 3.1、6、8、9 节已同步纳入新的页面分类、编排、日志和集成验证要求。
|
||||||
|
|
||||||
|
### 2026-08-17 当前授权变更
|
||||||
|
|
||||||
|
用户明确要求解决无头 Chromium 指纹暴露 `HeadlessChrome` 的问题。此前随包 Chromium 在服务端
|
||||||
|
风控页中实测返回 `HeadlessChrome/149.0.7827.55`,会让 HTTP UA 与正常桌面 Chromium 身份不同。
|
||||||
|
本规范第 6 至 9 节同步加入了只移除无头产品标记、保留实际版本与 Client Hints、覆盖主/备用引擎、
|
||||||
|
并在诊断包及真实 Chromium 集成测试中核验页面实际指纹的契约。
|
||||||
|
|
||||||
|
### 2026-08-17 主引擎轨迹授权变更
|
||||||
|
|
||||||
|
用户明确要求主引擎避免固定、流畅且稳定的短时拖动,因为这类动作在实际风控页上缺少人工操作的
|
||||||
|
确认节奏。第 3.3 节据此从固定 6 点和 `480–900ms` 调整为 `8–12` 个单调前进点、一次中段停顿及
|
||||||
|
`1.1–2.1s` 墙钟窗口。用户随后明确要求 Y 轴不能只是微扰,因此该节补充为使用实际滑轨半高的连续
|
||||||
|
非线性 S 形纵向范围。用户随后明确要求 X 轴也不能每次精确落点,因此末点改为在精确可用距离外随机 `4–20px` 的受控鼠标超调,页面控件仍由轨道边界钳位。距离计算、事件顺序、严格成功判定及备用引擎均保持不变。
|
||||||
|
|
||||||
|
### 2026-08-18 主引擎连续拖动授权变更
|
||||||
|
|
||||||
|
用户在实际风控页观察到主引擎呈现逐段拖动效果,明确要求按下后必须一口气连续拖至终点。第 3.3 节据此移除中段确认停顿:保留原有高层曲线锚点、三段速度形状、完整 S 形纵向范围、受控鼠标超调和 `1.1–2.1s` 墙钟窗口,但将锚点间移动展开为最大间隔 `30ms` 的连续事件流。距离计算、成功判定、失败恢复、Cookie 处理和备用引擎保持不变。
|
||||||
|
|
||||||
|
### 2026-08-18 主引擎提速授权变更
|
||||||
|
|
||||||
|
用户在有头模式观察后明确要求主引擎滑动速度提高一倍。第 3.3 节据此将按下到释放的目标窗口从 `1.1–2.1s` 缩短为 `0.55–1.05s`,并将连续事件最大间隔从 `30ms` 收紧为 `15ms`。非匀速节奏、三段速度形状、完整 S 形纵向范围、受控鼠标超调、距离计算、成功判定、失败恢复、Cookie 处理和备用引擎保持不变。
|
||||||
|
|
||||||
|
### 2026-08-18 滑动失败直接重试授权变更
|
||||||
|
|
||||||
|
用户明确要求滑动后出现平台失败提示时,不得刷新验证页;必须点击失败按钮,让平台在当前页重新生成滑块后直接进行下一次拖动。第 5 节据此限制已完成拖动后的恢复路径为按钮点击与归位确认:找不到失败按钮或点击后滑块未归位时结束本次流程并保留现场。首次页面准备尚未实际拖动时的既有重载恢复保留。
|
||||||
|
|
||||||
只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中:
|
只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中:
|
||||||
|
|
||||||
1. 说明要改变本文哪一条冻结契约及原因。
|
1. 说明要改变本文哪一条冻结契约及原因。
|
||||||
|
|||||||
+10
-1
@@ -22,6 +22,9 @@
|
|||||||
控制器以及匹配架构的 Playwright driver、Chromium;Linux 安装包自带相同的浏览器 runtime,
|
控制器以及匹配架构的 Playwright driver、Chromium;Linux 安装包自带相同的浏览器 runtime,
|
||||||
安装脚本只补齐系统依赖。桌面托盘退出前会先停止后台服务。
|
安装脚本只补齐系统依赖。桌面托盘退出前会先停止后台服务。
|
||||||
|
|
||||||
|
管理后台侧边栏底部会显示当前运行版本和短提交号。源码运行默认显示 `dev`/`unknown`;正式安装包和
|
||||||
|
Docker 镜像会显示构建时注入的正式版本与提交信息。
|
||||||
|
|
||||||
Windows 安装包注册 `YdisksXianyuHelper` 服务;macOS 安装包分别提供 Apple Silicon(arm64)和
|
Windows 安装包注册 `YdisksXianyuHelper` 服务;macOS 安装包分别提供 Apple Silicon(arm64)和
|
||||||
Intel(amd64)版本,并注册 `com.ydisks.xianyu-helper.server` 与
|
Intel(amd64)版本,并注册 `com.ydisks.xianyu-helper.server` 与
|
||||||
`com.ydisks.xianyu-helper.tray` 两个 LaunchAgent。Linux 安装包按 amd64/arm64 分发,执行
|
`com.ydisks.xianyu-helper.tray` 两个 LaunchAgent。Linux 安装包按 amd64/arm64 分发,执行
|
||||||
@@ -46,4 +49,10 @@ Intel(amd64)版本,并注册 `com.ydisks.xianyu-helper.server` 与
|
|||||||
|
|
||||||
## GitHub Wiki 同步
|
## GitHub Wiki 同步
|
||||||
|
|
||||||
这些 Markdown 文件位于仓库 `docs/wiki/`,可直接复制到 GitHub Wiki 对应页面;文件名即页面名。`_Sidebar.md` 是 Wiki 导航。仓库内保留副本便于在 Pull Request 中审阅和版本化维护。
|
这些 Markdown 文件位于仓库 `docs/wiki/`,是 Wiki 的唯一维护来源;文件名即页面名,`_Sidebar.md` 是
|
||||||
|
Wiki 导航。`main` 分支发生变更后,`.github/workflows/sync-wiki.yml` 会自动把这些文件镜像到 GitHub
|
||||||
|
Wiki;也可以通过 GitHub Actions 手动运行该工作流。仓库内保留副本,便于在 Pull Request 中审阅和版本化维护,
|
||||||
|
不建议直接在 GitHub Wiki 仓库中维护内容。
|
||||||
|
|
||||||
|
项目 Pages 站点使用 `main` 分支的 `/docs` 目录发布,域名由 `docs/CNAME` 中的配置决定;修改首页或图片资源
|
||||||
|
后,合并到 `main` 即可由 GitHub Pages 发布。Pages 发布与 GitHub Wiki 同步是两个独立流程。
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
- 进入会话后优先读取本地缓存,再从闲鱼历史消息接口补齐记录;底部可继续加载更早消息和更多历史联系人。
|
- 进入会话后优先读取本地缓存,再从闲鱼历史消息接口补齐记录;底部可继续加载更早消息和更多历史联系人。
|
||||||
- 文本消息、闲鱼文字表情和图片发送。当前不支持从管理后台发送视频,因此界面不提供视频发送按钮。
|
- 文本消息、闲鱼文字表情和图片发送。当前不支持从管理后台发送视频,因此界面不提供视频发送按钮。
|
||||||
- 发送方按“对方/我”区分,并显示对应头像;账号之间的会话和实时消息完全隔离。
|
- 发送方按“对方/我”区分,并显示对应头像;账号之间的会话和实时消息完全隔离。
|
||||||
- 应用使用后端 `/api/chat/ws` 推送实时事件;刷新或重连后仍以历史接口和本地数据库为准,不只依赖 WebSocket 存续期间收到的消息。
|
- 应用使用后端 `/api/v1/chat/ws` 推送实时事件;刷新或重连后仍以历史接口和本地数据库为准,不只依赖 WebSocket 存续期间收到的消息。
|
||||||
|
|
||||||
### 官方消息识别
|
### 官方消息识别
|
||||||
|
|
||||||
@@ -59,4 +59,3 @@
|
|||||||
- 关键词回复、默认回复和 AI 回复。
|
- 关键词回复、默认回复和 AI 回复。
|
||||||
|
|
||||||
闲鱼官方系统消息只用于平台事件识别,不应被配置为普通买家关键词触发自动回复。
|
闲鱼官方系统消息只用于平台事件识别,不应被配置为普通买家关键词触发自动回复。
|
||||||
|
|
||||||
+1
-1
@@ -18,7 +18,7 @@
|
|||||||
|
|
||||||
- 标题非空,价格大于 0;库存为正整数,留空默认 1。
|
- 标题非空,价格大于 0;库存为正整数,留空默认 1。
|
||||||
- 邮费模式为 `free`/`包邮` 或 `fixed`/`固定邮费`;固定邮费时必须填邮费。
|
- 邮费模式为 `free`/`包邮` 或 `fixed`/`固定邮费`;固定邮费时必须填邮费。
|
||||||
- 每件商品 1–9 张图片,多个用英文分号 `;` 分隔。可用公开 `https://` URL,或 ZIP 内相对路径。
|
- 每件商品 1–9 张图片,多个用英文分号 `;` 分隔。可用公开可访问的 `http(s)://` URL,或 ZIP 内相对路径。
|
||||||
- 上传页的默认类目可以留空。需要指定时,先选择账号,再输入关键词,由闲鱼推荐接口返回完整类目信息。表格的“类目ID + 类目名称 + 频道类目ID”可覆盖当前行;三列必须同时填写。
|
- 上传页的默认类目可以留空。需要指定时,先选择账号,再输入关键词,由闲鱼推荐接口返回完整类目信息。表格的“类目ID + 类目名称 + 频道类目ID”可覆盖当前行;三列必须同时填写。
|
||||||
- “淘宝类目ID”按闲鱼推荐响应填写;“电子资料”的值为空,应保持为空。
|
- “淘宝类目ID”按闲鱼推荐响应填写;“电子资料”的值为空,应保持为空。
|
||||||
- 本地图片 ZIP 最大 200 MiB,单图最大 10 MiB;表格最大 20 MiB。
|
- 本地图片 ZIP 最大 200 MiB,单图最大 10 MiB;表格最大 20 MiB。
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
| 评价后发送赠品 | 收到评价系统卡片 | 匹配商品/规格 → 发送赠品卡密。 |
|
| 评价后发送赠品 | 收到评价系统卡片 | 匹配商品/规格 → 发送赠品卡密。 |
|
||||||
| 超时未评价求评价 | 定时扫描已发货未评价订单 | 到达等待时间 → 发送提醒文案。 |
|
| 超时未评价求评价 | 定时扫描已发货未评价订单 | 到达等待时间 → 发送提醒文案。 |
|
||||||
|
|
||||||
系统通知卡片只进入自动化判断;买家普通消息走关键词、默认回复和 AI 规则。
|
系统通知卡片只进入自动化判断;买家普通消息依次进入 API 回复、关键词回复、AI 回复和默认回复链路。
|
||||||
|
|
||||||
账号级自动评价和每日擦亮不属于上表的订单规则,配置入口在“账号管理 → 自动评价与每日擦亮”,执行方式见[在线聊天与账号自动任务](在线聊天与账号自动任务)。
|
账号级自动评价和每日擦亮不属于上表的订单规则,配置入口在“账号管理 → 自动评价与每日擦亮”,执行方式见[在线聊天与账号自动任务](在线聊天与账号自动任务)。
|
||||||
|
|
||||||
@@ -46,4 +46,4 @@
|
|||||||
|
|
||||||
在“自动化规则”的“关键词回复”页:选择账号 → 新增规则 → 填写关键词与文本或图片 URL → 保存。关键词规则用于买家普通消息。
|
在“自动化规则”的“关键词回复”页:选择账号 → 新增规则 → 填写关键词与文本或图片 URL → 保存。关键词规则用于买家普通消息。
|
||||||
|
|
||||||
“账号默认回复”只在关键词和 AI 都未处理该消息时使用。可设置文本、图片 URL 和“同一会话只回复一次”。上线前避免关键词、默认回复和 AI 提示词对同类问题给出互相矛盾的答案。
|
默认回复处于四级回复链路的最后一级:API 回复优先,其次是关键词回复,再是 AI 回复,最后才是默认回复。AI 仅处理砍价场景;AI 未启用、未配置 API Key、消息不属于砍价、没有可用结果或调用失败时,都会继续尝试默认回复。默认回复可设置文本、图片 URL 和“同一会话只回复一次”;指定商品默认回复优先于账号默认回复。上线前避免 API、关键词、默认回复和 AI 提示词对同类问题给出互相矛盾的答案。
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
1. 进入“账号管理”,选择添加账号/扫码登录。
|
1. 进入“账号管理”,选择添加账号/扫码登录。
|
||||||
2. 用目标闲鱼账号在官方客户端完成扫码;若出现人脸或安全验证,按页面提示在官方流程中完成。
|
2. 用目标闲鱼账号在官方客户端完成扫码;若出现人脸或安全验证,按页面提示在官方流程中完成。
|
||||||
3. 等待后台保存登录信息,确认昵称、账号 ID 和运行状态正常。
|
3. 等待后台保存登录信息,确认昵称、账号 ID 和运行状态正常。若状态显示“运行状态冲突”,表示数据库已停用但旧运行实例仍存活;不要把它当作已停用,等待或重试停用并检查服务日志。
|
||||||
4. 为账号填写备注,按需开启或暂停账号,并进入编辑页绑定通知渠道。
|
4. 为账号填写备注,按需开启或暂停账号,并进入编辑页绑定通知渠道。
|
||||||
5. 首次接入后同步一次商品;开始自动化前确认账号处于启用状态。
|
5. 首次接入后同步一次商品;开始自动化前确认账号处于启用状态。
|
||||||
|
|
||||||
|
|||||||
+54
-2
@@ -22,16 +22,50 @@
|
|||||||
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
|
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
|
||||||
两次不少于 8 个字符的密码即可。
|
两次不少于 8 个字符的密码即可。
|
||||||
|
|
||||||
|
> 安全提示:源码和容器使用 `-addr :59188` 时会监听全部接口。未初始化实例的网页首次初始化没有
|
||||||
|
> 预共享 secret,最先连到管理端口的客户端可以创建管理员。该便利行为不做 IP 限制,部署者必须在
|
||||||
|
> 防火墙、安全组或反向代理层限制访问;公网部署建议设置 `XIANYU_ADMIN_PASSWORD` 或先使用
|
||||||
|
> `-init-admin` 完成初始化。
|
||||||
|
|
||||||
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
|
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
|
||||||
|
|
||||||
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||||
|
|
||||||
|
源码服务默认使用 `-addr :59188`,会监听全部网络接口;Docker Compose 端口映射默认也使用
|
||||||
|
`XIANYU_BIND_ADDRESS=0.0.0.0`。桌面安装包则显式绑定 `127.0.0.1:59188`。远程部署必须在防火墙、
|
||||||
|
安全组或反向代理层限制管理端口,不能把源码示例中的 `:59188` 误认为仅本机监听。
|
||||||
|
|
||||||
|
## 版本、镜像与正式发布
|
||||||
|
|
||||||
|
项目以 Git 标签作为正式版本来源,正式标签必须符合 `v1.2.3` 格式,并指向 `main` 已包含的提交。
|
||||||
|
推送正式标签后,统一的 `.github/workflows/release.yml` 会重新从该标签提交构建桌面安装包和 Docker 镜像;
|
||||||
|
不会复用之前 `main` 分支构建的产物。
|
||||||
|
构建、Chromium 启动和 `/health` 检查全部通过后,还需要 `production-release` Environment 人工审批,
|
||||||
|
审批通过才会创建 GitHub Release、上传安装包与 `SHA256SUMS`,并更新正式镜像标签。
|
||||||
|
GitHub Release 正文使用正式标签所指向提交的短 SHA 和完整 Git commit message(主题和正文),不会展开
|
||||||
|
标签之间的全部历史提交。重跑同名标签时会同步更新正文并覆盖附件。
|
||||||
|
|
||||||
|
Docker 标签规则如下:
|
||||||
|
|
||||||
|
| Git 引用 | 镜像标签 | 是否正式发布 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `dev` 分支 | `dev`、`sha-<完整提交号>` | 否,用于日常调试 |
|
||||||
|
| `main` 分支 | `main`、`sha-<完整提交号>` | 否,稳定候选构建 |
|
||||||
|
| `v1.2.3` 标签 | `v1.2.3`、`1.2.3`、`1.2`、`latest`、`sha-<完整提交号>` | 是 |
|
||||||
|
|
||||||
|
`latest` 只在正式版本审批发布阶段更新,不会随 `main` 或 `dev` 分支提交变化。生产环境建议使用
|
||||||
|
`v1.2.3`、`1.2.3` 或 SHA 标签固定版本;Compose 默认使用 `latest`。
|
||||||
|
|
||||||
|
当前 Windows 和 macOS 正式安装包的 CI 签名步骤仍需要对应的签名证书 Secrets;未配置时这些平台的
|
||||||
|
正式发布会在签名步骤失败。Linux 安装包不依赖桌面端签名证书。
|
||||||
|
|
||||||
## 独立安装包
|
## 独立安装包
|
||||||
|
|
||||||
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
|
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
|
||||||
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。Docker CI 会优先
|
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。Docker CI 会优先
|
||||||
复用架构专属的 GitHub Actions runtime 缓存,Dockerfile 最终使用 `node:latest` 运行时,不执行
|
复用架构专属的 GitHub Actions runtime 缓存,Dockerfile 最终使用固定的 Node.js 24 slim 运行时,
|
||||||
`apt-get update` 或安装 Debian Chromium。安装时不需要用户再执行浏览器下载命令。
|
只通过 Playwright 安装 Chromium 所需系统动态库,随后清理 apt 索引和临时缓存,不安装 Debian
|
||||||
|
仓库中的 Chromium。安装时不需要用户再执行浏览器下载命令。
|
||||||
|
|
||||||
| 平台 | 安装方式 | 服务标识 | 默认地址 |
|
| 平台 | 安装方式 | 服务标识 | 默认地址 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
@@ -50,6 +84,22 @@ Windows 安装阶段会授予交互式登录用户该服务的查询、启动和
|
|||||||
`/var/lib/ydisks-xianyu-helper` 与 `/var/log/ydisks-xianyu-helper`。macOS 必须选择与 CPU 匹配的
|
`/var/lib/ydisks-xianyu-helper` 与 `/var/log/ydisks-xianyu-helper`。macOS 必须选择与 CPU 匹配的
|
||||||
arm64 或 amd64 包;Linux 也必须在相同架构的主机上安装,安装脚本不使用 QEMU。
|
arm64 或 amd64 包;Linux 也必须在相同架构的主机上安装,安装脚本不使用 QEMU。
|
||||||
|
|
||||||
|
本地 macOS 打包必须先构建前端与三个可执行文件,再调用唯一的打包脚本。脚本在 runtime 缺失时会自动
|
||||||
|
从本机 Playwright 缓存准备匹配的 driver、Chromium 和 headless shell:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci --prefix frontend
|
||||||
|
npm run build --prefix frontend
|
||||||
|
mkdir -p dist/macos/arm64
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-server ./cmd/server
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/browser-install ./cmd/browser-install
|
||||||
|
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-tray ./cmd/tray
|
||||||
|
packaging/macos/build-pkg.sh 0.0.0-local "$PWD/dist/macos" arm64
|
||||||
|
```
|
||||||
|
|
||||||
|
Intel macOS 将上述 `arm64` 替换为 `amd64`,且需要本机已准备对应 x64 runtime。没有签名身份时生成的是
|
||||||
|
未签名 pkg,不可作为已签名分发包使用。
|
||||||
|
|
||||||
## 桌面端日志与操作
|
## 桌面端日志与操作
|
||||||
|
|
||||||
日志目录如下。Windows 和 macOS 托盘菜单还可以启动、停止或重启后台服务,打开管理页面和日志目录。
|
日志目录如下。Windows 和 macOS 托盘菜单还可以启动、停止或重启后台服务,打开管理页面和日志目录。
|
||||||
@@ -70,6 +120,8 @@ Windows 安装器会在安装阶段一次性配置当前机器上该服务的最
|
|||||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||||
```
|
```
|
||||||
|
|
||||||
|
上例会监听全部接口;仅本机使用时可改为 `-addr 127.0.0.1:59188`。
|
||||||
|
|
||||||
也可显式指定:
|
也可显式指定:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+11
-368
@@ -1,372 +1,15 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React from 'react';
|
||||||
import Sidebar from './components/Sidebar';
|
import { AppErrorBoundary } from './app/errors/AppErrorBoundary';
|
||||||
import Dashboard from './components/Dashboard';
|
import { SessionProvider } from './app/providers/SessionProvider';
|
||||||
import AccountList from './components/AccountList';
|
import { AppRouter } from './app/router/AppRouter';
|
||||||
import OrderList from './components/OrderList';
|
|
||||||
import CardList from './components/CardList';
|
|
||||||
import ItemList from './components/ItemList';
|
|
||||||
import Settings from './components/Settings';
|
|
||||||
import Rules from './components/Rules';
|
|
||||||
import Notifications from './components/Notifications';
|
|
||||||
import Chat from './components/Chat';
|
|
||||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
|
|
||||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
|
||||||
import { initializeAdmin, login, logout, verifySession } from './services/api';
|
|
||||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
|
||||||
|
|
||||||
interface DeliveryRuleTarget {
|
/** App 只装配全局 Provider、错误边界和路由,不保留任何领域页面或请求状态。 */
|
||||||
cookieId: string;
|
const App: React.FC = () => (
|
||||||
itemId: string;
|
<AppErrorBoundary>
|
||||||
requestId: number;
|
<SessionProvider>
|
||||||
}
|
<AppRouter />
|
||||||
|
</SessionProvider>
|
||||||
// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API
|
</AppErrorBoundary>
|
||||||
// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接
|
|
||||||
// 返回 JSON 而不是 SPA 页面。
|
|
||||||
const ROUTES: Record<string, string> = {
|
|
||||||
'/app/dashboard': 'dashboard',
|
|
||||||
'/app/accounts': 'accounts',
|
|
||||||
'/app/chat': 'chat',
|
|
||||||
'/app/orders': 'orders',
|
|
||||||
'/app/cards': 'cards',
|
|
||||||
'/app/items': 'items',
|
|
||||||
'/app/rules': 'rules',
|
|
||||||
'/app/notifications': 'notifications',
|
|
||||||
'/app/settings': 'settings',
|
|
||||||
};
|
|
||||||
const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
|
|
||||||
Object.entries(ROUTES).map(([path, tab]) => [tab, path])
|
|
||||||
);
|
);
|
||||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard';
|
|
||||||
|
|
||||||
const App: React.FC = () => {
|
|
||||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
|
||||||
const [isAdmin, setIsAdmin] = useState(false);
|
|
||||||
const [activeTab, setActiveTab] = useState(tabFromPath);
|
|
||||||
const [checkingAuth, setCheckingAuth] = useState(true);
|
|
||||||
const [needsInit, setNeedsInit] = useState(false);
|
|
||||||
const [username, setUsername] = useState('');
|
|
||||||
const [password, setPassword] = useState('');
|
|
||||||
const [loginLoading, setLoginLoading] = useState(false);
|
|
||||||
const [loginError, setLoginError] = useState('');
|
|
||||||
const [initialPassword, setInitialPassword] = useState('');
|
|
||||||
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
|
|
||||||
const [initializing, setInitializing] = useState(false);
|
|
||||||
const [initializationError, setInitializationError] = useState('');
|
|
||||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
|
|
||||||
|
|
||||||
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
|
|
||||||
const navigate = (tab: string) => {
|
|
||||||
const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab;
|
|
||||||
const path = TAB_TO_PATH[nextTab];
|
|
||||||
if (path && path !== window.location.pathname) {
|
|
||||||
window.history.pushState({}, '', path);
|
|
||||||
}
|
|
||||||
setActiveTab(nextTab);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 浏览器后退/前进同步 tab。
|
|
||||||
useEffect(() => {
|
|
||||||
const onPopState = () => setActiveTab(tabFromPath());
|
|
||||||
window.addEventListener('popstate', onPopState);
|
|
||||||
return () => window.removeEventListener('popstate', onPopState);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Check auth on mount
|
|
||||||
useEffect(() => {
|
|
||||||
verifySession()
|
|
||||||
.then((res) => {
|
|
||||||
if (res?.initialized === false) {
|
|
||||||
setNeedsInit(true);
|
|
||||||
setIsLoggedIn(false);
|
|
||||||
setIsAdmin(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setNeedsInit(false);
|
|
||||||
if (res?.authenticated) {
|
|
||||||
setIsLoggedIn(true);
|
|
||||||
setIsAdmin(res.is_admin === true);
|
|
||||||
} else {
|
|
||||||
setIsAdmin(false);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
setIsLoggedIn(false);
|
|
||||||
setIsAdmin(false);
|
|
||||||
})
|
|
||||||
.finally(() => setCheckingAuth(false));
|
|
||||||
|
|
||||||
const handleAuthLogoutEvent = () => {
|
|
||||||
setIsLoggedIn(false);
|
|
||||||
setIsAdmin(false);
|
|
||||||
};
|
|
||||||
window.addEventListener('auth:logout', handleAuthLogoutEvent);
|
|
||||||
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
|
|
||||||
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
|
|
||||||
setActiveTab('dashboard');
|
|
||||||
}
|
|
||||||
}, [checkingAuth, isLoggedIn, isAdmin, activeTab]);
|
|
||||||
|
|
||||||
const handleLogin = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setLoginLoading(true);
|
|
||||||
setLoginError('');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await login({ username, password });
|
|
||||||
if (res.success) {
|
|
||||||
setIsLoggedIn(true);
|
|
||||||
setIsAdmin(res.is_admin === true);
|
|
||||||
} else {
|
|
||||||
setLoginError(res.message || '登录失败');
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
|
||||||
setLoginError(msg || '登录失败');
|
|
||||||
} finally {
|
|
||||||
setLoginLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInitialize = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setInitializationError('');
|
|
||||||
if (initialPassword.length < 8) {
|
|
||||||
setInitializationError('密码至少需要 8 个字符');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (initialPassword !== initialPasswordConfirm) {
|
|
||||||
setInitializationError('两次输入的密码不一致');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setInitializing(true);
|
|
||||||
try {
|
|
||||||
const res = await initializeAdmin(initialPassword);
|
|
||||||
if (!res.success) {
|
|
||||||
setInitializationError(res.message || '初始化失败,请重试');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setNeedsInit(false);
|
|
||||||
setIsLoggedIn(true);
|
|
||||||
setIsAdmin(res.is_admin === true);
|
|
||||||
setInitialPassword('');
|
|
||||||
setInitialPasswordConfirm('');
|
|
||||||
} catch (err) {
|
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
|
||||||
setInitializationError(msg || '初始化失败,请重试');
|
|
||||||
} finally {
|
|
||||||
setInitializing(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogout = async () => {
|
|
||||||
try {
|
|
||||||
await logout();
|
|
||||||
} catch (err) {
|
|
||||||
console.error('退出登录失败', err);
|
|
||||||
} finally {
|
|
||||||
setIsLoggedIn(false);
|
|
||||||
setIsAdmin(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
if (checkingAuth) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center bg-surface">
|
|
||||||
<Loader2 className="w-8 h-8 text-brand animate-spin" />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Init Screen (system not initialized)
|
|
||||||
if (needsInit) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
|
|
||||||
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
|
|
||||||
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
|
|
||||||
|
|
||||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in">
|
|
||||||
<div className="text-center mb-8">
|
|
||||||
<div className="mx-auto mb-6 flex justify-center">
|
|
||||||
<YdisksBrandIcon sizeClass="w-24 h-24" />
|
|
||||||
</div>
|
|
||||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">首次设置管理员密码</h2>
|
|
||||||
<p className="text-gray-600 font-medium">设置完成后会自动进入系统,管理员账号为 admin。</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleInitialize} className="space-y-5">
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="relative group">
|
|
||||||
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
placeholder="设置管理员密码(至少 8 个字符)"
|
|
||||||
value={initialPassword}
|
|
||||||
onChange={e => setInitialPassword(e.target.value)}
|
|
||||||
autoFocus
|
|
||||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="relative group">
|
|
||||||
<ShieldCheck className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
placeholder="再次输入密码"
|
|
||||||
value={initialPasswordConfirm}
|
|
||||||
onChange={e => setInitialPasswordConfirm(e.target.value)}
|
|
||||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{initializationError && (
|
|
||||||
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
|
|
||||||
<ShieldCheck className="w-4 h-4" /> {initializationError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={initializing}
|
|
||||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
|
|
||||||
>
|
|
||||||
{initializing ? <Loader2 className="w-5 h-5 animate-spin" /> : <>设置密码并进入系统 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<div className="mt-8 pt-6 border-t border-gray-100 text-center">
|
|
||||||
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">Secure Bootstrap</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login Screen Component
|
|
||||||
if (!isLoggedIn) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
|
|
||||||
{/* Animated Background Blobs */}
|
|
||||||
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
|
|
||||||
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
|
|
||||||
|
|
||||||
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in">
|
|
||||||
|
|
||||||
{/* Header with Logo */}
|
|
||||||
<div className="text-center mb-10">
|
|
||||||
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
|
|
||||||
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
|
|
||||||
</div>
|
|
||||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
|
|
||||||
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleLogin} className="space-y-5">
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="relative group">
|
|
||||||
<User className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="管理员账号"
|
|
||||||
value={username}
|
|
||||||
onChange={e => setUsername(e.target.value)}
|
|
||||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="relative group">
|
|
||||||
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
placeholder="密码"
|
|
||||||
value={password}
|
|
||||||
onChange={e => setPassword(e.target.value)}
|
|
||||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{loginError && (
|
|
||||||
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
|
|
||||||
<ShieldCheck className="w-4 h-4" /> {loginError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={loginLoading}
|
|
||||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
|
|
||||||
>
|
|
||||||
{loginLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <>立即登录 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<div className="mt-8 pt-6 border-t border-gray-100">
|
|
||||||
<div className="mt-6 text-center">
|
|
||||||
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">
|
|
||||||
Ydisks闲鱼助手 v1.0
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Main App Layout
|
|
||||||
const renderContent = () => {
|
|
||||||
switch (activeTab) {
|
|
||||||
case 'dashboard': return <Dashboard />;
|
|
||||||
case 'accounts': return <AccountList />;
|
|
||||||
case 'chat': return <Chat />;
|
|
||||||
case 'orders': return <OrderList />;
|
|
||||||
case 'cards': return <CardList />;
|
|
||||||
case 'items': return <ItemList onConfigureDelivery={(item) => {
|
|
||||||
setDeliveryRuleTarget({ cookieId: item.cookie_id, itemId: item.item_id, requestId: Date.now() });
|
|
||||||
navigate('rules');
|
|
||||||
}} />;
|
|
||||||
case 'rules': return <Rules
|
|
||||||
initialDeliveryTarget={deliveryRuleTarget}
|
|
||||||
onDeliveryTargetHandled={() => setDeliveryRuleTarget(undefined)}
|
|
||||||
/>;
|
|
||||||
case 'notifications': return <Notifications isAdmin={isAdmin} />;
|
|
||||||
case 'settings': return isAdmin ? <Settings /> : <Dashboard />;
|
|
||||||
default: return <Dashboard />;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen bg-canvas text-ink">
|
|
||||||
<Sidebar
|
|
||||||
activeTab={activeTab}
|
|
||||||
isAdmin={isAdmin}
|
|
||||||
collapsed={sidebarCollapsed}
|
|
||||||
onToggleCollapsed={() => setSidebarCollapsed(current => {
|
|
||||||
const next = !current;
|
|
||||||
writeSidebarCollapsed(next);
|
|
||||||
return next;
|
|
||||||
})}
|
|
||||||
onNavigate={navigate}
|
|
||||||
onLogout={handleLogout}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
|
|
||||||
{/* Subtle background decoration */}
|
|
||||||
<div className="fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"></div>
|
|
||||||
|
|
||||||
<div className={`${activeTab === 'chat' ? 'mx-auto max-w-[1680px]' : 'mx-auto max-w-[1400px] pb-10'}`}>
|
|
||||||
{renderContent()}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default App;
|
export default App;
|
||||||
+34
-33
@@ -1,32 +1,45 @@
|
|||||||
# Ydisks闲鱼助手前端
|
# Ydisks闲鱼助手前端
|
||||||
|
|
||||||
React + Vite + TypeScript 单页应用,作为 Ydisks闲鱼助手 Go 后端的管理面板。
|
React 19、Vite 6 与 TypeScript 单页应用,是 Go 后端提供的管理界面。
|
||||||
|
|
||||||
## 目录结构
|
## 目录结构
|
||||||
|
|
||||||
```text
|
```text
|
||||||
frontend/
|
frontend/
|
||||||
index.html 入口 HTML
|
index.html Vite 入口 HTML
|
||||||
index.tsx 应用入口(挂载 React、登录态判断、tab 路由)
|
index.tsx React 挂载入口
|
||||||
App.tsx 主壳:侧边栏 + 内容区 + 登录/首次初始化
|
App.tsx 根组件,仅装配 Provider、路由与错误边界
|
||||||
components/ 业务组件(Dashboard / OrderList / CardList / Rules / Settings ...)
|
app/
|
||||||
services/ 后端 API 封装(fetch 调用)
|
providers/ 会话状态与初始化流程
|
||||||
request.ts 统一请求工具(带 session cookie、错误处理)
|
router/ 浏览器历史路由与访问控制
|
||||||
types.ts 共享类型定义
|
shell/ 已登录应用壳与导航
|
||||||
vite.config.ts Vite 配置(base=/static/,代理 /api 到 :59188)
|
features/ 按业务领域组织的页面、状态、Hook 和 API 适配器
|
||||||
|
shared/
|
||||||
|
api-contract/ 版本化 HTTP DTO 定义
|
||||||
|
http/ 统一 HTTP 客户端、错误解析与契约校验
|
||||||
|
async/ 取消和最新请求代次工具
|
||||||
|
browser/ 浏览器侧轻量持久化工具
|
||||||
|
ui/ 跨领域复用的展示组件
|
||||||
|
vite.config.ts `base=/static/` 与 `/api`、`/health` 开发代理
|
||||||
```
|
```
|
||||||
|
|
||||||
|
生产组件、Hook 和状态只能通过所属 feature 的 API adapter 使用 transport DTO;feature 之间不得导入彼此的内部文件。所有生产业务请求均使用 `/api/v1/...`,并由 `frontend/featureArchitecture.test.ts` 的架构测试约束。
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
||||||
npm install
|
npm ci
|
||||||
npm run dev # http://localhost:3000,API 代理到 localhost:59188
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
开发时先启动后端(默认端口为 `59188`;桌面安装包绑定 `127.0.0.1`,源码运行可按需指定监听地址),
|
Vite 开发服务器运行在 `http://localhost:3000`,将 `/api` 和 `/health` 代理到 `http://localhost:59188`。先启动后端,例如:
|
||||||
例如 `go run ./cmd/server -addr :59188`,再启动前端 dev server。
|
|
||||||
这里的 `localhost:3000` 仅是 Vite 开发服务器地址,不是应用服务端口。
|
```bash
|
||||||
|
go run ./cmd/server -addr :59188
|
||||||
|
```
|
||||||
|
|
||||||
|
`-addr :59188` 会监听全部网络接口;本机开发以外应显式使用回环地址或配置网络访问控制。桌面安装包固定绑定 `127.0.0.1:59188`。
|
||||||
|
|
||||||
## 构建产物
|
## 构建产物
|
||||||
|
|
||||||
@@ -34,31 +47,19 @@ npm run dev # http://localhost:3000,API 代理到 localhost:59188
|
|||||||
npm run build
|
npm run build
|
||||||
```
|
```
|
||||||
|
|
||||||
产物写入 `../internal/webui/static/`,由 Go 服务通过 `//go:embed` 内嵌并服务于 `/static/*`。
|
产物写入 `../internal/webui/static/`,随后在构建 Go 服务时由 `//go:embed` 嵌入并服务于 `/static/*`。生产部署无需单独分发前端。若服务二进制已运行,必须重新构建并重启服务,浏览器刷新不会替换已嵌入的资源。
|
||||||
生产部署无需单独分发前端。若 Go 服务已经运行,构建完成后必须重启 Go 服务,
|
|
||||||
因为嵌入资源在 Go 编译时写入服务二进制;仅刷新浏览器不会更新已运行进程中的前端版本。
|
|
||||||
|
|
||||||
## Dashboard 图表约定
|
侧边栏的运行版本和短提交号来自后端 `/health`。源码运行通常显示 `dev`/`unknown`;CI 构建的安装包和 Docker 镜像会注入版本信息。
|
||||||
|
|
||||||
Dashboard 的营收趋势柱状图使用统一的品牌蓝 `#0094f7` 表示同一指标序列,日期之间
|
|
||||||
只通过柱高区分营收,不使用不同颜色表达不同类别。饼图使用中心汇总值、图例和悬浮提示
|
|
||||||
展示明细;悬停扇区会轻微放大。图表是展示型组件,点击或键盘焦点不会显示浏览器默认
|
|
||||||
的粗蓝色 SVG 焦点框,避免被误解为业务选中状态。
|
|
||||||
|
|
||||||
## 路由
|
## 路由
|
||||||
|
|
||||||
应用使用 `window.history.pushState` 做 tab 导航,路径包括 `/app/dashboard`、`/app/accounts`、
|
路由使用 `window.history.pushState`,包括 `/app/dashboard`、`/app/accounts`、`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、`/app/notifications` 与管理员可见的 `/app/settings`。未登录时显示会话表单;当 `/api/v1/session` 表示系统未初始化时,显示首次初始化表单。后端对非 API 的 GET 请求回退到 `index.html`,支持深链刷新。
|
||||||
`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、
|
|
||||||
`/app/notifications` 和管理员可见的 `/app/settings`。
|
|
||||||
未登录时显示登录表单(客户端状态,非独立路由)。当后端 `/verify` 返回
|
|
||||||
`initialized: false` 时,显示首次初始化表单;用户确认不少于 8 个字符的管理员密码后,
|
|
||||||
前端调用 `/initialize` 创建 `admin` 并使用返回的会话自动进入系统。后端 SPA catch-all
|
|
||||||
对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
|
|
||||||
|
|
||||||
## 测试
|
## 测试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm test # 前端单元测试
|
npm test -- --run
|
||||||
npm run typecheck # TypeScript 类型检查
|
npm run typecheck
|
||||||
npm run build # 构建并更新 Go 嵌入资源
|
npm run comments:check
|
||||||
|
npm run build
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
/** ErrorBoundaryProps 描述顶层错误边界可恢复的页面子树。 */
|
||||||
|
interface ErrorBoundaryProps {
|
||||||
|
/** children 是由错误边界保护的整个应用路由树。 */
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ErrorBoundaryState 只记录渲染期故障,避免把错误对象或敏感响应写入浏览器状态。 */
|
||||||
|
interface ErrorBoundaryState {
|
||||||
|
/** hasError 表示应用子树是否因渲染错误而被隔离。 */
|
||||||
|
hasError: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** AppErrorBoundary 隔离未捕获的页面渲染错误,并提供不依赖网络请求的恢复入口。 */
|
||||||
|
export class AppErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||||
|
/** state 保存当前子树的错误隔离状态。 */
|
||||||
|
public state: ErrorBoundaryState = { hasError: false };
|
||||||
|
|
||||||
|
/** getDerivedStateFromError 在 React 捕获到子树异常时切换到静态恢复视图。 */
|
||||||
|
public static getDerivedStateFromError(): ErrorBoundaryState {
|
||||||
|
return { hasError: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** handleReload 由用户点击触发,使用完整刷新重新建立会话和路由运行环境。 */
|
||||||
|
private handleReload = (): void => {
|
||||||
|
window.location.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** render 在正常路径渲染应用子树;捕获异常后只暴露安全的恢复界面。 */
|
||||||
|
public render(): React.ReactNode {
|
||||||
|
// hasError 表示当前是否需要显示错误隔离界面。
|
||||||
|
const { hasError } = this.state;
|
||||||
|
// children 是未发生渲染错误时应继续展示的应用路由树。
|
||||||
|
const { children } = this.props;
|
||||||
|
if (!hasError) return children;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex min-h-screen items-center justify-center bg-canvas p-6 text-ink">
|
||||||
|
<section className="max-w-md text-center">
|
||||||
|
<h1 className="text-xl font-semibold">页面暂时无法显示</h1>
|
||||||
|
<button className="ios-btn-primary mt-6 px-4 py-2" type="button" onClick={this.handleReload}>
|
||||||
|
重新加载
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { AccountTaskRunResponseEnvelope,AccountTaskSettings,AccountTaskSettingsResponse } from './api';
|
||||||
|
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||||
|
|
||||||
|
/** 获取指定账号的自动评价与自动擦亮设置。 */
|
||||||
|
export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => get(`/api/v1/account-tasks/${accountID}`, undefined, options);
|
||||||
|
|
||||||
|
/** 保存指定账号的自动评价与自动擦亮设置。 */
|
||||||
|
export const updateAccountTaskSettings = async (accountID: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> => put(`/api/v1/account-tasks/${accountID}`, settings, options);
|
||||||
|
|
||||||
|
/** 立即发起账号级计划任务,并使用较长超时覆盖平台执行窗口。 */
|
||||||
|
export const runAccountTask = async (accountID: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> => post(`/api/v1/account-tasks/${accountID}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||||
|
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts';
|
||||||
|
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
|
||||||
|
import { useAccountAutomation } from './accountAutomationHooks';
|
||||||
|
|
||||||
|
vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
|
||||||
|
getAccountTaskSettings: vi.fn(),
|
||||||
|
runAccountTask: vi.fn(),
|
||||||
|
updateAccountTaskSettings: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// getSettingsMock 是读取账号任务设置的可控请求替身。
|
||||||
|
const getSettingsMock = vi.mocked(getAccountTaskSettings);
|
||||||
|
// runTaskMock 是立即执行账号任务的可控请求替身。
|
||||||
|
const runTaskMock = vi.mocked(runAccountTask);
|
||||||
|
// updateSettingsMock 是保存账号任务设置的可控请求替身。
|
||||||
|
const updateSettingsMock = vi.mocked(updateAccountTaskSettings);
|
||||||
|
|
||||||
|
// accountFixture 是 Hook 测试使用的启用账号对象。
|
||||||
|
const accountFixture: AccountDetail = { id: 'account-1', enabled: true, auto_confirm: false, auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' };
|
||||||
|
|
||||||
|
// settingsFixture 是账号任务接口返回的完整设置对象。
|
||||||
|
const settingsFixture: AccountTaskSettingsResponse = { account_id: 'account-1', auto_rate_enabled: true, rate_content: '已保存文案', auto_polish_enabled: true, polish_time: '04:00', last_rate_scan_at: 0, last_polish_date: '', last_polish_at: 0 };
|
||||||
|
|
||||||
|
// onSavedFixture 是保存或执行成功后的页面同步回调替身。
|
||||||
|
const onSavedFixture = vi.fn();
|
||||||
|
|
||||||
|
// renderAutomationHook 是渲染账号任务 Hook 的具名回调。
|
||||||
|
const renderAutomationHook = () => useAccountAutomation({ account: accountFixture, onSaved: onSavedFixture });
|
||||||
|
|
||||||
|
describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请求与动作状态。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置所有 API 替身和页面回调。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
getSettingsMock.mockResolvedValue(settingsFixture);
|
||||||
|
updateSettingsMock.mockResolvedValue(settingsFixture);
|
||||||
|
runTaskMock.mockResolvedValue({ success: true, summary: { task_type: 'auto_rate', found: 1, success: 1, failed: 0, skipped: 0 } });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('加载设置后可以保存和立即执行任务', /* 当前回调验证成功加载、保存和执行路径。 */ async () => {
|
||||||
|
// hook 是账号任务 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(renderAutomationHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待首次设置请求完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.form).toEqual(settingsFixture);
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// saveAction 执行设置保存动作。
|
||||||
|
async () => hook.result.current.save(),
|
||||||
|
);
|
||||||
|
expect(updateSettingsMock).toHaveBeenCalledWith('account-1', settingsFixture, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||||
|
expect(onSavedFixture).toHaveBeenCalledWith(settingsFixture);
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// runAction 执行自动擦亮任务。
|
||||||
|
async () => hook.result.current.run('auto_polish'),
|
||||||
|
);
|
||||||
|
expect(runTaskMock).toHaveBeenCalledWith('account-1', 'auto_polish', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||||
|
expect(hook.result.current.summary).toMatchObject({ success: 1 });
|
||||||
|
expect(hook.result.current.error).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('保存失败后可通过 retry 重试并清除错误', /* 当前回调验证失败状态和安全重试路径。 */ async () => {
|
||||||
|
// hook 是保存失败场景下的账号任务 Hook 渲染结果。
|
||||||
|
const hook = renderHook(renderAutomationHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待失败场景的首次设置请求完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
updateSettingsMock.mockRejectedValueOnce(new Error('保存失败'));
|
||||||
|
await act(
|
||||||
|
// saveAction 执行预期失败的设置保存动作。
|
||||||
|
async () => hook.result.current.save(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.error).toBe('保存失败');
|
||||||
|
expect(hook.result.current.retryAvailable).toBe(true);
|
||||||
|
await act(
|
||||||
|
// retryAction 触发最近一次保存动作的重试。
|
||||||
|
async () => hook.result.current.retry(),
|
||||||
|
);
|
||||||
|
expect(updateSettingsMock).toHaveBeenCalledTimes(2);
|
||||||
|
expect(hook.result.current.error).toBe('');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('禁用账号不会发起立即执行请求', /* 当前回调验证账号运行门禁。 */ async () => {
|
||||||
|
// disabledAccount 是不允许执行账号级计划任务的账号对象。
|
||||||
|
const disabledAccount = { ...accountFixture, enabled: false };
|
||||||
|
// renderDisabledHook 是禁用账号 Hook 的渲染回调。
|
||||||
|
const renderDisabledHook = () => useAccountAutomation({ account: disabledAccount, onSaved: onSavedFixture });
|
||||||
|
// hook 是禁用账号 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(renderDisabledHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待禁用账号的设置读取完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// runAction 验证禁用账号不会提交自动评价任务。
|
||||||
|
async () => hook.result.current.run('auto_rate'),
|
||||||
|
);
|
||||||
|
expect(runTaskMock).not.toHaveBeenCalled();
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('加载设置失败时展示业务错误', /* 当前回调验证首次读取失败分支。 */ async () => {
|
||||||
|
getSettingsMock.mockRejectedValueOnce(new Error('读取失败'));
|
||||||
|
// hook 是读取失败场景下的账号任务 Hook 渲染结果。
|
||||||
|
const hook = renderHook(renderAutomationHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待读取失败状态完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.error).toBe('读取失败');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('执行失败后可通过 retry 重试', /* 当前回调验证执行失败与重试动作。 */ async () => {
|
||||||
|
// hook 是执行失败场景下的账号任务 Hook 渲染结果。
|
||||||
|
const hook = renderHook(renderAutomationHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待首次设置请求完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
runTaskMock.mockRejectedValueOnce(new Error('执行失败'));
|
||||||
|
await act(
|
||||||
|
// runAction 执行预期失败的账号任务。
|
||||||
|
async () => hook.result.current.run('auto_rate'),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.error).toBe('执行失败');
|
||||||
|
expect(hook.result.current.retryAvailable).toBe(true);
|
||||||
|
await act(
|
||||||
|
// retryAction 触发最近一次执行动作的重试。
|
||||||
|
async () => hook.result.current.retry(),
|
||||||
|
);
|
||||||
|
expect(runTaskMock).toHaveBeenCalledTimes(2);
|
||||||
|
expect(hook.result.current.error).toBe('');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('保存进行中时忽略重复保存动作', /* 当前回调验证账号任务保存的并发门禁。 */ async () => {
|
||||||
|
// resolveUpdate 是延迟保存请求的完成控制器。
|
||||||
|
let resolveUpdate: (value: AccountTaskSettingsResponse) => void = () => undefined;
|
||||||
|
// pendingUpdate 是保持 saving 状态的保存请求 Promise。
|
||||||
|
const pendingUpdate = new Promise<AccountTaskSettingsResponse>(/* updateExecutor 保存延迟 Promise 的完成函数。 */ resolve => { resolveUpdate = resolve; });
|
||||||
|
updateSettingsMock.mockReturnValueOnce(pendingUpdate);
|
||||||
|
// hook 是保存并发门禁场景的账号任务 Hook 渲染结果。
|
||||||
|
const hook = renderHook(renderAutomationHook);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待任务设置初始加载完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
// firstSave 是保持进行中的首次保存动作。
|
||||||
|
const firstSave = hook.result.current.save();
|
||||||
|
await waitFor(
|
||||||
|
// savingAssertion 等待保存状态打开。
|
||||||
|
() => expect(hook.result.current.saving).toBe(true),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// duplicateSaveAction 触发重复保存并验证门禁。
|
||||||
|
async () => hook.result.current.save(),
|
||||||
|
);
|
||||||
|
expect(updateSettingsMock).toHaveBeenCalledTimes(1);
|
||||||
|
resolveUpdate(settingsFixture);
|
||||||
|
await act(
|
||||||
|
// resolveAction 完成首次保存请求并收口状态。
|
||||||
|
async () => firstSave,
|
||||||
|
);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { useCallback,useEffect,useRef,useState } from 'react';
|
||||||
|
import type { AccountTaskSettings,AccountTaskSummary } from './api';
|
||||||
|
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
|
||||||
|
import { accountTaskErrorMessage,buildAccountTaskDefaults,canStartAccountTask,isAccountTaskAbortError,isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||||
|
import type { AccountAutomationOptions,AccountAutomationState,AccountTaskType } from './accountAutomationTypes';
|
||||||
|
|
||||||
|
/** AccountAutomation Hook 的完整返回值。 */
|
||||||
|
export type UseAccountAutomationResult = AccountAutomationState & {
|
||||||
|
/** 更新任务设置草稿。 */
|
||||||
|
setForm: React.Dispatch<React.SetStateAction<AccountTaskSettings>>;
|
||||||
|
/** 保存任务设置。 */
|
||||||
|
save: () => Promise<void>;
|
||||||
|
/** 立即运行指定任务。 */
|
||||||
|
run: (taskType: AccountTaskType) => Promise<void>;
|
||||||
|
/** 重试最近一次失败动作。 */
|
||||||
|
retry: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 管理账号自动评价和自动擦亮的设置、执行、取消与重试。 */
|
||||||
|
export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOptions): UseAccountAutomationResult => {
|
||||||
|
// form 保存当前账号任务设置草稿。
|
||||||
|
const [form, setForm] = useState<AccountTaskSettings>(/* 当前回调处理用户交互或异步状态变化。 */ () => buildAccountTaskDefaults(account));
|
||||||
|
// loading 表示账号任务设置是否正在读取。
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
// saving 表示任务设置是否正在保存。
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
// running 保存当前执行中的任务类型。
|
||||||
|
const [running, setRunning] = useState<'' | AccountTaskType>('');
|
||||||
|
// error 保存最近一次任务操作错误。
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
// summary 保存最近一次任务执行统计。
|
||||||
|
const [summary, setSummary] = useState<AccountTaskSummary | null>(null);
|
||||||
|
// retryAction 保存最近一次失败动作。
|
||||||
|
const [retryAction, setRetryAction] = useState<(() => Promise<void>) | null>(null);
|
||||||
|
// requestSequence 隔离账号切换后的旧响应。
|
||||||
|
const requestSequence = useRef(0);
|
||||||
|
// requestController 保存当前账号任务请求控制器。
|
||||||
|
const requestController = useRef<AbortController | null>(null);
|
||||||
|
|
||||||
|
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||||
|
// sequence 请求序号。
|
||||||
|
const sequence = ++requestSequence.current;
|
||||||
|
requestController.current?.abort();
|
||||||
|
// controller 请求取消控制器。
|
||||||
|
const controller = new AbortController();
|
||||||
|
requestController.current = controller;
|
||||||
|
setForm(buildAccountTaskDefaults(account));
|
||||||
|
setSummary(null);
|
||||||
|
setError('');
|
||||||
|
setSaving(false);
|
||||||
|
setRunning('');
|
||||||
|
setRetryAction(null);
|
||||||
|
setLoading(true);
|
||||||
|
getAccountTaskSettings(account.id, { signal: controller.signal }).then(/* 当前回调处理异步操作结果。 */ settings => {
|
||||||
|
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
|
||||||
|
setForm(settings);
|
||||||
|
}).catch(/* 当前回调处理异步操作结果。 */ loadError => {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(loadError)) setError(accountTaskErrorMessage(loadError, '加载任务设置失败'));
|
||||||
|
}).finally(/* 当前回调处理异步操作结果。 */ () => {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setLoading(false);
|
||||||
|
});
|
||||||
|
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
|
||||||
|
}, [account.id]);
|
||||||
|
|
||||||
|
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => requestController.current?.abort(), []);
|
||||||
|
|
||||||
|
/** 保存任务设置并在成功后同步账号列表。 */
|
||||||
|
const save = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!canStartAccountTask(saving, running)) return;
|
||||||
|
// sequence 请求序号。
|
||||||
|
const sequence = ++requestSequence.current;
|
||||||
|
requestController.current?.abort();
|
||||||
|
// controller 请求取消控制器。
|
||||||
|
const controller = new AbortController();
|
||||||
|
requestController.current = controller;
|
||||||
|
setSaving(true);
|
||||||
|
setError('');
|
||||||
|
setRetryAction(null);
|
||||||
|
try {
|
||||||
|
// stored 已保存数据。
|
||||||
|
const stored = await updateAccountTaskSettings(account.id, form, { signal: controller.signal });
|
||||||
|
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
|
||||||
|
setForm(stored);
|
||||||
|
onSaved(stored);
|
||||||
|
} catch (/* saveError 表示保存错误。 */ saveError) {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(saveError)) {
|
||||||
|
setError(accountTaskErrorMessage(saveError, '保存失败'));
|
||||||
|
setRetryAction(/* 当前回调处理用户交互或异步状态变化。 */ () => save);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setSaving(false);
|
||||||
|
}
|
||||||
|
}, [account.id, form, onSaved, running, saving]);
|
||||||
|
|
||||||
|
/** 保存设置后立即执行指定账号任务并刷新结果。 */
|
||||||
|
const run = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (taskType: AccountTaskType): Promise<void> => {
|
||||||
|
if (!canStartAccountTask(saving, running) || !account.enabled) return;
|
||||||
|
// sequence 请求序号。
|
||||||
|
const sequence = ++requestSequence.current;
|
||||||
|
requestController.current?.abort();
|
||||||
|
// controller 请求取消控制器。
|
||||||
|
const controller = new AbortController();
|
||||||
|
requestController.current = controller;
|
||||||
|
setRunning(taskType);
|
||||||
|
setError('');
|
||||||
|
setSummary(null);
|
||||||
|
setRetryAction(null);
|
||||||
|
try {
|
||||||
|
await updateAccountTaskSettings(account.id, form, { signal: controller.signal });
|
||||||
|
// result 处理结果。
|
||||||
|
const result = await runAccountTask(account.id, taskType, { signal: controller.signal });
|
||||||
|
// stored 已保存数据。
|
||||||
|
const stored = await getAccountTaskSettings(account.id, { signal: controller.signal });
|
||||||
|
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
|
||||||
|
setSummary(result.summary);
|
||||||
|
setForm(stored);
|
||||||
|
onSaved(stored);
|
||||||
|
} catch (/* runError 表示执行错误。 */ runError) {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(runError)) {
|
||||||
|
setError(accountTaskErrorMessage(runError, '任务执行失败'));
|
||||||
|
setRetryAction(/* 当前回调处理用户交互或异步状态变化。 */ () => /* 当前回调处理用户交互或异步状态变化。 */ () => run(taskType));
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setRunning('');
|
||||||
|
}
|
||||||
|
}, [account.enabled, account.id, form, onSaved, running, saving]);
|
||||||
|
|
||||||
|
/** 重试最近一次保存或执行动作。 */
|
||||||
|
const retry = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (retryAction) await retryAction();
|
||||||
|
}, [retryAction]);
|
||||||
|
|
||||||
|
return { form, loading, saving, running, summary, error, retryAvailable: retryAction !== null, setForm, save, run, retry };
|
||||||
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { expect,test } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||||
|
import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState';
|
||||||
|
|
||||||
|
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
|
||||||
|
const accountFixture: AccountDetail = {
|
||||||
|
id: 'a1', enabled: true, auto_confirm: false, auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00',
|
||||||
|
};
|
||||||
|
|
||||||
|
test('账号任务默认设置继承账号配置并保持安全文案',
|
||||||
|
// 默认值测试验证新账号没有文案时仍使用明确的中文好评内容。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountTaskDefaults(accountFixture)).toMatchObject({ account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快', polish_time: '03:00' });
|
||||||
|
expect(buildAccountTaskDefaults({ ...accountFixture, rate_content: '' }).rate_content).toBe('不错的买家,交易愉快');
|
||||||
|
});
|
||||||
|
test('账号任务阻断重复提交并拒绝过期响应',
|
||||||
|
// 动作边界测试验证保存或执行中不会重复发起任务,账号切换后的旧响应不能写入。
|
||||||
|
() => {
|
||||||
|
// controller 请求取消控制器。
|
||||||
|
const controller = new AbortController();
|
||||||
|
expect(canStartAccountTask(false, '')).toBe(true);
|
||||||
|
expect(canStartAccountTask(true, '')).toBe(false);
|
||||||
|
expect(canStartAccountTask(false, 'auto_rate')).toBe(false);
|
||||||
|
expect(isCurrentAccountTaskRequest(4, 4, controller.signal)).toBe(true);
|
||||||
|
expect(isCurrentAccountTaskRequest(3, 4, controller.signal)).toBe(false);
|
||||||
|
controller.abort();
|
||||||
|
expect(isCurrentAccountTaskRequest(4, 4, controller.signal)).toBe(false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import type { AccountDetail,AccountTaskSettings } from './api';
|
||||||
|
import type { AccountTaskType } from './accountAutomationTypes';
|
||||||
|
|
||||||
|
/** 根据账号详情创建任务设置初始草稿。 */
|
||||||
|
export const buildAccountTaskDefaults = (account: AccountDetail): AccountTaskSettings => ({
|
||||||
|
account_id: account.id,
|
||||||
|
auto_rate_enabled: account.auto_rate_enabled === true,
|
||||||
|
rate_content: account.rate_content || '不错的买家,交易愉快',
|
||||||
|
auto_polish_enabled: account.auto_polish_enabled === true,
|
||||||
|
polish_time: account.polish_time || '03:00',
|
||||||
|
last_rate_scan_at: account.last_rate_scan_at,
|
||||||
|
last_polish_date: account.last_polish_date,
|
||||||
|
last_polish_at: account.last_polish_at,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 判断账号任务响应是否仍属于当前编辑账号和请求代次。 */
|
||||||
|
export const isCurrentAccountTaskRequest = (currentSequence: number, requestSequence: number, signal: AbortSignal): boolean => (
|
||||||
|
currentSequence === requestSequence && !signal.aborted
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 统一提取账号任务请求错误文本。 */
|
||||||
|
export const accountTaskErrorMessage = (error: unknown, fallback: string): string => error instanceof Error ? error.message : fallback;
|
||||||
|
|
||||||
|
/** 判断错误是否来自请求主动取消。 */
|
||||||
|
export const isAccountTaskAbortError = (error: unknown): boolean => error instanceof Error && error.message === '请求已取消';
|
||||||
|
|
||||||
|
/** 判断账号任务动作是否允许重复提交。 */
|
||||||
|
export const canStartAccountTask = (saving: boolean, running: '' | AccountTaskType): boolean => !saving && running === '';
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { AccountDetail,AccountTaskSettings,AccountTaskSummary } from './api';
|
||||||
|
|
||||||
|
/** 账号任务类型。 */
|
||||||
|
export type AccountTaskType = 'auto_rate' | 'auto_polish';
|
||||||
|
|
||||||
|
/** AccountAutomation Hook 的输入参数。 */
|
||||||
|
export type AccountAutomationOptions = {
|
||||||
|
/** 当前编辑的账号。 */
|
||||||
|
account: AccountDetail;
|
||||||
|
/** 保存成功后的页面同步回调。 */
|
||||||
|
onSaved: (settings: AccountTaskSettings) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** AccountAutomation Hook 的状态和动作。 */
|
||||||
|
export type AccountAutomationState = {
|
||||||
|
/** 账号任务设置草稿。 */
|
||||||
|
form: AccountTaskSettings;
|
||||||
|
/** 初始设置加载状态。 */
|
||||||
|
loading: boolean;
|
||||||
|
/** 保存设置状态。 */
|
||||||
|
saving: boolean;
|
||||||
|
/** 当前运行中的任务类型。 */
|
||||||
|
running: '' | AccountTaskType;
|
||||||
|
/** 最近一次任务统计。 */
|
||||||
|
summary: AccountTaskSummary | null;
|
||||||
|
/** 当前错误信息。 */
|
||||||
|
error: string;
|
||||||
|
/** 是否存在可重试动作。 */
|
||||||
|
retryAvailable: boolean;
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { describe,expect,test } from 'vitest';
|
||||||
|
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||||
|
|
||||||
|
describe('notification binding save guard', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
test('does not overwrite bindings when loading failed', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
expect(shouldSaveNotificationBindings(false, true)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not write unchanged bindings', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
expect(shouldSaveNotificationBindings(true, false)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writes an explicitly changed, successfully loaded selection', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
expect(shouldSaveNotificationBindings(true, true)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
+1
@@ -1 +1,2 @@
|
|||||||
|
// shouldSaveNotificationBindings 判断通知绑定是否需要保存。
|
||||||
export const shouldSaveNotificationBindings = (loaded: boolean, dirty: boolean): boolean => loaded && dirty;
|
export const shouldSaveNotificationBindings = (loaded: boolean, dirty: boolean): boolean => loaded && dirty;
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
import {
|
||||||
|
AIReplySettings,
|
||||||
|
AIReplySettingsResponse,
|
||||||
|
AccountBindingsResponse,
|
||||||
|
AccountDetail,AccountSummaryResponse,
|
||||||
|
AccountTaskRunResponseEnvelope,
|
||||||
|
AccountTaskSettings,
|
||||||
|
AccountTaskSettingsResponse,
|
||||||
|
CookieProfileResponse,
|
||||||
|
CookieSettingsResponse,
|
||||||
|
NotificationChannel,
|
||||||
|
NotificationChannelResponse,
|
||||||
|
NotificationEventType,
|
||||||
|
OperationResponse,
|
||||||
|
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
|
||||||
|
} from '../../../shared/api-contract/accounts';
|
||||||
|
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||||
|
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
|
||||||
|
export type * from '../../../shared/api-contract/accounts';
|
||||||
|
// Accounts
|
||||||
|
// addAccount 新增账号。
|
||||||
|
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||||
|
return post('/api/v1/accounts', { id, value, login_method: loginMethod });
|
||||||
|
};
|
||||||
|
|
||||||
|
// accountAvatarURL 生成账号头像地址。
|
||||||
|
const accountAvatarURL = (item: AccountSummaryResponse, version: string): string => {
|
||||||
|
// raw 原始值,用于当前 API 处理流程。
|
||||||
|
const raw = item.avatar_url || '';
|
||||||
|
if (!raw) return '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// url 解析后的地址,用于当前 API 处理流程。
|
||||||
|
const url = new URL(raw, window.location.origin);
|
||||||
|
if (url.hostname.endsWith('alicdn.com')) {
|
||||||
|
url.searchParams.set('_v', version);
|
||||||
|
}
|
||||||
|
return url.toString();
|
||||||
|
} catch {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// getAccountDetails 读取账号详情。
|
||||||
|
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
|
||||||
|
// data 数据,用于当前 API 处理流程。
|
||||||
|
const response = await get<unknown>('/api/v1/accounts/details', undefined, options);
|
||||||
|
// data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。
|
||||||
|
const data = collectionFrom<AccountSummaryResponse>(response, ['data', 'accounts', 'details']);
|
||||||
|
// avatarVersion 头像缓存版本,用于当前 API 处理流程。
|
||||||
|
const avatarVersion = Date.now().toString();
|
||||||
|
return data.map(/* 当前回调用于处理集合元素或接口响应。 */ item => ({
|
||||||
|
id: item.id,
|
||||||
|
cookie_configured: item.has_cookie === true,
|
||||||
|
enabled: item.enabled,
|
||||||
|
auto_confirm: item.auto_confirm,
|
||||||
|
remark: item.remark,
|
||||||
|
pause_duration: item.pause_duration,
|
||||||
|
paused_until: Number(item.paused_until || 0),
|
||||||
|
paused: item.paused === true,
|
||||||
|
username: item.username || '',
|
||||||
|
login_password_configured: undefined,
|
||||||
|
show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true',
|
||||||
|
nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`,
|
||||||
|
avatar_url: accountAvatarURL(item, avatarVersion),
|
||||||
|
profile_error: item.profile_error || '',
|
||||||
|
ai_enabled: false,
|
||||||
|
auto_rate_enabled: item.auto_rate_enabled,
|
||||||
|
rate_content: item.rate_content || '不错的买家,交易愉快',
|
||||||
|
auto_polish_enabled: item.auto_polish_enabled,
|
||||||
|
polish_time: item.polish_time || '03:00',
|
||||||
|
last_rate_scan_at: Number(item.last_rate_scan_at || 0),
|
||||||
|
last_polish_date: item.last_polish_date || '',
|
||||||
|
last_polish_at: Number(item.last_polish_at || 0),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// getAccountTaskSettings 读取账号计划任务设置。
|
||||||
|
export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||||
|
get(`/api/v1/account-tasks/${id}`, undefined, options);
|
||||||
|
|
||||||
|
// updateAccountTaskSettings 更新账号计划任务设置。
|
||||||
|
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
|
||||||
|
put(`/api/v1/account-tasks/${id}`, settings, options);
|
||||||
|
|
||||||
|
// runAccountTask 立即执行账号计划任务。
|
||||||
|
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> =>
|
||||||
|
post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options });
|
||||||
|
|
||||||
|
|
||||||
|
export interface AccountRuntimeStatus {
|
||||||
|
/** state 表示状态。 */ state: NonNullable<AccountDetail['runtime_state']>;
|
||||||
|
/** message 表示消息数据。 */ message?: string;
|
||||||
|
/** connected 表示连接状态。 */ connected: boolean;
|
||||||
|
/** failures 表示失败次数。 */ failures: number;
|
||||||
|
/** updated_at 表示最后更新时间。 */ updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getAccountRuntimeStatuses 读取账号运行状态。
|
||||||
|
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, AccountRuntimeStatus>> => {
|
||||||
|
const response = await get<unknown>('/api/v1/accounts/runtime-status', undefined, options);
|
||||||
|
// statuses 是兼容直接映射、statuses 包裹和 null 的运行状态索引。
|
||||||
|
const statuses = objectFrom<Record<string, AccountRuntimeStatus>>(response, ['statuses', 'data', 'result']);
|
||||||
|
return statuses || {};
|
||||||
|
};
|
||||||
|
|
||||||
|
// generateQRLogin 生成二维码登录会话。
|
||||||
|
export const generateQRLogin = async (options?: RequestControlOptions): Promise<QRLoginGenerateResponse> => {
|
||||||
|
// 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。
|
||||||
|
return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
|
||||||
|
};
|
||||||
|
|
||||||
|
// checkQRLoginStatus 查询二维码登录状态。
|
||||||
|
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<QRLoginStatusResponse> => {
|
||||||
|
return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||||
|
};
|
||||||
|
|
||||||
|
// completeQRVerification 完成二维码登录验证。
|
||||||
|
export const completeQRVerification = async (
|
||||||
|
sessionId: string,
|
||||||
|
targetAccountId?: string,
|
||||||
|
): Promise<QRLoginVerificationResponse> => {
|
||||||
|
return post(`/api/v1/qr-login/complete-verification/${sessionId}`, {
|
||||||
|
target_account_id: targetAccountId || '',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// updateAccountStatus 更新账号状态。
|
||||||
|
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/status`, { enabled });
|
||||||
|
};
|
||||||
|
|
||||||
|
// deleteAccount 删除账号。
|
||||||
|
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
|
||||||
|
return del(`/api/v1/accounts/${id}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateAccountRemark 更新账号备注。
|
||||||
|
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/remark`, { remark });
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateAccountAutoConfirm 更新账号自动确认设置。
|
||||||
|
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateAccountPauseDuration 更新账号暂停时长。
|
||||||
|
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateAccountCookie 更新账号登录凭证。
|
||||||
|
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod });
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface AccountSettingsUpdate {
|
||||||
|
/** cookie 表示登录凭证。 */ cookie?: string;
|
||||||
|
/** remark 表示备注。 */ remark?: string;
|
||||||
|
/** auto_confirm 表示自动确认状态。 */ auto_confirm?: boolean;
|
||||||
|
/** pause_duration 表示暂停时长。 */ pause_duration?: number;
|
||||||
|
/** username 表示用户名。 */ username?: string;
|
||||||
|
/** login_password 表示登录密码。 */ login_password?: string;
|
||||||
|
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
|
||||||
|
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||||
|
/** channel_ids 表示通知渠道标识列表。 */ channel_ids?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateAccountSettings 更新账号设置。
|
||||||
|
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/settings`, data, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface LongLoginSettings {
|
||||||
|
/** can_open_long_login 表示是否允许开启长期登录。 */ can_open_long_login: boolean;
|
||||||
|
/** enabled 表示启用状态。 */ enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getLongLoginSettings 读取长期登录设置。
|
||||||
|
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||||
|
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// setLongLoginSettings 设置长期登录开关。
|
||||||
|
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface PasswordLoginStartResponse {
|
||||||
|
/** success 表示是否成功。 */ success: boolean;
|
||||||
|
/** session_id 表示会话标识。 */ session_id?: string;
|
||||||
|
/** status 表示状态值。 */ status?: 'processing' | 'failed';
|
||||||
|
/** message 表示消息数据。 */ message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PasswordLoginStatusResponse {
|
||||||
|
/** status 表示状态值。 */ status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error';
|
||||||
|
/** message 表示消息数据。 */ message?: string;
|
||||||
|
/** account_id 表示账号标识。 */ account_id?: string;
|
||||||
|
/** is_new_account 表示是否为新账号。 */ is_new_account?: boolean;
|
||||||
|
/** cookie_count 表示登录凭证数量。 */ cookie_count?: number;
|
||||||
|
/** verification_url 表示验证地址。 */ verification_url?: string;
|
||||||
|
/** screenshot_path 表示验证截图路径。 */ screenshot_path?: string;
|
||||||
|
/** qr_code_url 表示二维码地址。 */ qr_code_url?: string;
|
||||||
|
/** error 保存密码登录流程返回的失败说明;前端只用于界面提示,不应记录或序列化登录凭证。 */ error?: string;
|
||||||
|
/** reason 表示失败原因。 */ reason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// passwordLogin 执行密码登录。
|
||||||
|
export const passwordLogin = async (data: {
|
||||||
|
/** account_id 表示账号标识。 */ account_id: string;
|
||||||
|
/** account 表示账号。 */ account: string;
|
||||||
|
/** password 表示密码。 */ password: string;
|
||||||
|
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||||
|
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
|
||||||
|
return post('/api/v1/password-login', data, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// checkPasswordLoginStatus 查询密码登录状态。
|
||||||
|
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
|
||||||
|
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||||
|
};
|
||||||
|
|
||||||
|
// cancelPasswordLogin 取消密码登录。
|
||||||
|
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||||
|
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// refreshAccountProfile 刷新账号资料。
|
||||||
|
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
|
||||||
|
return post(`/api/v1/accounts/${id}/refresh-profile`, {});
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateAccountLoginInfo 更新账号登录信息。
|
||||||
|
export const updateAccountLoginInfo = async (id: string, data: {
|
||||||
|
/** username 表示用户名。 */ username?: string;
|
||||||
|
/** login_password 表示登录密码。 */ login_password?: string;
|
||||||
|
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
|
||||||
|
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
|
||||||
|
}): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/accounts/${id}/login-info`, data);
|
||||||
|
};
|
||||||
|
|
||||||
|
// getAllAISettings 读取全部人工智能设置。
|
||||||
|
export const getAllAISettings = async (options?: RequestControlOptions): Promise<Record<string, AIReplySettings>> => {
|
||||||
|
const response = await get<unknown>('/api/v1/settings/ai-reply', undefined, options);
|
||||||
|
// settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。
|
||||||
|
return objectFrom<Record<string, AIReplySettings>>(response, ['settings', 'data', 'result']) || {};
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// getAccountAISettings 读取账号人工智能设置。
|
||||||
|
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
|
||||||
|
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateAccountAISettings 更新账号人工智能设置。
|
||||||
|
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||||
|
// payload 请求载荷,用于当前 API 处理流程。
|
||||||
|
const payload = {
|
||||||
|
ai_enabled: settings.ai_enabled ?? false,
|
||||||
|
max_discount_percent: settings.max_discount_percent ?? 10,
|
||||||
|
max_discount_amount: settings.max_discount_amount ?? 100,
|
||||||
|
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
|
||||||
|
custom_prompts: settings.custom_prompts ?? ''
|
||||||
|
};
|
||||||
|
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// parseNotificationEventTypes 解析通知事件类型。
|
||||||
|
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||||
|
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
|
||||||
|
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||||
|
try {
|
||||||
|
// parsed 转换后的数值,用于当前 API 处理流程。
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
|
||||||
|
} catch {
|
||||||
|
// fall back to legacy comma/semicolon separated values
|
||||||
|
}
|
||||||
|
return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// getNotificationChannels 读取通知渠道。
|
||||||
|
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => {
|
||||||
|
// result 接口响应结果,用于当前 API 处理流程。
|
||||||
|
const result = await get<unknown>('/api/v1/notifications/channels', undefined, options);
|
||||||
|
// channels 通知渠道列表,用于当前 API 处理流程。
|
||||||
|
const channels = collectionFrom<NotificationChannelResponse>(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => {
|
||||||
|
// parsedConfig 解析后的通知配置,用于当前 API 处理流程。
|
||||||
|
let parsedConfig;
|
||||||
|
try {
|
||||||
|
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
|
||||||
|
} catch {
|
||||||
|
parsedConfig = {};
|
||||||
|
}
|
||||||
|
// normalizedType 是兼容旧渠道别名后的前端渠道类型。
|
||||||
|
const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type'];
|
||||||
|
return {
|
||||||
|
id: String(item.id),
|
||||||
|
name: item.name,
|
||||||
|
type: normalizedType,
|
||||||
|
config: parsedConfig,
|
||||||
|
event_types: parseNotificationEventTypes(item.event_types),
|
||||||
|
enabled: item.enabled,
|
||||||
|
created_at: item.created_at,
|
||||||
|
updated_at: item.updated_at,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { success: true, data: channels };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 账号 ↔ 渠道 绑定(覆盖式)
|
||||||
|
export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise<number[]> => {
|
||||||
|
// response 是兼容直接绑定对象、data 包裹和 null 的通知绑定响应。
|
||||||
|
const response = await get<unknown>(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options);
|
||||||
|
// result 是去除历史包裹后的账号通知绑定对象。
|
||||||
|
const result = objectFrom<Partial<AccountBindingsResponse>>(response, ['data', 'result']) || {};
|
||||||
|
return Array.isArray(result.channel_ids) ? result.channel_ids : [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { Bot,Loader2,Save,Settings,X } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import type { AccountDetail,AIReplySettings } from '../api';
|
||||||
|
|
||||||
|
// AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。
|
||||||
|
export interface AccountAISettingsModalProps {
|
||||||
|
// account 是当前正在编辑 AI 设置的账号。
|
||||||
|
account: AccountDetail;
|
||||||
|
// settings 是账号 AI 设置编辑草稿。
|
||||||
|
settings: AIReplySettings;
|
||||||
|
// saving 表示 AI 设置保存请求是否正在执行。
|
||||||
|
saving: boolean;
|
||||||
|
// onChange 更新 AI 设置草稿。
|
||||||
|
onChange: (settings: AIReplySettings) => void;
|
||||||
|
// onClose 关闭 AI 设置弹窗。
|
||||||
|
onClose: () => void;
|
||||||
|
// onSave 保存 AI 设置并刷新账号列表。
|
||||||
|
onSave: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountAISettingsModal 渲染账号 AI 自动回复策略编辑界面。
|
||||||
|
export const AccountAISettingsModal: React.FC<AccountAISettingsModalProps> = ({ account, settings, saving, onChange, onClose, onSave }) => {
|
||||||
|
// updateSettings 使用最新草稿合并单个 AI 字段变化。
|
||||||
|
const updateSettings = (patch: Partial<AIReplySettings>) => onChange({ ...settings, ...patch });
|
||||||
|
// handleEnabledChange 切换 AI 自动回复开关。
|
||||||
|
const handleEnabledChange = () => updateSettings({ ai_enabled: !settings.ai_enabled });
|
||||||
|
// handleDiscountPercentChange 更新最大折扣比例。
|
||||||
|
const handleDiscountPercentChange = (event: React.ChangeEvent<HTMLInputElement>) => updateSettings({ max_discount_percent: parseInt(event.target.value, 10) || 0 });
|
||||||
|
// handleDiscountAmountChange 更新最大折扣金额。
|
||||||
|
const handleDiscountAmountChange = (event: React.ChangeEvent<HTMLInputElement>) => updateSettings({ max_discount_amount: parseInt(event.target.value, 10) || 0 });
|
||||||
|
// handleBargainRoundsChange 更新最大砍价轮次。
|
||||||
|
const handleBargainRoundsChange = (event: React.ChangeEvent<HTMLInputElement>) => updateSettings({ max_bargain_rounds: parseInt(event.target.value, 10) || 1 });
|
||||||
|
// handlePromptChange 更新自定义 AI 提示词。
|
||||||
|
const handlePromptChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => updateSettings({ custom_prompts: event.target.value });
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="modal-overlay-centered">
|
||||||
|
<div className="modal-container" style={{ maxWidth: '600px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-2xl font-extrabold text-gray-900 flex items-center gap-2"><Bot className="w-6 h-6 text-purple-500" />AI助手设置</h3>
|
||||||
|
<p className="text-sm text-gray-500 mt-1">{account.nickname || account.remark || account.id}</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={onClose} className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0" aria-label="关闭 AI 设置"><X className="w-5 h-5 text-gray-500" /></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body space-y-6">
|
||||||
|
<div className="flex items-center justify-between p-4 bg-purple-50 rounded-xl">
|
||||||
|
<div><div className="font-bold text-gray-900 flex items-center gap-2"><Bot className="w-4 h-4 text-purple-500" />启用AI自动回复</div><div className="text-xs text-gray-500">AI将自动处理买家的砍价消息</div></div>
|
||||||
|
<button type="button" onClick={handleEnabledChange} className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${settings.ai_enabled ? 'bg-brand' : 'bg-gray-300'}`} aria-label="切换 AI 自动回复">
|
||||||
|
<span className={`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${settings.ai_enabled ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border-t border-gray-200 pt-6">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 mb-4">砍价策略</h3>
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
<div><label className="block text-sm font-bold text-gray-700 mb-2">最大折扣比例 (%)</label><input type="number" value={settings.max_discount_percent} onChange={handleDiscountPercentChange} className="w-full ios-input px-4 py-3 rounded-xl" min="0" max="100" /><p className="text-xs text-gray-500 mt-1">例如:10 表示最多降价 10%;设为 0 表示不允许降价</p></div>
|
||||||
|
<div><label className="block text-sm font-bold text-gray-700 mb-2">最大折扣金额 (元)</label><input type="number" value={settings.max_discount_amount} onChange={handleDiscountAmountChange} className="w-full ios-input px-4 py-3 rounded-xl" min="0" /><p className="text-xs text-gray-500 mt-1">例如:100 表示最多降价 100 元;设为 0 表示不允许降价</p></div>
|
||||||
|
<div><label className="block text-sm font-bold text-gray-700 mb-2">最大砍价轮次</label><input type="number" value={settings.max_bargain_rounds} onChange={handleBargainRoundsChange} className="w-full ios-input px-4 py-3 rounded-xl" min="1" max="10" /><p className="text-xs text-gray-500 mt-1">买家最多可以砍价的次数</p></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div><label className="block text-sm font-bold text-gray-700 mb-2">自定义提示词(可选)</label><textarea value={settings.custom_prompts} onChange={handlePromptChange} placeholder="输入自定义的AI回复规则或风格指引... 例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等" className="w-full ios-input px-4 py-3 rounded-xl h-40 resize-none" /></div>
|
||||||
|
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
|
||||||
|
<h4 className="font-bold text-blue-900 mb-2 flex items-center gap-2"><Settings className="w-4 h-4" />AI如何工作</h4>
|
||||||
|
<ul className="text-xs text-blue-800 space-y-1"><li>• 自动识别买家的砍价请求</li><li>• 根据设定的策略智能回复</li><li>• 在合理范围内同意降价或礼貌拒绝</li><li>• 保持专业友好的沟通风格</li></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer"><div className="flex gap-3 w-full">
|
||||||
|
<button onClick={onClose} 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}>取消</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void onSave()} className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2" disabled={saving}>{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}{saving ? '保存中...' : '保存'}</button>
|
||||||
|
</div></div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
};
|
||||||
+20
-61
@@ -1,68 +1,26 @@
|
|||||||
import React, { useState } from 'react';
|
|
||||||
import { CalendarClock,Loader2,MessageSquareQuote,Play,Save,Sparkles,X } from 'lucide-react';
|
import { CalendarClock,Loader2,MessageSquareQuote,Play,Save,Sparkles,X } from 'lucide-react';
|
||||||
import { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../types';
|
import React from 'react';
|
||||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../services/api';
|
import { AccountDetail,AccountTaskSettings } from '../api';
|
||||||
|
import { useAccountAutomation } from '../accountAutomationHooks';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
account: AccountDetail;
|
/** account 表示账号。 */ account: AccountDetail;
|
||||||
onClose: () => void;
|
/** onClose 表示关闭弹窗的回调。 */ onClose: () => void;
|
||||||
onSaved: (settings: AccountTaskSettings) => void;
|
/** onSaved 表示保存完成后的回调。 */ onSaved: (settings: AccountTaskSettings) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Toggle: React.FC<{checked: boolean; onChange: () => void; label: string}> = ({ checked, onChange, label }) => (
|
// Toggle 渲染可复用的开关控件。
|
||||||
|
const Toggle: React.FC<{/** checked 表示开关当前是否选中。 */ checked: boolean; /** onChange 表示开关状态变化的回调。 */ onChange: () => void; /** label 表示控件的无障碍名称。 */ label: string}> = ({ checked, onChange, label }) => (
|
||||||
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
|
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
|
||||||
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
|
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
|
||||||
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
|
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// AccountAutomationModal 渲染账号自动化设置弹窗。
|
||||||
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
|
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
|
||||||
const [form, setForm] = useState<AccountTaskSettings>({
|
// automationState 是账号任务 feature Hook 提供的表单和动作状态。
|
||||||
account_id: account.id,
|
const { form, loading, saving, running, error, summary, retryAvailable, setForm, save, run, retry } = useAccountAutomation({ account, onSaved });
|
||||||
auto_rate_enabled: account.auto_rate_enabled === true,
|
|
||||||
rate_content: account.rate_content || '不错的买家,交易愉快',
|
|
||||||
auto_polish_enabled: account.auto_polish_enabled === true,
|
|
||||||
polish_time: account.polish_time || '03:00',
|
|
||||||
last_rate_scan_at: account.last_rate_scan_at,
|
|
||||||
last_polish_date: account.last_polish_date,
|
|
||||||
last_polish_at: account.last_polish_at,
|
|
||||||
});
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [running, setRunning] = useState<'' | 'auto_rate' | 'auto_polish'>('');
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [summary, setSummary] = useState<AccountTaskSummary | null>(null);
|
|
||||||
|
|
||||||
const save = async () => {
|
|
||||||
setSaving(true);
|
|
||||||
setError('');
|
|
||||||
try {
|
|
||||||
const stored = await updateAccountTaskSettings(account.id, form);
|
|
||||||
setForm(stored);
|
|
||||||
onSaved(stored);
|
|
||||||
} catch (saveError) {
|
|
||||||
setError(saveError instanceof Error ? saveError.message : '保存失败');
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const run = async (taskType: 'auto_rate' | 'auto_polish') => {
|
|
||||||
setRunning(taskType);
|
|
||||||
setError('');
|
|
||||||
setSummary(null);
|
|
||||||
try {
|
|
||||||
await updateAccountTaskSettings(account.id, form);
|
|
||||||
const result = await runAccountTask(account.id, taskType);
|
|
||||||
const stored = await getAccountTaskSettings(account.id);
|
|
||||||
setSummary(result.summary);
|
|
||||||
setForm(stored);
|
|
||||||
onSaved(stored);
|
|
||||||
} catch (runError) {
|
|
||||||
setError(runError instanceof Error ? runError.message : '任务执行失败');
|
|
||||||
} finally {
|
|
||||||
setRunning('');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal-overlay-centered">
|
<div className="modal-overlay-centered">
|
||||||
@@ -78,6 +36,7 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="modal-body space-y-5">
|
<div className="modal-body space-y-5">
|
||||||
|
{loading && <div className="rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500">正在读取任务设置...</div>}
|
||||||
<section className="rounded-2xl border border-slate-200 bg-white p-5">
|
<section className="rounded-2xl border border-slate-200 bg-white p-5">
|
||||||
<div className="flex items-start gap-4">
|
<div className="flex items-start gap-4">
|
||||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><MessageSquareQuote className="h-5 w-5" /></div>
|
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><MessageSquareQuote className="h-5 w-5" /></div>
|
||||||
@@ -87,14 +46,14 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
|
|||||||
<h4 className="font-black text-slate-900">自动评价</h4>
|
<h4 className="font-black text-slate-900">自动评价</h4>
|
||||||
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
|
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
|
||||||
</div>
|
</div>
|
||||||
<Toggle checked={form.auto_rate_enabled} onChange={() => setForm(current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
|
<Toggle checked={form.auto_rate_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
|
||||||
</div>
|
</div>
|
||||||
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
|
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
|
||||||
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={event => setForm(current => ({ ...current, rate_content: event.target.value }))}
|
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, rate_content: event.target.value }))}
|
||||||
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
|
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
|
||||||
<div className="mt-3 flex items-center justify-between gap-3">
|
<div className="mt-3 flex items-center justify-between gap-3">
|
||||||
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
|
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
|
||||||
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_rate')}
|
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_rate')}
|
||||||
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
|
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
|
||||||
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
|
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
|
||||||
</button>
|
</button>
|
||||||
@@ -112,15 +71,15 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
|
|||||||
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
|
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
|
||||||
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
|
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
|
||||||
</div>
|
</div>
|
||||||
<Toggle checked={form.auto_polish_enabled} onChange={() => setForm(current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
|
<Toggle checked={form.auto_polish_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-4 flex items-end justify-between gap-4">
|
<div className="mt-4 flex items-end justify-between gap-4">
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
|
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
|
||||||
<input type="time" value={form.polish_time} onChange={event => setForm(current => ({ ...current, polish_time: event.target.value }))}
|
<input type="time" value={form.polish_time} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, polish_time: event.target.value }))}
|
||||||
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
|
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
|
||||||
</label>
|
</label>
|
||||||
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_polish')}
|
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_polish')}
|
||||||
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
|
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
|
||||||
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
|
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
|
||||||
</button>
|
</button>
|
||||||
@@ -135,14 +94,14 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
|
|||||||
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
|
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{error && <div className="rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">{error}</div>}
|
{error && <div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void retry()}>重试</button>}</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="modal-footer">
|
<div className="modal-footer">
|
||||||
<div className="flex w-full gap-3">
|
<div className="flex w-full gap-3">
|
||||||
<button type="button" onClick={onClose} disabled={saving || running !== ''}
|
<button type="button" onClick={onClose} disabled={saving || running !== ''}
|
||||||
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
|
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
|
||||||
<button type="button" onClick={() => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
|
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
|
||||||
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
|
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
|
||||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
|
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
|
||||||
</button>
|
</button>
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { AlertCircle,Bot,CalendarClock,Check,Clock,Edit2,Loader2,MessageCircle,Power,QrCode,RefreshCw,Sparkles,Trash2,User } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import type { AccountDetail } from '../api';
|
||||||
|
import { accountRuntimePresentation } from '../runtime';
|
||||||
|
|
||||||
|
// AccountCardProps 描述账号卡片展示所需的数据和动作。
|
||||||
|
export interface AccountCardProps {
|
||||||
|
// account 是当前账号的非敏感展示数据。
|
||||||
|
account: AccountDetail;
|
||||||
|
// refreshing 表示当前账号是否正在刷新资料。
|
||||||
|
refreshing: boolean;
|
||||||
|
// deleting 表示当前账号是否正在删除。
|
||||||
|
deleting: boolean;
|
||||||
|
// onRefreshProfile 刷新账号昵称和头像。
|
||||||
|
onRefreshProfile: (account: AccountDetail) => void | Promise<void>;
|
||||||
|
// onReauthorize 启动当前账号二维码重新授权。
|
||||||
|
onReauthorize: (account: AccountDetail) => void | Promise<void>;
|
||||||
|
// onEdit 打开账号编辑弹窗。
|
||||||
|
onEdit: (account: AccountDetail) => void | Promise<void>;
|
||||||
|
// onAI 打开账号 AI 设置弹窗。
|
||||||
|
onAI: (account: AccountDetail) => void | Promise<void>;
|
||||||
|
// onTasks 打开账号自动化任务弹窗。
|
||||||
|
onTasks: (account: AccountDetail) => void;
|
||||||
|
// onToggle 切换账号启用状态。
|
||||||
|
onToggle: (id: string, currentStatus: boolean) => void | Promise<void>;
|
||||||
|
// onDelete 打开账号删除确认框。
|
||||||
|
onDelete: (account: AccountDetail) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountCard 渲染单个账号的状态摘要与操作入口。
|
||||||
|
export const AccountCard = React.memo(/* AccountCard 负责渲染单个账号卡片及其操作。 */ function AccountCard({
|
||||||
|
account,
|
||||||
|
refreshing,
|
||||||
|
deleting,
|
||||||
|
onRefreshProfile,
|
||||||
|
onReauthorize,
|
||||||
|
onEdit,
|
||||||
|
onAI,
|
||||||
|
onTasks,
|
||||||
|
onToggle,
|
||||||
|
onDelete,
|
||||||
|
}: AccountCardProps) {
|
||||||
|
// runtime 保存账号运行状态的展示样式。
|
||||||
|
const runtime = accountRuntimePresentation(account);
|
||||||
|
// requiresLogin 表示当前账号是否需要重新授权。
|
||||||
|
const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand">
|
||||||
|
<div className="flex min-w-0 items-start gap-5 sm:gap-8">
|
||||||
|
<div className="relative">
|
||||||
|
{account.avatar_url ? (
|
||||||
|
<img
|
||||||
|
src={account.avatar_url}
|
||||||
|
alt={account.nickname || '账号头像'}
|
||||||
|
className="w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center">
|
||||||
|
<User className="w-9 h-9" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className={`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${runtime.dot}`}>
|
||||||
|
{account.runtime_state === 'online' && <Check className="w-3 h-3 text-white" />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2.5 mb-1">
|
||||||
|
<h3 className="text-xl font-extrabold text-gray-900 break-words">{account.nickname || account.remark || `账号 ${account.id.substring(0, 6)}...`}</h3>
|
||||||
|
<span className={`px-2.5 py-0.5 rounded-lg text-xs font-bold ${runtime.badge}`}>{runtime.label}</span>
|
||||||
|
{account.ai_enabled && (
|
||||||
|
<span className="px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1">
|
||||||
|
<Bot className="w-3 h-3" /> AI
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{account.auto_rate_enabled && (
|
||||||
|
<span className="flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700">
|
||||||
|
<MessageCircle className="h-3 w-3" /> 自动评价
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{account.auto_polish_enabled && (
|
||||||
|
<span className="flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700">
|
||||||
|
<Sparkles className="h-3 w-3" /> 每日擦亮
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{account.auto_confirm && <span className="flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700"><Check className="h-3 w-3" /> 自动确认发货</span>}
|
||||||
|
{account.profile_error && (
|
||||||
|
<span className="px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1" title={account.profile_error}>
|
||||||
|
<AlertCircle className="w-3 h-3" /> 资料未同步
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex flex-wrap items-center justify-between gap-4">
|
||||||
|
<div className="text-sm font-medium text-gray-500">
|
||||||
|
<p>{account.remark || '暂无备注'}</p>
|
||||||
|
<p className="font-mono text-xs text-gray-400">ID: {account.id}</p>
|
||||||
|
</div>
|
||||||
|
{account.runtime_message && account.runtime_state !== 'online' && account.runtime_state !== 'disabled' && (
|
||||||
|
<div className={`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${requiresLogin ? 'text-red-700' : 'text-amber-700'}`}>
|
||||||
|
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||||
|
<span>{account.runtime_message}</span>
|
||||||
|
{requiresLogin && (
|
||||||
|
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onReauthorize(account)} className="inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100">
|
||||||
|
<QrCode className="w-3.5 h-3.5" /> 重新授权
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{account.paused && <span className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700"><Clock className="h-3 w-3" /> 暂停处理中</span>}
|
||||||
|
<div className="mt-3 flex flex-wrap items-center justify-end gap-2">
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onRefreshProfile(account)} disabled={refreshing} className="p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50" title="刷新昵称和头像">
|
||||||
|
<RefreshCw className={`w-5 h-5 ${refreshing ? 'animate-spin' : ''}`} />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onReauthorize(account)} className={`p-3 rounded-xl transition-colors ${requiresLogin ? 'text-red-600 bg-red-50 hover:bg-red-100' : 'text-blue-600 hover:bg-blue-50'}`} title="重新扫码授权当前账号">
|
||||||
|
<QrCode className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onEdit(account)} className="p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600" title="编辑账号">
|
||||||
|
<Edit2 className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onAI(account)} className="p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600" title="AI设置">
|
||||||
|
<Bot className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onTasks(account)} className="p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600" title="自动评价与每日擦亮">
|
||||||
|
<CalendarClock className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onToggle(account.id, account.enabled)} className={`p-3 rounded-xl transition-colors ${account.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'}`} title={account.enabled ? '停用账号' : '启用账号'}>
|
||||||
|
<Power className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onDelete(account)} disabled={deleting} className="p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40" title={deleting ? '删除中…' : `删除账号 ${account.nickname || account.remark || account.id}`}>
|
||||||
|
{deleting ? <Loader2 className="w-5 h-5 animate-spin" /> : <Trash2 className="w-5 h-5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { AlertCircle,Loader2,Trash2,X } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import type { AccountDetail } from '../api';
|
||||||
|
|
||||||
|
// AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。
|
||||||
|
export interface AccountDeleteDialogProps {
|
||||||
|
// account 是待删除的账号摘要。
|
||||||
|
account: AccountDetail;
|
||||||
|
// deleting 表示删除请求是否正在执行。
|
||||||
|
deleting: boolean;
|
||||||
|
// error 是删除失败后的用户可见提示。
|
||||||
|
error: string;
|
||||||
|
// onClose 关闭删除确认框。
|
||||||
|
onClose: () => void;
|
||||||
|
// onConfirm 确认删除账号。
|
||||||
|
onConfirm: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountDeleteDialog 渲染账号删除确认框并通过 Portal 隔离页面布局。
|
||||||
|
export const AccountDeleteDialog: React.FC<AccountDeleteDialogProps> = ({ account, deleting, error, onClose, onConfirm }) => createPortal(
|
||||||
|
<div className="modal-overlay-centered" role="presentation">
|
||||||
|
<div className="h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal" role="dialog" aria-modal="true" aria-labelledby="delete-account-title" aria-describedby="delete-account-description">
|
||||||
|
<div className="relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5">
|
||||||
|
<div className="absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl" />
|
||||||
|
<div className="relative flex items-start gap-4">
|
||||||
|
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200"><Trash2 className="h-5 w-5" /></div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<h3 id="delete-account-title" className="text-lg font-extrabold tracking-tight text-gray-950">删除这个账号?</h3>
|
||||||
|
<p id="delete-account-description" className="mt-1 text-xs leading-5 text-gray-600">删除后,该账号的关联配置也会一并清理,此操作无法撤销。</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={onClose} disabled={deleting} className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40" aria-label="关闭删除确认"><X className="h-5 w-5" /></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-5 py-4">
|
||||||
|
<div className="rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3">
|
||||||
|
<div className="text-sm font-extrabold text-gray-900">{account.nickname || account.remark || '未命名账号'}</div>
|
||||||
|
{account.remark && account.nickname && <div className="mt-1 text-sm text-gray-500">备注:{account.remark}</div>}
|
||||||
|
<div className="mt-1.5 break-all font-mono text-[11px] text-gray-400">ID: {account.id}</div>
|
||||||
|
</div>
|
||||||
|
{deleting && (
|
||||||
|
<div className="mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3" role="progressbar" aria-label="正在删除账号">
|
||||||
|
<Loader2 className="h-5 w-5 flex-shrink-0 animate-spin text-brand" />
|
||||||
|
<div><div className="text-sm font-extrabold text-blue-950">正在删除账号</div><div className="mt-0.5 text-xs text-blue-700">正在清理关联数据,请保持页面打开…</div></div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<div className="mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3" role="alert">
|
||||||
|
<AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-red-600" />
|
||||||
|
<div><div className="text-sm font-extrabold text-red-800">删除失败</div><div className="mt-1 text-xs leading-5 text-red-700">{error}</div></div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4">
|
||||||
|
<button type="button" onClick={onClose} disabled={deleting} className="flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50">取消</button>
|
||||||
|
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void onConfirm()} disabled={deleting} className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400">
|
||||||
|
{deleting ? <><Loader2 className="h-4 w-4 animate-spin" />处理中</> : <><Trash2 className="h-4 w-4" />确认删除</>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
import { Bell,Check,Clock,Eye,EyeOff,Key,Loader2,X } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import type { NotificationChannel } from '../api';
|
||||||
|
import type { AccountEditForm,AccountEditModalProps } from '../types';
|
||||||
|
import { SquareQRCode } from './SquareQRCode';
|
||||||
|
|
||||||
|
// AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。
|
||||||
|
export const AccountEditModal: React.FC<AccountEditModalProps> = ({
|
||||||
|
account,
|
||||||
|
editForm,
|
||||||
|
setEditForm,
|
||||||
|
saving,
|
||||||
|
onClose,
|
||||||
|
onSave,
|
||||||
|
onRestartPause,
|
||||||
|
longLogin,
|
||||||
|
onToggleLongLogin,
|
||||||
|
passwordLoginView,
|
||||||
|
onPasswordLogin,
|
||||||
|
onCancelPasswordLogin,
|
||||||
|
notifChannels,
|
||||||
|
selectedChannelIds,
|
||||||
|
bindingsLoaded,
|
||||||
|
bindingsLoading,
|
||||||
|
bindingsLoadError,
|
||||||
|
onRetryBindings,
|
||||||
|
onToggleChannel,
|
||||||
|
onSettingsDirty,
|
||||||
|
}) => {
|
||||||
|
// updateField 用函数式更新避免连续输入事件读取旧表单快照。
|
||||||
|
const updateField = <K extends keyof AccountEditForm>(field: K, value: AccountEditForm[K]) => {
|
||||||
|
setEditForm(
|
||||||
|
// current 是事件发生前的最新编辑表单。
|
||||||
|
current => ({ ...current, [field]: value }),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// handleClose 关闭编辑弹窗并取消未完成的异步操作。
|
||||||
|
const handleClose = () => void onClose();
|
||||||
|
// handleSave 提交编辑表单并让父级刷新账号数据。
|
||||||
|
const handleSave = () => void onSave();
|
||||||
|
// handleRemarkChange 更新账号备注字段。
|
||||||
|
const handleRemarkChange = (event: React.ChangeEvent<HTMLInputElement>) => updateField('remark', event.target.value);
|
||||||
|
// handleCookieChange 更新账号 Cookie 字段。
|
||||||
|
const handleCookieChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => updateField('cookie', event.target.value);
|
||||||
|
// handleAutoConfirmToggle 切换自动确认发货设置。
|
||||||
|
const handleAutoConfirmToggle = () => updateField('auto_confirm', !editForm.auto_confirm);
|
||||||
|
// handlePauseDurationChange 更新账号暂停时长。
|
||||||
|
const handlePauseDurationChange = (event: React.ChangeEvent<HTMLInputElement>) => updateField('pause_duration', parseInt(event.target.value, 10) || 0);
|
||||||
|
// handleRestartPause 按当前时长立即重新暂停账号。
|
||||||
|
const handleRestartPause = () => void onRestartPause();
|
||||||
|
// handleLongLoginToggle 切换闲鱼官方长登录设置。
|
||||||
|
const handleLongLoginToggle = () => void onToggleLongLogin();
|
||||||
|
// handleUsernameChange 更新密码登录用户名。
|
||||||
|
const handleUsernameChange = (event: React.ChangeEvent<HTMLInputElement>) => updateField('username', event.target.value);
|
||||||
|
// handlePasswordChange 更新密码并清除待清空标记。
|
||||||
|
const handlePasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => setEditForm(
|
||||||
|
// current 是密码输入前的最新编辑表单。
|
||||||
|
current => ({ ...current, login_password: event.target.value, clear_password: false }),
|
||||||
|
);
|
||||||
|
// handlePasswordVisibilityToggle 切换密码明文显示状态。
|
||||||
|
const handlePasswordVisibilityToggle = () => updateField('showLoginPassword', !editForm.showLoginPassword);
|
||||||
|
// handleClearPasswordChange 更新密码清空选项。
|
||||||
|
const handleClearPasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => setEditForm(
|
||||||
|
// current 是勾选清空密码前的最新编辑表单。
|
||||||
|
current => ({ ...current, clear_password: event.target.checked, login_password: event.target.checked ? '' : current.login_password }),
|
||||||
|
);
|
||||||
|
// handleShowBrowserToggle 切换密码登录时是否展示浏览器。
|
||||||
|
const handleShowBrowserToggle = () => updateField('show_browser', !editForm.show_browser);
|
||||||
|
// handleCancelPasswordLogin 取消正在执行的密码登录。
|
||||||
|
const handleCancelPasswordLogin = () => void onCancelPasswordLogin();
|
||||||
|
// handlePasswordLogin 启动密码登录刷新授权。
|
||||||
|
const handlePasswordLogin = () => void onPasswordLogin();
|
||||||
|
// handleRetryBindings 重新加载当前账号的通知绑定。
|
||||||
|
const handleRetryBindings = () => void onRetryBindings();
|
||||||
|
// handleChannelClick 切换通知渠道并标记绑定表单已修改。
|
||||||
|
const handleChannelClick = (channelId: number) => {
|
||||||
|
if (!bindingsLoaded) return;
|
||||||
|
onToggleChannel(channelId);
|
||||||
|
onSettingsDirty();
|
||||||
|
};
|
||||||
|
// renderNotificationChannel 渲染单个通知渠道选项。
|
||||||
|
const renderNotificationChannel = (channel: NotificationChannel) => {
|
||||||
|
// checked 表示当前通知渠道是否已被选中。
|
||||||
|
const checked = selectedChannelIds.includes(Number(channel.id));
|
||||||
|
// handleChannelButtonClick 把渠道 ID 绑定到当前选项的点击事件。
|
||||||
|
const handleChannelButtonClick = () => handleChannelClick(Number(channel.id));
|
||||||
|
return (
|
||||||
|
<label key={channel.id} className="flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleChannelButtonClick}
|
||||||
|
disabled={!bindingsLoaded}
|
||||||
|
className={`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${checked ? 'bg-brand border-brand' : 'bg-white border-gray-300'}`}
|
||||||
|
>
|
||||||
|
{checked && <Check className="w-3.5 h-3.5 text-white" />}
|
||||||
|
</button>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="font-bold text-gray-900 text-sm">{channel.name}</div>
|
||||||
|
<div className="text-xs text-gray-500">{channel.type}{channel.enabled ? '' : ' · 已停用'}</div>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="modal-overlay-centered">
|
||||||
|
<div className="modal-container" style={{ maxWidth: '600px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-2xl font-extrabold text-gray-900">编辑账号</h3>
|
||||||
|
<p className="text-sm text-gray-500 mt-1">{account.nickname || account.remark || account.id}</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={handleClose} className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0">
|
||||||
|
<X className="w-5 h-5 text-gray-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body space-y-6">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-bold text-gray-700 mb-2">账号ID</label>
|
||||||
|
<input type="text" value={account.id} disabled className="w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-bold text-gray-700 mb-2">备注</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={editForm.remark}
|
||||||
|
onChange={handleRemarkChange}
|
||||||
|
placeholder="为账号添加备注"
|
||||||
|
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">Cookie</label>
|
||||||
|
<textarea
|
||||||
|
value={editForm.cookie}
|
||||||
|
onChange={handleCookieChange}
|
||||||
|
placeholder="更新账号Cookie"
|
||||||
|
className="w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">当前Cookie长度: {editForm.cookie.length} 字符</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
|
||||||
|
<div>
|
||||||
|
<div className="font-bold text-gray-900 flex items-center gap-2"><Check className="w-4 h-4 text-green-500" />自动确认发货</div>
|
||||||
|
<div className="text-xs text-gray-500">自动将闲鱼订单标记为已发货</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleAutoConfirmToggle}
|
||||||
|
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${editForm.auto_confirm ? 'bg-brand' : 'bg-gray-300'}`}
|
||||||
|
>
|
||||||
|
<span className={`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${editForm.auto_confirm ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2"><Clock className="w-4 h-4 text-blue-500" />暂停处理时长(分钟)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={editForm.pause_duration}
|
||||||
|
onChange={handlePauseDurationChange}
|
||||||
|
placeholder="0"
|
||||||
|
min="0"
|
||||||
|
max="1440"
|
||||||
|
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 && !account.paused && editForm.pause_duration === (account.pause_duration || 0) && (
|
||||||
|
<button type="button" disabled={saving} onClick={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>
|
||||||
|
|
||||||
|
<div className="border-t border-gray-200 pt-6">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2"><Key className="w-5 h-5 text-blue-500" />登录信息</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4">
|
||||||
|
<div>
|
||||||
|
<div className="font-bold text-gray-900">保存登录信息</div>
|
||||||
|
<div className="mt-1 text-xs text-gray-500">状态直接读取并修改闲鱼官方长登录设置</div>
|
||||||
|
{longLogin.error && <div className="mt-1 text-xs text-red-600">{longLogin.error}</div>}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="保存登录信息"
|
||||||
|
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
|
||||||
|
onClick={handleLongLoginToggle}
|
||||||
|
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-brand' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||||
|
>
|
||||||
|
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-bold text-gray-700 mb-2">用户名</label>
|
||||||
|
<input type="text" value={editForm.username} onChange={handleUsernameChange} placeholder="闲鱼账号/手机号" 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>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
type={editForm.showLoginPassword ? 'text' : 'password'}
|
||||||
|
value={editForm.login_password}
|
||||||
|
onChange={handlePasswordChange}
|
||||||
|
placeholder="用于自动登录"
|
||||||
|
className="w-full ios-input px-4 py-3 rounded-xl pr-12"
|
||||||
|
/>
|
||||||
|
<button type="button" onClick={handlePasswordVisibilityToggle} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
|
||||||
|
{editForm.showLoginPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<label className="mt-3 flex items-center gap-3 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={editForm.clear_password}
|
||||||
|
onChange={handleClearPasswordChange}
|
||||||
|
className="w-4 h-4 accent-brand"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-bold text-gray-700">清空已保存密码</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="font-bold text-gray-900">登录时显示浏览器</div>
|
||||||
|
<div className="text-xs text-gray-500">调试时可开启查看登录过程</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={handleShowBrowserToggle} className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${editForm.show_browser ? 'bg-brand' : 'bg-gray-300'}`}>
|
||||||
|
<span className={`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${editForm.show_browser ? 'translate-x-6' : 'translate-x-0'}`} />
|
||||||
|
</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>
|
||||||
|
|
||||||
|
{(notifChannels.length > 0 || bindingsLoading || bindingsLoadError) && (
|
||||||
|
<div className="border-t border-gray-200 pt-6">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 mb-1 flex items-center gap-2"><Bell className="w-5 h-5 text-blue-500" />通知渠道绑定</h3>
|
||||||
|
<p className="text-xs text-gray-500 mb-4">勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道</p>
|
||||||
|
{bindingsLoading && <div className="flex items-center gap-2 text-sm text-gray-500"><Loader2 className="w-4 h-4 animate-spin" />正在加载通知绑定</div>}
|
||||||
|
{bindingsLoadError && !bindingsLoading && (
|
||||||
|
<div className="mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3">
|
||||||
|
<span>{bindingsLoadError}</span>
|
||||||
|
<button type="button" className="font-bold whitespace-nowrap" onClick={handleRetryBindings}>重试</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{notifChannels.map(renderNotificationChannel)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer">
|
||||||
|
<div className="flex gap-3 w-full">
|
||||||
|
<button onClick={handleClose} 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}>取消</button>
|
||||||
|
<button onClick={handleSave} className="flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2" disabled={saving}>
|
||||||
|
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
|
||||||
|
{saving ? '保存中...' : '保存'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { Check,Loader2,X } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import type { AccountDetail } from '../api';
|
||||||
|
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||||
|
import { SquareQRCode } from './SquareQRCode';
|
||||||
|
|
||||||
|
// AccountQRCodeModalProps 描述二维码登录弹窗的展示状态和关闭回调。
|
||||||
|
export interface AccountQRCodeModalProps {
|
||||||
|
// target 是重新授权时的目标账号,新增账号时为空。
|
||||||
|
target: AccountDetail | null;
|
||||||
|
// status 是二维码登录当前阶段。
|
||||||
|
status: string;
|
||||||
|
// codeUrl 是待扫描的二维码地址。
|
||||||
|
codeUrl: string;
|
||||||
|
// errorMessage 是二维码生成或轮询失败提示。
|
||||||
|
errorMessage: string;
|
||||||
|
// faceQrUrl 是风控人脸验证二维码地址。
|
||||||
|
faceQrUrl: string;
|
||||||
|
// verificationScreenshot 是风控验证截图地址。
|
||||||
|
verificationScreenshot: string;
|
||||||
|
// onClose 关闭二维码登录弹窗并取消后台请求。
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountQRCodeModal 渲染二维码登录、风控验证和结果状态。
|
||||||
|
export const AccountQRCodeModal: React.FC<AccountQRCodeModalProps> = ({ target, status, codeUrl, errorMessage, faceQrUrl, verificationScreenshot, onClose }) => createPortal(
|
||||||
|
<div className="modal-overlay-centered">
|
||||||
|
<div className="modal-container relative" style={{ maxWidth: '26rem' }}>
|
||||||
|
<button onClick={onClose} 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" aria-label="关闭二维码登录">
|
||||||
|
<X className="w-5 h-5 text-gray-600" />
|
||||||
|
</button>
|
||||||
|
<div className="modal-body">
|
||||||
|
<div className="text-center">
|
||||||
|
<h3 className="text-2xl font-extrabold text-gray-900 mb-2">{target ? '重新授权账号' : '扫码添加账号'}</h3>
|
||||||
|
<p className="text-gray-500 mb-8 font-medium">{target ? `请用闲鱼APP扫码,为「${target.nickname || target.remark || target.id}」刷新授权` : '请打开闲鱼APP扫描下方二维码'}</p>
|
||||||
|
<div className={`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${status === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
|
||||||
|
{status === 'loading' && <Loader2 className="w-10 h-10 text-brand animate-spin" />}
|
||||||
|
{status === 'waiting' && <SquareQRCode src={codeUrl} alt="闲鱼登录二维码" className="p-2" />}
|
||||||
|
{status === '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"><Check className="w-8 h-8" /></div>
|
||||||
|
<span className="font-bold text-lg">登录成功</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{status === '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">{errorMessage || '请关闭窗口后重新发起扫码登录。'}</span></div>}
|
||||||
|
{status === 'verification' && <RiskVerificationPanel faceQrUrl={faceQrUrl} verificationScreenshot={verificationScreenshot} />}
|
||||||
|
</div>
|
||||||
|
{status !== 'verification' && <p className="text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl">二维码有效期为5分钟,请尽快扫码。</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
+2
-2
@@ -1,9 +1,9 @@
|
|||||||
import React from 'react';
|
|
||||||
import { renderToStaticMarkup } from 'react-dom/server';
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
import { expect,test } from 'vitest';
|
import { expect,test } from 'vitest';
|
||||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||||
|
|
||||||
test('risk verification panel explains automatic refresh without manual controls', () => {
|
test('risk verification panel explains automatic refresh without manual controls', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// html 渲染后的 HTML。
|
||||||
const html = renderToStaticMarkup(
|
const html = renderToStaticMarkup(
|
||||||
<RiskVerificationPanel faceQrUrl="data:image/png;base64,abc" />,
|
<RiskVerificationPanel faceQrUrl="data:image/png;base64,abc" />,
|
||||||
);
|
);
|
||||||
+4
-3
@@ -1,11 +1,12 @@
|
|||||||
import React from 'react';
|
|
||||||
import { AlertTriangle,Loader2 } from 'lucide-react';
|
import { AlertTriangle,Loader2 } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
|
||||||
interface RiskVerificationPanelProps {
|
interface RiskVerificationPanelProps {
|
||||||
faceQrUrl?: string;
|
/** faceQrUrl 表示人脸验证二维码地址。 */ faceQrUrl?: string;
|
||||||
verificationScreenshot?: string;
|
/** verificationScreenshot 表示验证失败截图地址。 */ verificationScreenshot?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RiskVerificationPanel 渲染风控验证面板。
|
||||||
export const RiskVerificationPanel: React.FC<RiskVerificationPanelProps> = ({
|
export const RiskVerificationPanel: React.FC<RiskVerificationPanelProps> = ({
|
||||||
faceQrUrl,
|
faceQrUrl,
|
||||||
verificationScreenshot,
|
verificationScreenshot,
|
||||||
+2
-2
@@ -1,9 +1,9 @@
|
|||||||
import React from 'react';
|
|
||||||
import { renderToStaticMarkup } from 'react-dom/server';
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
import { expect,test } from 'vitest';
|
import { expect,test } from 'vitest';
|
||||||
import { SquareQRCode } from './SquareQRCode';
|
import { SquareQRCode } from './SquareQRCode';
|
||||||
|
|
||||||
test('login QR code preserves a square aspect ratio without stretching', () => {
|
test('login QR code preserves a square aspect ratio without stretching', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// html 渲染后的 HTML。
|
||||||
const html = renderToStaticMarkup(<SquareQRCode src="data:image/png;base64,abc" alt="登录二维码" className="p-2" />);
|
const html = renderToStaticMarkup(<SquareQRCode src="data:image/png;base64,abc" alt="登录二维码" className="p-2" />);
|
||||||
expect(html).toContain('aspect-square');
|
expect(html).toContain('aspect-square');
|
||||||
expect(html).toContain('h-auto');
|
expect(html).toContain('h-auto');
|
||||||
+4
-3
@@ -1,11 +1,12 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
interface SquareQRCodeProps {
|
interface SquareQRCodeProps {
|
||||||
src: string;
|
/** src 表示二维码图片地址。 */ src: string;
|
||||||
alt: string;
|
/** alt 表示二维码的替代文本。 */ alt: string;
|
||||||
className?: string;
|
/** className 表示附加的 CSS 类名。 */ className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SquareQRCode 渲染方形二维码图片。
|
||||||
export const SquareQRCode: React.FC<SquareQRCodeProps> = ({ src, alt, className = '' }) => (
|
export const SquareQRCode: React.FC<SquareQRCodeProps> = ({ src, alt, className = '' }) => (
|
||||||
<img
|
<img
|
||||||
src={src}
|
src={src}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { cleanup,fireEvent,render,screen } from '@testing-library/react';
|
||||||
|
import { afterEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts';
|
||||||
|
import { AccountAISettingsModal } from './AccountAISettingsModal';
|
||||||
|
import { AccountCard } from './AccountCard';
|
||||||
|
import { AccountDeleteDialog } from './AccountDeleteDialog';
|
||||||
|
import { AccountQRCodeModal } from './AccountQRCodeModal';
|
||||||
|
|
||||||
|
// accountFixture 是账号组件测试使用的最小非敏感账号摘要。
|
||||||
|
const accountFixture = {
|
||||||
|
id: 'account-1',
|
||||||
|
nickname: '测试账号',
|
||||||
|
remark: '测试备注',
|
||||||
|
enabled: true,
|
||||||
|
runtime_state: 'online',
|
||||||
|
runtime_message: '',
|
||||||
|
ai_enabled: true,
|
||||||
|
auto_rate_enabled: false,
|
||||||
|
auto_polish_enabled: false,
|
||||||
|
auto_confirm: false,
|
||||||
|
paused: false,
|
||||||
|
} as AccountDetail;
|
||||||
|
|
||||||
|
// aiSettingsFixture 是 AI 设置弹窗测试使用的编辑草稿。
|
||||||
|
const aiSettingsFixture: AIReplySettings = {
|
||||||
|
ai_enabled: false,
|
||||||
|
max_discount_percent: 10,
|
||||||
|
max_discount_amount: 100,
|
||||||
|
max_bargain_rounds: 3,
|
||||||
|
custom_prompts: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
// noopAccountAction 是账号卡片测试使用的动作占位函数。
|
||||||
|
const noopAccountAction = (): void => undefined;
|
||||||
|
|
||||||
|
describe('账号 feature 展示组件', /* 当前回调覆盖账号页面子模块展示边界。 */ () => {
|
||||||
|
afterEach(/* 当前回调清理 Portal 和测试 DOM。 */ () => cleanup());
|
||||||
|
|
||||||
|
test('账号卡片展示状态并转发所有操作', /* 当前回调验证账号卡片的操作边界。 */ () => {
|
||||||
|
// onDelete 是删除操作测试替身。
|
||||||
|
const onDelete = vi.fn();
|
||||||
|
// onAI 是 AI 设置操作测试替身。
|
||||||
|
const onAI = vi.fn();
|
||||||
|
// onToggle 是启停操作测试替身。
|
||||||
|
const onToggle = vi.fn();
|
||||||
|
render(<AccountCard account={accountFixture} refreshing={false} deleting={false} onRefreshProfile={noopAccountAction} onReauthorize={noopAccountAction} onEdit={noopAccountAction} onAI={onAI} onTasks={noopAccountAction} onToggle={onToggle} onDelete={onDelete} />);
|
||||||
|
expect(screen.getByText('测试账号')).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByTitle('AI设置'));
|
||||||
|
fireEvent.click(screen.getByTitle('停用账号'));
|
||||||
|
fireEvent.click(screen.getByTitle('删除账号 测试账号'));
|
||||||
|
expect(onAI).toHaveBeenCalledWith(accountFixture);
|
||||||
|
expect(onToggle).toHaveBeenCalledWith(accountFixture.id, accountFixture.enabled);
|
||||||
|
expect(onDelete).toHaveBeenCalledWith(accountFixture);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('AI 设置弹窗使用补丁更新并转发保存', /* 当前回调验证 AI 设置字段更新和保存动作。 */ () => {
|
||||||
|
// onChange 是 AI 设置草稿更新测试替身。
|
||||||
|
const onChange = vi.fn();
|
||||||
|
// onSave 是 AI 设置保存测试替身。
|
||||||
|
const onSave = vi.fn();
|
||||||
|
render(<AccountAISettingsModal account={accountFixture} settings={aiSettingsFixture} saving={false} onChange={onChange} onClose={noopAccountAction} onSave={onSave} />);
|
||||||
|
fireEvent.click(screen.getByLabelText('切换 AI 自动回复'));
|
||||||
|
fireEvent.change(screen.getByDisplayValue('10'), { target: { value: '20' } });
|
||||||
|
fireEvent.click(screen.getByText('保存'));
|
||||||
|
expect(onChange).toHaveBeenNthCalledWith(1, { ...aiSettingsFixture, ai_enabled: true });
|
||||||
|
expect(onChange).toHaveBeenNthCalledWith(2, { ...aiSettingsFixture, max_discount_percent: 20 });
|
||||||
|
expect(onSave).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('删除确认框展示错误并转发确认动作', /* 当前回调验证删除确认框的错误和提交分支。 */ () => {
|
||||||
|
// onConfirm 是删除确认测试替身。
|
||||||
|
const onConfirm = vi.fn();
|
||||||
|
render(<AccountDeleteDialog account={accountFixture} deleting={false} error="删除失败" onClose={noopAccountAction} onConfirm={onConfirm} />);
|
||||||
|
expect(screen.getByRole('alert').textContent).toContain('删除失败');
|
||||||
|
fireEvent.click(screen.getByText('确认删除'));
|
||||||
|
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('二维码弹窗展示风控验证面板且不生成外部链接', /* 当前回调验证二维码风控状态的安全展示边界。 */ () => {
|
||||||
|
render(<AccountQRCodeModal target={accountFixture} status="verification" codeUrl="" errorMessage="" faceQrUrl="face-qr" verificationScreenshot="screen" onClose={noopAccountAction} />);
|
||||||
|
expect(screen.getByText('需要完成安全风控验证')).toBeTruthy();
|
||||||
|
expect(document.querySelectorAll('a')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { renderHook,waitFor } from '@testing-library/react';
|
||||||
|
import { act } from 'react';
|
||||||
|
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||||
|
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
|
||||||
|
import { useAccountsData } from './hooks';
|
||||||
|
|
||||||
|
vi.mock('./api', /* accountsApiMockFactory 提供账号列表 Hook 的确定性 API 替身。 */ () => ({
|
||||||
|
getAccountDetails: vi.fn(),
|
||||||
|
getAccountRuntimeStatuses: vi.fn(),
|
||||||
|
getAllAISettings: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// getDetailsMock 是账号详情请求的可控替身。
|
||||||
|
const getDetailsMock = vi.mocked(getAccountDetails);
|
||||||
|
// getRuntimeMock 是账号运行状态轮询请求的可控替身。
|
||||||
|
const getRuntimeMock = vi.mocked(getAccountRuntimeStatuses);
|
||||||
|
// getAISettingsMock 是账号 AI 配置请求的可控替身。
|
||||||
|
const getAISettingsMock = vi.mocked(getAllAISettings);
|
||||||
|
|
||||||
|
// accountFixture 是账号列表 Hook 测试使用的基础账号对象。
|
||||||
|
const accountFixture: AccountDetail = { id: 'account-1', enabled: true, auto_confirm: false, remark: '测试账号' };
|
||||||
|
|
||||||
|
describe('useAccountsData', /* 当前回调处理账号详情、AI 配置和运行状态轮询。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置账号 API 替身和日志输出。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
getDetailsMock.mockResolvedValue([accountFixture]);
|
||||||
|
getAISettingsMock.mockResolvedValue({ 'account-1': { ai_enabled: true, max_discount_percent: 20, max_discount_amount: 30, max_bargain_rounds: 4, custom_prompts: '提示词' } } as never);
|
||||||
|
getRuntimeMock.mockResolvedValue({ 'account-1': { state: 'online', connected: true, failures: 0, message: '在线', updated_at: '2026-08-15T00:00:00Z' } });
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(
|
||||||
|
// errorImplementation 屏蔽轮询失败测试中的日志输出。
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('加载账号并合并 AI 与运行状态', /* 当前回调验证账号列表成功加载路径。 */ async () => {
|
||||||
|
// hook 是账号数据 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// accountsHookFactory 创建账号数据 Hook。
|
||||||
|
() => useAccountsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待账号详情和 AI 配置请求完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// runtimeAssertion 等待首次运行状态轮询完成。
|
||||||
|
() => expect(getRuntimeMock).toHaveBeenCalled(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.accounts[0]).toMatchObject({ ai_enabled: true, max_discount_percent: 20, runtime_state: 'online', runtime_connected: true });
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('AI 配置失败不阻断账号列表,详情失败则结束加载', /* 当前回调验证两类并行请求的错误隔离。 */ async () => {
|
||||||
|
getAISettingsMock.mockRejectedValueOnce(new Error('AI 服务失败'));
|
||||||
|
// aiHook 是 AI 配置失败场景的账号数据 Hook 渲染结果。
|
||||||
|
const aiHook = renderHook(
|
||||||
|
// aiHookFactory 创建 AI 配置失败场景的 Hook。
|
||||||
|
() => useAccountsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待 AI 失败但账号详情成功的结果。
|
||||||
|
() => expect(aiHook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(aiHook.result.current.accounts).toHaveLength(1);
|
||||||
|
expect(aiHook.result.current.accounts[0].ai_enabled).toBe(false);
|
||||||
|
aiHook.unmount();
|
||||||
|
|
||||||
|
getDetailsMock.mockRejectedValueOnce(new Error('账号服务失败'));
|
||||||
|
// detailsHook 是账号详情失败场景的账号数据 Hook 渲染结果。
|
||||||
|
const detailsHook = renderHook(
|
||||||
|
// detailsHookFactory 创建账号详情失败场景的 Hook。
|
||||||
|
() => useAccountsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待账号详情失败状态收束。
|
||||||
|
() => expect(detailsHook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(detailsHook.result.current.accounts).toEqual([]);
|
||||||
|
expect(console.error).toHaveBeenCalled();
|
||||||
|
detailsHook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('运行状态轮询失败时保留账号列表并记录错误', /* 当前回调验证运行状态轮询异常分支。 */ async () => {
|
||||||
|
getRuntimeMock.mockRejectedValueOnce(new Error('运行状态服务失败'));
|
||||||
|
// hook 是运行状态轮询失败场景的账号数据 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// runtimeErrorHookFactory 创建运行状态轮询失败场景的 Hook。
|
||||||
|
() => useAccountsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待账号详情加载完成。
|
||||||
|
() => expect(hook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.accounts).toHaveLength(1);
|
||||||
|
expect(console.error).toHaveBeenCalledWith('加载账号运行状态失败:', expect.any(Error));
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('运行状态轮询完成后按计划安排下一轮查询', /* 当前回调验证账号状态轮询定时器回调。 */ async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
// hook 是账号轮询定时器场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// timerHookFactory 创建账号轮询定时器场景的 Hook。
|
||||||
|
() => useAccountsData(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// initialFlushAction 刷新初始账号和运行状态 Promise。
|
||||||
|
async () => { await Promise.resolve(); await Promise.resolve(); },
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// timerAction 推进两秒轮询定时器。
|
||||||
|
async () => { await vi.advanceTimersByTimeAsync(2_000); },
|
||||||
|
);
|
||||||
|
expect(getRuntimeMock).toHaveBeenCalledTimes(2);
|
||||||
|
hook.unmount();
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||||
|
import type { AccountDetail } from './api';
|
||||||
|
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
|
||||||
|
import { mergeAccountRuntimeStatuses } from './runtime';
|
||||||
|
import type { AccountAISettingsState } from './types';
|
||||||
|
|
||||||
|
// AccountsDataResult 暴露账号列表、加载状态和可复用的刷新动作。
|
||||||
|
export interface AccountsDataResult {
|
||||||
|
// accounts 是当前账号列表及其 AI、运行时展示字段。
|
||||||
|
accounts: AccountDetail[];
|
||||||
|
// setAccounts 允许页面在删除或任务设置保存后局部更新列表。
|
||||||
|
setAccounts: Dispatch<SetStateAction<AccountDetail[]>>;
|
||||||
|
// loading 表示账号基础数据是否正在加载。
|
||||||
|
loading: boolean;
|
||||||
|
// loadAccounts 刷新账号基础资料和 AI 设置。
|
||||||
|
loadAccounts: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeAccountAISettings 将 AI 配置补充到账号详情,缺省值保持页面原有行为。
|
||||||
|
export const mergeAccountAISettings = (
|
||||||
|
accounts: AccountDetail[],
|
||||||
|
allAISettings: AccountAISettingsState,
|
||||||
|
): AccountDetail[] => accounts.map(
|
||||||
|
// account 是待补充 AI 配置的账号对象。
|
||||||
|
account => ({
|
||||||
|
...account,
|
||||||
|
ai_enabled: allAISettings[account.id]?.ai_enabled ?? false,
|
||||||
|
max_discount_percent: allAISettings[account.id]?.max_discount_percent ?? 10,
|
||||||
|
max_discount_amount: allAISettings[account.id]?.max_discount_amount ?? 100,
|
||||||
|
max_bargain_rounds: allAISettings[account.id]?.max_bargain_rounds ?? 3,
|
||||||
|
custom_prompts: allAISettings[account.id]?.custom_prompts ?? '',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// useAccountsData 统一管理账号加载、AI 合并和运行状态短轮询。
|
||||||
|
export const useAccountsData = (): AccountsDataResult => {
|
||||||
|
// accounts 保存页面当前可见的账号详情。
|
||||||
|
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||||
|
// loading 表示首次加载或手动刷新的账号基础数据是否未完成。
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
// accountLoadGeneration 丢弃切换或连续刷新后到达的旧账号响应。
|
||||||
|
const accountLoadGeneration = useRef(0);
|
||||||
|
// accountLoadAbort 保存当前账号加载请求的取消控制器。
|
||||||
|
const accountLoadAbort = useRef<AbortController | null>(null);
|
||||||
|
|
||||||
|
// loadAccounts 并行读取账号详情和 AI 设置,并只提交最新请求结果。
|
||||||
|
const loadAccounts = useCallback(
|
||||||
|
// 账号加载回调并行请求详情和 AI 设置。
|
||||||
|
async () => {
|
||||||
|
// generation 标记本次账号刷新请求的代次。
|
||||||
|
const generation = ++accountLoadGeneration.current;
|
||||||
|
accountLoadAbort.current?.abort();
|
||||||
|
// controller 让新刷新开始时主动取消旧的网络请求。
|
||||||
|
const controller = new AbortController();
|
||||||
|
accountLoadAbort.current = controller;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
// options 将同一个取消信号传给两个彼此独立的请求。
|
||||||
|
const options = { signal: controller.signal };
|
||||||
|
// results 让账号详情和 AI 配置并行加载,AI 失败不阻断账号列表。
|
||||||
|
const [detailsResult, aiResult] = await Promise.allSettled([
|
||||||
|
getAccountDetails(options),
|
||||||
|
getAllAISettings(options),
|
||||||
|
]);
|
||||||
|
if (generation !== accountLoadGeneration.current) return;
|
||||||
|
if (detailsResult.status === 'rejected') throw detailsResult.reason;
|
||||||
|
// allAISettings 是按账号 ID 索引的 AI 配置快照。
|
||||||
|
const allAISettings = aiResult.status === 'fulfilled' ? aiResult.value : {};
|
||||||
|
if (aiResult.status === 'rejected') console.error('加载 AI 设置失败:', aiResult.reason);
|
||||||
|
setAccounts(mergeAccountAISettings(detailsResult.value, allAISettings));
|
||||||
|
} catch (error /* 账号加载错误 */) {
|
||||||
|
if (generation === accountLoadGeneration.current && !controller.signal.aborted) {
|
||||||
|
console.error('加载账号失败:', error);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (generation === accountLoadGeneration.current) setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
// 账号数据副作用负责首次加载和运行状态轮询。
|
||||||
|
() => {
|
||||||
|
// cancelled 表示页面已卸载,阻止轮询继续写入 React 状态。
|
||||||
|
let cancelled = false;
|
||||||
|
// timer 保存下一次运行状态轮询的句柄。
|
||||||
|
let timer: number | null = null;
|
||||||
|
// runtimeController 取消页面卸载时仍在执行的运行状态请求。
|
||||||
|
const runtimeController = new AbortController();
|
||||||
|
|
||||||
|
// pollRuntimeStatuses 读取进程内运行状态并安排下一次轮询。
|
||||||
|
const pollRuntimeStatuses = async () => {
|
||||||
|
try {
|
||||||
|
// statuses 是后端按账号 ID 返回的最新运行状态快照。
|
||||||
|
const statuses = await getAccountRuntimeStatuses({ signal: runtimeController.signal, timeoutMs: 10_000 });
|
||||||
|
if (!cancelled) {
|
||||||
|
setAccounts(
|
||||||
|
// current 是运行状态轮询开始前的最新账号列表。
|
||||||
|
current => mergeAccountRuntimeStatuses(current, statuses),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error /* 运行状态轮询错误 */) {
|
||||||
|
if (!cancelled) console.error('加载账号运行状态失败:', error);
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) {
|
||||||
|
timer = window.setTimeout(
|
||||||
|
// timerCallback 在两秒后启动下一次运行状态轮询。
|
||||||
|
() => void pollRuntimeStatuses(),
|
||||||
|
2_000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void loadAccounts().finally(
|
||||||
|
// loadFinished 在初始账号加载完成后启动第一次状态轮询。
|
||||||
|
() => {
|
||||||
|
if (!cancelled) void pollRuntimeStatuses();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// cleanup 在页面卸载时停止账号请求和运行状态轮询。
|
||||||
|
const cleanup = () => {
|
||||||
|
cancelled = true;
|
||||||
|
runtimeController.abort();
|
||||||
|
accountLoadGeneration.current += 1;
|
||||||
|
accountLoadAbort.current?.abort();
|
||||||
|
if (timer !== null) window.clearTimeout(timer);
|
||||||
|
};
|
||||||
|
return cleanup;
|
||||||
|
},
|
||||||
|
[loadAccounts],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { accounts, setAccounts, loading, loadAccounts };
|
||||||
|
};
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
|
||||||
|
import React from 'react';
|
||||||
|
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../../shared/api-contract/accounts';
|
||||||
|
|
||||||
|
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
|
||||||
|
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
|
||||||
|
accounts: [
|
||||||
|
{ id: 'account-1', nickname: 'Alpha', remark: '主账号', enabled: true, runtime_message: '在线' },
|
||||||
|
{ id: 'account-2', nickname: 'Beta', remark: '备用账号', enabled: false, runtime_message: '已停用' },
|
||||||
|
] as AccountDetail[],
|
||||||
|
setAccounts: vi.fn(),
|
||||||
|
loadAccounts: vi.fn(),
|
||||||
|
updateAccountStatus: vi.fn(),
|
||||||
|
deleteAccount: vi.fn(),
|
||||||
|
generateQRLogin: vi.fn(),
|
||||||
|
checkQRLoginStatus: vi.fn(),
|
||||||
|
completeQRVerification: vi.fn(),
|
||||||
|
refreshAccountProfile: vi.fn(),
|
||||||
|
pollerStart: vi.fn(),
|
||||||
|
pollerStop: vi.fn(),
|
||||||
|
requestNext: vi.fn(),
|
||||||
|
requestIsCurrent: vi.fn(),
|
||||||
|
requestCancel: vi.fn(),
|
||||||
|
pollCallbacks: null as Record<string, (...args: any[]) => void> | null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({
|
||||||
|
useAccountsData: /* useAccountsDataMock 返回固定账号列表和刷新操作。 */ () => ({
|
||||||
|
accounts: accountListMocks.accounts,
|
||||||
|
setAccounts: accountListMocks.setAccounts,
|
||||||
|
loading: false,
|
||||||
|
loadAccounts: accountListMocks.loadAccounts,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({
|
||||||
|
useAccountSubmodules: /* useAccountSubmodulesMock 返回不阻断页面渲染的子模块状态。 */ () => ({
|
||||||
|
longLogin: false,
|
||||||
|
notifChannels: [],
|
||||||
|
selectedChannelIds: [],
|
||||||
|
bindingsLoaded: true,
|
||||||
|
bindingsLoading: false,
|
||||||
|
bindingsLoadError: '',
|
||||||
|
aiSettings: {},
|
||||||
|
saving: false,
|
||||||
|
passwordLoginView: { status: 'idle', message: '' },
|
||||||
|
setAiSettings: vi.fn(),
|
||||||
|
setBindingsDirty: vi.fn(),
|
||||||
|
openEditModal: vi.fn(),
|
||||||
|
closeEditModal: vi.fn(),
|
||||||
|
openAIModal: vi.fn(),
|
||||||
|
closeAIModal: vi.fn(),
|
||||||
|
loadNotificationBindings: vi.fn(),
|
||||||
|
toggleNotificationChannel: vi.fn(),
|
||||||
|
handleLongLoginToggle: vi.fn(),
|
||||||
|
handleSaveAISettings: vi.fn(),
|
||||||
|
handleSaveEdit: vi.fn(),
|
||||||
|
handleRestartPause: vi.fn(),
|
||||||
|
handlePasswordLogin: vi.fn(),
|
||||||
|
handleCancelPasswordLogin: vi.fn(),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({
|
||||||
|
updateAccountStatus: accountListMocks.updateAccountStatus,
|
||||||
|
deleteAccount: accountListMocks.deleteAccount,
|
||||||
|
generateQRLogin: accountListMocks.generateQRLogin,
|
||||||
|
checkQRLoginStatus: accountListMocks.checkQRLoginStatus,
|
||||||
|
completeQRVerification: accountListMocks.completeQRVerification,
|
||||||
|
refreshAccountProfile: accountListMocks.refreshAccountProfile,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({
|
||||||
|
createLatestRequestGate: /* requestGateFactory 创建二维码请求代次门禁。 */ () => ({
|
||||||
|
next: accountListMocks.requestNext,
|
||||||
|
isCurrent: accountListMocks.requestIsCurrent,
|
||||||
|
cancel: accountListMocks.requestCancel,
|
||||||
|
}),
|
||||||
|
createQRLoginPoller: /* qrPollerFactory 创建二维码轮询控制器。 */ () => ({
|
||||||
|
start: accountListMocks.pollerStart,
|
||||||
|
stop: accountListMocks.pollerStop,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => {
|
||||||
|
// AccountCardMock 渲染页面测试需要的账号操作入口。
|
||||||
|
const AccountCardMock: React.FC<any> = (props /* props 表示账号卡片及其事件回调。 */) => (
|
||||||
|
<div data-testid={`account-card-${props.account.id}`}>
|
||||||
|
<span>{props.account.nickname}</span>
|
||||||
|
<button onClick={/* deleteAction 触发账号删除确认。 */ () => props.onDelete(props.account)}>删除</button>
|
||||||
|
<button onClick={/* toggleAction 切换账号启用状态。 */ () => props.onToggle(props.account.id, props.account.enabled)}>切换</button>
|
||||||
|
<button onClick={/* refreshAction 刷新账号资料。 */ () => props.onRefreshProfile(props.account)}>刷新资料</button>
|
||||||
|
<button onClick={/* reauthorizeAction 启动账号二维码重新授权。 */ () => props.onReauthorize(props.account)}>重新授权</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
return { AccountCard: AccountCardMock };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('../components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => {
|
||||||
|
// AccountDeleteDialogMock 展示删除错误并暴露确认/关闭操作。
|
||||||
|
const AccountDeleteDialogMock: React.FC<any> = (props /* props 表示删除弹窗及其操作回调。 */) => (
|
||||||
|
<div data-testid="delete-dialog">
|
||||||
|
<span>{props.error}</span>
|
||||||
|
<button onClick={/* confirmAction 确认删除当前账号。 */ () => props.onConfirm()}>确认删除</button>
|
||||||
|
<button onClick={/* closeAction 关闭删除确认弹窗。 */ () => props.onClose()}>取消</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
return { AccountDeleteDialog: AccountDeleteDialogMock };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('../components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => {
|
||||||
|
// AccountQRCodeModalMock 展示二维码状态并暴露关闭操作。
|
||||||
|
const AccountQRCodeModalMock: React.FC<any> = (props /* props 表示二维码弹窗及其操作回调。 */) => (
|
||||||
|
<div data-testid="qr-modal">
|
||||||
|
<span>{props.status}</span>
|
||||||
|
<button onClick={/* closeAction 关闭二维码登录弹窗。 */ () => props.onClose()}>关闭二维码</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
return { AccountQRCodeModal: AccountQRCodeModalMock };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('../components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({
|
||||||
|
AccountEditModal: /* AccountEditModalMock 表示账号编辑弹窗替身。 */ () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({
|
||||||
|
AccountAISettingsModal: /* AccountAISettingsModalMock 表示 AI 设置弹窗替身。 */ () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../components/AccountAutomationModal', /* automationModalMockFactory 提供账号任务弹窗替身。 */ () => ({
|
||||||
|
default: /* AccountAutomationModalMock 表示账号自动化弹窗替身。 */ () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import AccountList from './AccountList';
|
||||||
|
|
||||||
|
describe('AccountList 页面组合行为', /* 当前回调验证账号列表页面的搜索、删除、资料和二维码流程。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置账号页面 API、请求门禁和浏览器提示替身。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
accountListMocks.requestNext.mockReturnValue(1);
|
||||||
|
accountListMocks.requestIsCurrent.mockReturnValue(true);
|
||||||
|
accountListMocks.generateQRLogin.mockResolvedValue({ success: true, qr_code_url: 'qr-url', session_id: 'session-1' });
|
||||||
|
accountListMocks.completeQRVerification.mockResolvedValue({ success: true, account_id: 'account-1' });
|
||||||
|
accountListMocks.updateAccountStatus.mockResolvedValue({ success: true });
|
||||||
|
accountListMocks.deleteAccount.mockResolvedValue({ success: true });
|
||||||
|
accountListMocks.refreshAccountProfile.mockResolvedValue({ success: true });
|
||||||
|
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽页面资料刷新提示。 */ () => undefined);
|
||||||
|
accountListMocks.pollerStart.mockImplementation(/* pollerStartImplementation 保存二维码轮询回调。 */ (_sessionId: string, _check: unknown, callbacks: Record<string, (...args: any[]) => void>) => {
|
||||||
|
accountListMocks.pollCallbacks = callbacks;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(/* 当前回调清理页面 DOM 和浏览器提示替身。 */ () => {
|
||||||
|
cleanup();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('搜索只展示匹配账号并保留总数提示', /* 当前回调验证账号搜索过滤行为。 */ () => {
|
||||||
|
render(<AccountList />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('account-card-account-1')).toBeTruthy();
|
||||||
|
expect(screen.getByTestId('account-card-account-2')).toBeTruthy();
|
||||||
|
fireEvent.change(screen.getByPlaceholderText('搜索昵称 / 备注 / 账号ID'), { target: { value: 'Alpha' } });
|
||||||
|
|
||||||
|
expect(screen.getByTestId('account-card-account-1')).toBeTruthy();
|
||||||
|
expect(screen.queryByTestId('account-card-account-2')).toBeNull();
|
||||||
|
expect(screen.getByText('当前显示 1 / 2 个账号')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('删除确认成功后调用 API 并移除目标账号', /* 当前回调验证删除确认和本地列表更新边界。 */ async () => {
|
||||||
|
render(<AccountList />);
|
||||||
|
fireEvent.click(screen.getAllByText('删除')[0]);
|
||||||
|
expect(screen.getByTestId('delete-dialog')).toBeTruthy();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('确认删除'));
|
||||||
|
await waitFor(/* deleteAssertion 等待删除请求完成。 */ () => expect(accountListMocks.deleteAccount).toHaveBeenCalledWith('account-1'));
|
||||||
|
expect(accountListMocks.setAccounts).toHaveBeenCalledTimes(1);
|
||||||
|
// nextAccounts 是页面删除逻辑提交给状态 Setter 的过滤函数结果。
|
||||||
|
const nextAccounts = accountListMocks.setAccounts.mock.calls[0][0](accountListMocks.accounts);
|
||||||
|
expect(nextAccounts).toEqual([accountListMocks.accounts[1]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('账号卡片操作分别触发状态切换和资料刷新', /* 当前回调验证账号卡片向页面协调器转发操作。 */ async () => {
|
||||||
|
render(<AccountList />);
|
||||||
|
fireEvent.click(screen.getAllByText('切换')[0]);
|
||||||
|
await waitFor(/* toggleAssertion 等待账号状态更新请求完成。 */ () => expect(accountListMocks.updateAccountStatus).toHaveBeenCalledWith('account-1', false));
|
||||||
|
expect(accountListMocks.loadAccounts).toHaveBeenCalled();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getAllByText('刷新资料')[0]);
|
||||||
|
await waitFor(/* refreshAssertion 等待资料刷新请求完成。 */ () => expect(accountListMocks.refreshAccountProfile).toHaveBeenCalledWith('account-1'));
|
||||||
|
expect(accountListMocks.loadAccounts).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('二维码授权启动轮询并在成功后保存会话结果', /* 当前回调验证二维码生成、轮询成功和延迟收束流程。 */ async () => {
|
||||||
|
render(<AccountList />);
|
||||||
|
fireEvent.click(screen.getByText('扫码添加新账号'));
|
||||||
|
expect(await screen.findByTestId('qr-modal')).toBeTruthy();
|
||||||
|
await waitFor(/* pollerAssertion 等待二维码轮询器启动。 */ () => expect(accountListMocks.pollerStart).toHaveBeenCalledWith('session-1', accountListMocks.checkQRLoginStatus, expect.anything()));
|
||||||
|
expect(screen.getByText('waiting')).toBeTruthy();
|
||||||
|
|
||||||
|
await accountListMocks.pollCallbacks?.onSuccess();
|
||||||
|
expect(accountListMocks.completeQRVerification).toHaveBeenCalledWith('session-1', undefined);
|
||||||
|
await waitFor(/* successAssertion 等待二维码成功状态渲染。 */ () => expect(screen.getByText('success')).toBeTruthy());
|
||||||
|
await waitFor(/* reloadAssertion 等待成功后的账号列表刷新。 */ () => expect(accountListMocks.loadAccounts).toHaveBeenCalled(), { timeout: 2_000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('关闭二维码弹窗会停止轮询并取消请求', /* 当前回调验证页面卸载前的二维码资源收束。 */ async () => {
|
||||||
|
// view 是关闭二维码资源后用于卸载页面的渲染结果。
|
||||||
|
const view = render(<AccountList />);
|
||||||
|
fireEvent.click(screen.getByText('扫码添加新账号'));
|
||||||
|
expect(await screen.findByTestId('qr-modal')).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByText('关闭二维码'));
|
||||||
|
|
||||||
|
expect(accountListMocks.pollerStop).toHaveBeenCalled();
|
||||||
|
expect(accountListMocks.requestCancel).toHaveBeenCalled();
|
||||||
|
view.unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
import { Loader2,QrCode,User } from 'lucide-react';
|
||||||
|
import React,{ useState } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { AccountDetail } from '../api';
|
||||||
|
import {
|
||||||
|
deleteAccount,
|
||||||
|
refreshAccountProfile,
|
||||||
|
updateAccountStatus,
|
||||||
|
} from '../api';
|
||||||
|
import { AccountAISettingsModal } from '../components/AccountAISettingsModal';
|
||||||
|
import AccountAutomationModal from '../components/AccountAutomationModal';
|
||||||
|
import { AccountCard } from '../components/AccountCard';
|
||||||
|
import { AccountDeleteDialog } from '../components/AccountDeleteDialog';
|
||||||
|
import { AccountEditModal } from '../components/AccountEditModal';
|
||||||
|
import { AccountQRCodeModal } from '../components/AccountQRCodeModal';
|
||||||
|
import { useAccountsData } from '../hooks';
|
||||||
|
import { useAccountQRCodeLogin } from '../qrLogin';
|
||||||
|
import { useAccountSubmodules,type AccountModalType } from '../submoduleHooks';
|
||||||
|
import type { AccountEditForm } from '../types';
|
||||||
|
|
||||||
|
// AccountList 渲染账号列表组件。
|
||||||
|
const AccountList: React.FC = () => {
|
||||||
|
// accountData 保存账号列表及其加载控制器。
|
||||||
|
const { accounts, setAccounts, loading, loadAccounts } = useAccountsData();
|
||||||
|
// accountSearch 保存列表过滤关键词。
|
||||||
|
const [accountSearch, setAccountSearch] = useState('');
|
||||||
|
// refreshingProfileId 保存正在刷新资料的账号 ID。
|
||||||
|
const [refreshingProfileId, setRefreshingProfileId] = useState<string>('');
|
||||||
|
// deletingAccountId 保存正在删除的账号 ID。
|
||||||
|
const [deletingAccountId, setDeletingAccountId] = useState<string>('');
|
||||||
|
// deleteDialogAccount 保存待确认删除的账号。
|
||||||
|
const [deleteDialogAccount, setDeleteDialogAccount] = useState<AccountDetail | null>(null);
|
||||||
|
// deleteError 保存删除失败提示。
|
||||||
|
const [deleteError, setDeleteError] = useState('');
|
||||||
|
// activeModal 保存当前打开的账号配置弹窗。
|
||||||
|
const [activeModal, setActiveModal] = useState<AccountModalType>(null);
|
||||||
|
// editingAccount 保存当前编辑账号。
|
||||||
|
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||||
|
// taskAccount 保存当前打开自动化任务弹窗的账号。
|
||||||
|
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
|
||||||
|
|
||||||
|
// 编辑表单状态。
|
||||||
|
// editForm 保存编辑弹窗中的账号草稿。
|
||||||
|
const [editForm, setEditForm] = useState<AccountEditForm>({
|
||||||
|
remark: '',
|
||||||
|
cookie: '',
|
||||||
|
auto_confirm: false,
|
||||||
|
pause_duration: 0,
|
||||||
|
username: '',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: false,
|
||||||
|
showLoginPassword: false,
|
||||||
|
clear_password: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// accountSubmodules 集中管理编辑弹窗的长登录、通知绑定、AI 和密码登录状态。
|
||||||
|
const accountSubmodules = useAccountSubmodules({
|
||||||
|
editingAccount,
|
||||||
|
setEditingAccount,
|
||||||
|
setActiveModal,
|
||||||
|
editForm,
|
||||||
|
setEditForm,
|
||||||
|
loadAccounts,
|
||||||
|
});
|
||||||
|
// submoduleHandlers 保存编辑弹窗子模块的状态和事件处理函数。
|
||||||
|
const {
|
||||||
|
longLogin,
|
||||||
|
notifChannels,
|
||||||
|
selectedChannelIds,
|
||||||
|
bindingsLoaded,
|
||||||
|
bindingsLoading,
|
||||||
|
bindingsLoadError,
|
||||||
|
aiSettings,
|
||||||
|
saving,
|
||||||
|
passwordLoginView,
|
||||||
|
setAiSettings,
|
||||||
|
setBindingsDirty,
|
||||||
|
openEditModal,
|
||||||
|
closeEditModal,
|
||||||
|
openAIModal,
|
||||||
|
closeAIModal,
|
||||||
|
loadNotificationBindings,
|
||||||
|
toggleNotificationChannel,
|
||||||
|
handleLongLoginToggle,
|
||||||
|
handleSaveAISettings,
|
||||||
|
handleSaveEdit,
|
||||||
|
handleRestartPause,
|
||||||
|
handlePasswordLogin,
|
||||||
|
handleCancelPasswordLogin,
|
||||||
|
} = accountSubmodules;
|
||||||
|
|
||||||
|
// qrLogin 集中管理二维码弹窗状态、轮询、风控验证和异步资源收束。
|
||||||
|
const qrLogin = useAccountQRCodeLogin({ onLoginSuccess: loadAccounts });
|
||||||
|
// qrViewState 解构二维码弹窗向页面展示和触发操作所需的最小状态。
|
||||||
|
const {
|
||||||
|
showQRModal,
|
||||||
|
qrCodeUrl,
|
||||||
|
qrStatus,
|
||||||
|
qrErrorMessage,
|
||||||
|
verificationScreenshot,
|
||||||
|
faceQrUrl,
|
||||||
|
qrReauthTarget,
|
||||||
|
startQRLogin,
|
||||||
|
closeQRModal,
|
||||||
|
} = qrLogin;
|
||||||
|
|
||||||
|
// handleToggle 切换账号启用状态。
|
||||||
|
const handleToggle = async (id: string, currentStatus: boolean) => {
|
||||||
|
await updateAccountStatus(id, !currentStatus);
|
||||||
|
loadAccounts();
|
||||||
|
};
|
||||||
|
|
||||||
|
// openDeleteDialog 打开账号删除确认框。
|
||||||
|
const openDeleteDialog = (account: AccountDetail) => {
|
||||||
|
if (deletingAccountId) return;
|
||||||
|
setDeleteError('');
|
||||||
|
setDeleteDialogAccount(account);
|
||||||
|
};
|
||||||
|
|
||||||
|
// closeDeleteDialog 关闭账号删除确认框。
|
||||||
|
const closeDeleteDialog = () => {
|
||||||
|
if (deletingAccountId) return;
|
||||||
|
setDeleteError('');
|
||||||
|
setDeleteDialogAccount(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
// confirmDeleteAccount 执行账号删除并刷新列表状态。
|
||||||
|
const confirmDeleteAccount = async () => {
|
||||||
|
// account 保存当前确认删除的账号。
|
||||||
|
const account = deleteDialogAccount;
|
||||||
|
if (!account || deletingAccountId) return;
|
||||||
|
setDeletingAccountId(account.id);
|
||||||
|
setDeleteError('');
|
||||||
|
try {
|
||||||
|
await deleteAccount(account.id);
|
||||||
|
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.filter(/* 当前回调处理集合中的单个元素。 */ item => item.id !== account.id));
|
||||||
|
setDeleteDialogAccount(null);
|
||||||
|
} catch (/* error 保存账号删除请求的失败原因,仅转换为界面提示。 */ error: any) {
|
||||||
|
console.error('删除账号失败:', error);
|
||||||
|
setDeleteError(error?.message || '删除账号失败,请稍后重试');
|
||||||
|
} finally {
|
||||||
|
setDeletingAccountId('');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// handleRefreshProfile 刷新账号资料并同步列表。
|
||||||
|
const handleRefreshProfile = async (account: AccountDetail) => {
|
||||||
|
setRefreshingProfileId(account.id);
|
||||||
|
try {
|
||||||
|
// res 保存资料刷新接口返回值。
|
||||||
|
const res = await refreshAccountProfile(account.id);
|
||||||
|
if (res?.profile_error) {
|
||||||
|
alert('资料刷新失败:' + res.profile_error);
|
||||||
|
}
|
||||||
|
await loadAccounts();
|
||||||
|
} catch (/* error 保存资料刷新请求的失败原因,仅转换为界面提示。 */ error: any) {
|
||||||
|
console.error('刷新账号资料失败:', error);
|
||||||
|
alert(error?.message || '刷新账号资料失败,请先重新授权该账号');
|
||||||
|
} finally {
|
||||||
|
setRefreshingProfileId('');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-brand animate-spin"/></div>;
|
||||||
|
|
||||||
|
// filteredAccounts 过滤后的账号列表,负责当前功能中的对应处理。
|
||||||
|
const filteredAccounts = accounts.filter(/* 当前回调处理集合中的单个元素。 */ account => {
|
||||||
|
// keyword 搜索关键词。
|
||||||
|
const keyword = accountSearch.trim().toLowerCase();
|
||||||
|
if (!keyword) return true;
|
||||||
|
return [
|
||||||
|
account.id,
|
||||||
|
account.nickname,
|
||||||
|
account.remark,
|
||||||
|
account.username,
|
||||||
|
account.runtime_message,
|
||||||
|
].some(/* 当前回调处理用户交互或异步状态变化。 */ value => (value || '').toLowerCase().includes(keyword));
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 animate-fade-in relative">
|
||||||
|
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4">
|
||||||
|
<div>
|
||||||
|
<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 flex-col sm:flex-row gap-3">
|
||||||
|
<input
|
||||||
|
value={accountSearch}
|
||||||
|
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setAccountSearch(event.target.value)}
|
||||||
|
placeholder="搜索昵称 / 备注 / 账号ID"
|
||||||
|
className="ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => startQRLogin()}
|
||||||
|
className="ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95"
|
||||||
|
>
|
||||||
|
<QrCode className="w-5 h-5" />
|
||||||
|
扫码添加新账号
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2">
|
||||||
|
<div className="font-bold">当前显示 {filteredAccounts.length} / {accounts.length} 个账号</div>
|
||||||
|
<div className="text-blue-700">如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Account Grid */}
|
||||||
|
<div className="grid grid-cols-1 gap-6">
|
||||||
|
{filteredAccounts.map(/* 当前回调处理集合中的单个元素。 */ account => (
|
||||||
|
<AccountCard
|
||||||
|
key={account.id}
|
||||||
|
account={account}
|
||||||
|
refreshing={refreshingProfileId === account.id}
|
||||||
|
deleting={deletingAccountId === account.id}
|
||||||
|
onRefreshProfile={handleRefreshProfile}
|
||||||
|
onReauthorize={startQRLogin}
|
||||||
|
onEdit={openEditModal}
|
||||||
|
onAI={openAIModal}
|
||||||
|
onTasks={setTaskAccount}
|
||||||
|
onToggle={handleToggle}
|
||||||
|
onDelete={openDeleteDialog}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{accounts.length === 0 && (
|
||||||
|
<div className="ios-card p-12 text-center">
|
||||||
|
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||||
|
<User className="w-10 h-10 text-gray-400" />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-lg font-bold text-gray-900">暂无账号</h3>
|
||||||
|
<p className="text-gray-500 mt-1">请点击右上角扫码添加您的闲鱼账号</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{accounts.length > 0 && filteredAccounts.length === 0 && (
|
||||||
|
<div className="ios-card p-12 text-center">
|
||||||
|
<h3 className="text-lg font-bold text-gray-900">没有匹配的账号</h3>
|
||||||
|
<p className="text-gray-500 mt-1">换一个关键词搜索昵称、备注或账号ID。</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{taskAccount && createPortal(
|
||||||
|
<AccountAutomationModal
|
||||||
|
account={taskAccount}
|
||||||
|
onClose={/* 当前回调处理用户交互或异步状态变化。 */ () => setTaskAccount(null)}
|
||||||
|
onSaved={/* 当前回调处理集合中的单个元素。 */ settings => {
|
||||||
|
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.map(/* 当前回调处理集合中的单个元素。 */ account => account.id === taskAccount.id ? {
|
||||||
|
...account,
|
||||||
|
auto_rate_enabled: settings.auto_rate_enabled,
|
||||||
|
rate_content: settings.rate_content,
|
||||||
|
auto_polish_enabled: settings.auto_polish_enabled,
|
||||||
|
polish_time: settings.polish_time,
|
||||||
|
last_rate_scan_at: settings.last_rate_scan_at,
|
||||||
|
last_polish_date: settings.last_polish_date,
|
||||||
|
last_polish_at: settings.last_polish_at,
|
||||||
|
} : account));
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
|
||||||
|
{deleteDialogAccount && (
|
||||||
|
<AccountDeleteDialog
|
||||||
|
account={deleteDialogAccount}
|
||||||
|
deleting={deletingAccountId === deleteDialogAccount.id}
|
||||||
|
error={deleteError}
|
||||||
|
onClose={closeDeleteDialog}
|
||||||
|
onConfirm={confirmDeleteAccount}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showQRModal && (
|
||||||
|
<AccountQRCodeModal
|
||||||
|
target={qrReauthTarget}
|
||||||
|
status={qrStatus}
|
||||||
|
codeUrl={qrCodeUrl}
|
||||||
|
errorMessage={qrErrorMessage}
|
||||||
|
faceQrUrl={faceQrUrl}
|
||||||
|
verificationScreenshot={verificationScreenshot}
|
||||||
|
onClose={closeQRModal}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 编辑账号弹窗由 accounts feature 组件负责渲染和表单交互。 */}
|
||||||
|
{activeModal === 'edit' && editingAccount && (
|
||||||
|
<AccountEditModal
|
||||||
|
account={editingAccount}
|
||||||
|
editForm={editForm}
|
||||||
|
setEditForm={setEditForm}
|
||||||
|
saving={saving}
|
||||||
|
onClose={closeEditModal}
|
||||||
|
onSave={handleSaveEdit}
|
||||||
|
onRestartPause={handleRestartPause}
|
||||||
|
longLogin={longLogin}
|
||||||
|
onToggleLongLogin={handleLongLoginToggle}
|
||||||
|
passwordLoginView={passwordLoginView}
|
||||||
|
onPasswordLogin={handlePasswordLogin}
|
||||||
|
onCancelPasswordLogin={handleCancelPasswordLogin}
|
||||||
|
notifChannels={notifChannels}
|
||||||
|
selectedChannelIds={selectedChannelIds}
|
||||||
|
bindingsLoaded={bindingsLoaded}
|
||||||
|
bindingsLoading={bindingsLoading}
|
||||||
|
bindingsLoadError={bindingsLoadError}
|
||||||
|
onRetryBindings={/* 当前回调处理用户交互或异步状态变化。 */ () => loadNotificationBindings(editingAccount.id)}
|
||||||
|
onToggleChannel={toggleNotificationChannel}
|
||||||
|
onSettingsDirty={/* 当前回调处理用户交互或异步状态变化。 */ () => setBindingsDirty(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
|
||||||
|
{activeModal === 'ai-settings' && editingAccount && (
|
||||||
|
<AccountAISettingsModal
|
||||||
|
account={editingAccount}
|
||||||
|
settings={aiSettings}
|
||||||
|
saving={saving}
|
||||||
|
onChange={setAiSettings}
|
||||||
|
onClose={closeAIModal}
|
||||||
|
onSave={handleSaveAISettings}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AccountList;
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { act,renderHook } from '@testing-library/react';
|
||||||
|
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||||
|
|
||||||
|
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
|
||||||
|
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
|
||||||
|
generateQRLogin: vi.fn(),
|
||||||
|
checkQRLoginStatus: vi.fn(),
|
||||||
|
completeQRVerification: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('./api', /* qrApiMockFactory 提供二维码登录接口替身。 */ () => ({
|
||||||
|
generateQRLogin: qrLoginMocks.generateQRLogin,
|
||||||
|
checkQRLoginStatus: qrLoginMocks.checkQRLoginStatus,
|
||||||
|
completeQRVerification: qrLoginMocks.completeQRVerification,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { useAccountQRCodeLogin } from './qrLogin';
|
||||||
|
|
||||||
|
// accountFixture 表示二维码重新授权测试使用的账号。
|
||||||
|
const accountFixture: AccountDetail = {
|
||||||
|
id: 'account-1',
|
||||||
|
nickname: 'Alpha',
|
||||||
|
remark: '主账号',
|
||||||
|
enabled: true,
|
||||||
|
auto_confirm: false,
|
||||||
|
runtime_message: '在线',
|
||||||
|
};
|
||||||
|
|
||||||
|
// flushMicrotasks 等待轮询请求和回调完成。
|
||||||
|
const flushMicrotasks = async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('useAccountQRCodeLogin 二维码登录协调器', /* 当前回调验证二维码生成、轮询、验证和清理边界。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置二维码接口替身并启用可控定时器。 */ () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
qrLoginMocks.generateQRLogin.mockResolvedValue({ success: true, qr_code_url: 'qr-url', session_id: 'session-1' });
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValue({ status: 'waiting' });
|
||||||
|
qrLoginMocks.completeQRVerification.mockResolvedValue({ success: true, account_id: 'account-1' });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(/* 当前回调恢复真实定时器,避免污染其他测试。 */ () => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('成功登录后完成持久化并延迟刷新账号列表', /* 当前回调验证二维码成功的完整生命周期。 */ async () => {
|
||||||
|
// onLoginSuccess 刷新登录成功后的账号列表。
|
||||||
|
const onLoginSuccess = vi.fn();
|
||||||
|
// hook 保存二维码登录 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(/* hookFactory 创建二维码登录 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess }));
|
||||||
|
|
||||||
|
await act(/* startAction 启动二维码登录流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin(accountFixture);
|
||||||
|
});
|
||||||
|
expect(hook.result.current.qrStatus).toBe('waiting');
|
||||||
|
expect(hook.result.current.qrCodeUrl).toBe('qr-url');
|
||||||
|
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'user-1' });
|
||||||
|
await act(/* pollAction 触发二维码状态轮询。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(qrLoginMocks.completeQRVerification).toHaveBeenCalledWith('session-1', 'account-1');
|
||||||
|
expect(hook.result.current.qrStatus).toBe('success');
|
||||||
|
await act(/* closeAction 推进成功后的延迟关闭定时器。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
});
|
||||||
|
expect(onLoginSuccess).toHaveBeenCalledTimes(1);
|
||||||
|
expect(hook.result.current.showQRModal).toBe(false);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('风控验证状态会展示截图和人脸二维码', /* 当前回调验证风控中间态数据透传。 */ async () => {
|
||||||
|
// hook 保存风控验证场景的二维码登录 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建风控验证场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
await act(/* startAction 启动二维码登录流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin(accountFixture);
|
||||||
|
});
|
||||||
|
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({
|
||||||
|
status: 'verification_required',
|
||||||
|
verification_screenshot: 'screenshot-url',
|
||||||
|
face_qr_url: 'face-qr-url',
|
||||||
|
});
|
||||||
|
await act(/* pollAction 触发风控验证状态轮询。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(hook.result.current.qrStatus).toBe('verification');
|
||||||
|
expect(hook.result.current.verificationScreenshot).toBe('screenshot-url');
|
||||||
|
expect(hook.result.current.faceQrUrl).toBe('face-qr-url');
|
||||||
|
expect(hook.result.current.qrReauthTarget).toEqual(accountFixture);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('生成二维码失败时展示接口错误', /* 当前回调验证二维码生成异常反馈。 */ async () => {
|
||||||
|
qrLoginMocks.generateQRLogin.mockResolvedValueOnce({ success: false, message: '登录服务不可用' });
|
||||||
|
// hook 保存二维码生成异常场景的 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建二维码生成异常场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
|
||||||
|
await act(/* startAction 启动会失败的二维码生成流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(hook.result.current.qrStatus).toBe('error');
|
||||||
|
expect(hook.result.current.qrErrorMessage).toBe('登录服务不可用');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('持久化失败时将成功轮询转换为错误状态', /* 当前回调验证扫码成功后的保存失败边界。 */ async () => {
|
||||||
|
qrLoginMocks.completeQRVerification.mockResolvedValueOnce({ success: false, message: '账号保存失败' });
|
||||||
|
// hook 保存持久化失败场景的 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建保存失败场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
await act(/* startAction 启动二维码登录流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success' });
|
||||||
|
await act(/* pollAction 触发成功状态并执行持久化。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(hook.result.current.qrStatus).toBe('error');
|
||||||
|
expect(hook.result.current.showQRModal).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('扫描、终止和轮询异常状态均能更新页面状态', /* 当前回调验证二维码轮询的非成功状态回调。 */ async () => {
|
||||||
|
// hook 保存二维码状态切换场景的 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建二维码状态切换场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
await act(/* startAction 启动二维码登录流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'scanned' });
|
||||||
|
await act(/* scannedAction 触发已扫描状态轮询。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
expect(hook.result.current.qrStatus).toBe('waiting');
|
||||||
|
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'expired' });
|
||||||
|
await act(/* terminalAction 触发二维码过期状态轮询。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
expect(hook.result.current.qrStatus).toBe('error');
|
||||||
|
|
||||||
|
await act(/* restartAction 重新启动二维码以验证轮询异常。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockRejectedValueOnce(new Error('网络不可用'));
|
||||||
|
await act(/* pollErrorAction 触发二维码轮询异常。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
expect(hook.result.current.qrStatus).toBe('error');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('二维码响应缺少必要字段时使用默认错误提示', /* 当前回调验证二维码响应结构不完整的错误提示。 */ async () => {
|
||||||
|
qrLoginMocks.generateQRLogin.mockResolvedValueOnce({ success: true });
|
||||||
|
// hook 保存二维码响应缺字段场景的 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建响应缺字段场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
|
||||||
|
await act(/* startAction 启动响应缺字段的二维码流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(hook.result.current.qrStatus).toBe('error');
|
||||||
|
expect(hook.result.current.qrErrorMessage).toBe('闲鱼未返回可用的登录二维码');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('成功后的手动关闭会清理延迟关闭定时器', /* 当前回调验证成功状态下主动关闭的资源清理。 */ async () => {
|
||||||
|
// hook 保存成功后主动关闭场景的 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建成功后主动关闭场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
await act(/* startAction 启动二维码登录流程。 */ async () => {
|
||||||
|
await hook.result.current.startQRLogin();
|
||||||
|
});
|
||||||
|
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success' });
|
||||||
|
await act(/* pollAction 触发二维码成功状态。 */ async () => {
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
await flushMicrotasks();
|
||||||
|
});
|
||||||
|
|
||||||
|
act(/* closeAction 在延迟关闭前主动关闭二维码弹窗。 */ () => {
|
||||||
|
hook.result.current.closeQRModal();
|
||||||
|
});
|
||||||
|
expect(hook.result.current.showQRModal).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('关闭弹窗会取消未完成的二维码生成请求', /* 当前回调验证关闭操作的异步资源收束。 */ async () => {
|
||||||
|
// resolveGeneration 允许测试在关闭后完成原始请求。
|
||||||
|
let resolveGeneration: ((value: {
|
||||||
|
/** success 表示二维码生成请求是否成功。 */
|
||||||
|
success: boolean;
|
||||||
|
/** qr_code_url 表示返回的二维码地址。 */
|
||||||
|
qr_code_url?: string;
|
||||||
|
/** session_id 表示二维码登录会话标识。 */
|
||||||
|
session_id?: string;
|
||||||
|
}) => void) | undefined;
|
||||||
|
qrLoginMocks.generateQRLogin.mockImplementationOnce(/* generateAction 创建可取消的二维码请求。 */ ({ signal }: { signal: AbortSignal }) => new Promise(resolve => {
|
||||||
|
signal.addEventListener('abort', /* abortAction 记录二维码请求取消事件。 */ () => resolveGeneration = resolve, { once: true });
|
||||||
|
resolveGeneration = resolve;
|
||||||
|
}));
|
||||||
|
// hook 保存请求取消场景的二维码登录 Hook。
|
||||||
|
const hook = renderHook(/* hookFactory 创建请求取消场景 Hook。 */ () => useAccountQRCodeLogin({ onLoginSuccess: vi.fn() }));
|
||||||
|
// startPromise 保存尚未完成的二维码生成请求。
|
||||||
|
const startPromise = hook.result.current.startQRLogin();
|
||||||
|
|
||||||
|
act(/* closeAction 关闭二维码弹窗并取消请求。 */ () => {
|
||||||
|
hook.result.current.closeQRModal();
|
||||||
|
});
|
||||||
|
expect(hook.result.current.showQRModal).toBe(false);
|
||||||
|
expect(qrLoginMocks.generateQRLogin).toHaveBeenCalledWith(expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||||
|
resolveGeneration?.({ success: true, qr_code_url: 'stale-url', session_id: 'stale-session' });
|
||||||
|
await act(/* settleAction 等待被取消请求的异步收束。 */ async () => {
|
||||||
|
await startPromise;
|
||||||
|
});
|
||||||
|
expect(hook.result.current.qrCodeUrl).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import { useEffect,useRef,useState } from 'react';
|
||||||
|
import type { AccountDetail } from './api';
|
||||||
|
import { checkQRLoginStatus,completeQRVerification,generateQRLogin } from './api';
|
||||||
|
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
|
||||||
|
|
||||||
|
// AccountQRCodeLoginOptions 描述二维码登录协调器需要的页面刷新回调。
|
||||||
|
export interface AccountQRCodeLoginOptions {
|
||||||
|
// onLoginSuccess 表示二维码授权成功后刷新账号列表的回调。
|
||||||
|
onLoginSuccess: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountQRCodeLoginState 描述二维码授权弹窗和异步流程的页面状态。
|
||||||
|
export interface AccountQRCodeLoginState {
|
||||||
|
// showQRModal 表示二维码登录弹窗是否打开。
|
||||||
|
showQRModal: boolean;
|
||||||
|
// qrCodeUrl 保存当前二维码登录地址。
|
||||||
|
qrCodeUrl: string;
|
||||||
|
// qrStatus 保存二维码登录流程状态。
|
||||||
|
qrStatus: string;
|
||||||
|
// qrErrorMessage 保存二维码登录错误说明。
|
||||||
|
qrErrorMessage: string;
|
||||||
|
// verificationScreenshot 保存风控验证截图地址。
|
||||||
|
verificationScreenshot: string;
|
||||||
|
// faceQrUrl 保存人脸验证二维码地址。
|
||||||
|
faceQrUrl: string;
|
||||||
|
// qrReauthTarget 保存需要重新授权的目标账号。
|
||||||
|
qrReauthTarget: AccountDetail | null;
|
||||||
|
// startQRLogin 启动二维码登录或账号重新授权流程。
|
||||||
|
startQRLogin: (target?: AccountDetail) => Promise<void>;
|
||||||
|
// closeQRModal 关闭二维码登录弹窗并取消相关异步资源。
|
||||||
|
closeQRModal: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// useAccountQRCodeLogin 统一管理二维码生成、轮询、风控验证和资源取消生命周期。
|
||||||
|
export const useAccountQRCodeLogin = ({ onLoginSuccess }: AccountQRCodeLoginOptions): AccountQRCodeLoginState => {
|
||||||
|
// showQRModal 表示二维码登录弹窗是否打开。
|
||||||
|
const [showQRModal, setShowQRModal] = useState(false);
|
||||||
|
// qrCodeUrl 保存当前二维码登录地址。
|
||||||
|
const [qrCodeUrl, setQrCodeUrl] = useState('');
|
||||||
|
// qrStatus 保存二维码登录流程状态。
|
||||||
|
const [qrStatus, setQrStatus] = useState('pending');
|
||||||
|
// qrErrorMessage 保存二维码登录错误说明。
|
||||||
|
const [qrErrorMessage, setQrErrorMessage] = useState('');
|
||||||
|
// verificationScreenshot 保存风控验证截图地址。
|
||||||
|
const [verificationScreenshot, setVerificationScreenshot] = useState('');
|
||||||
|
// faceQrUrl 保存人脸验证二维码地址。
|
||||||
|
const [faceQrUrl, setFaceQrUrl] = useState('');
|
||||||
|
// qrReauthTarget 保存需要重新授权的目标账号。
|
||||||
|
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||||
|
// qrPollerRef 保存二维码登录状态轮询器实例。
|
||||||
|
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
|
||||||
|
// qrRequestGateRef 隔离过期的二维码生成请求。
|
||||||
|
const qrRequestGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||||
|
// qrGenerateAbortRef 保存二维码生成请求控制器。
|
||||||
|
const qrGenerateAbortRef = useRef<AbortController | null>(null);
|
||||||
|
// qrCloseTimerRef 保存二维码弹窗延迟关闭定时器。
|
||||||
|
const qrCloseTimerRef = useRef<number | null>(null);
|
||||||
|
|
||||||
|
if (qrPollerRef.current === null) {
|
||||||
|
qrPollerRef.current = createQRLoginPoller();
|
||||||
|
}
|
||||||
|
if (qrRequestGateRef.current === null) {
|
||||||
|
qrRequestGateRef.current = createLatestRequestGate();
|
||||||
|
}
|
||||||
|
|
||||||
|
// clearQRCloseTimer 清理二维码弹窗延迟关闭定时器。
|
||||||
|
const clearQRCloseTimer = () => {
|
||||||
|
if (qrCloseTimerRef.current !== null) {
|
||||||
|
window.clearTimeout(qrCloseTimerRef.current);
|
||||||
|
qrCloseTimerRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// stopQRPolling 停止二维码登录状态轮询。
|
||||||
|
const stopQRPolling = () => {
|
||||||
|
qrPollerRef.current?.stop();
|
||||||
|
};
|
||||||
|
|
||||||
|
// closeQRModal 关闭二维码登录弹窗并取消请求、轮询和延迟任务。
|
||||||
|
const closeQRModal = () => {
|
||||||
|
qrGenerateAbortRef.current?.abort();
|
||||||
|
qrRequestGateRef.current?.cancel();
|
||||||
|
stopQRPolling();
|
||||||
|
clearQRCloseTimer();
|
||||||
|
setShowQRModal(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// scheduleQRModalClose 在登录成功后延迟关闭二维码弹窗并刷新账号列表。
|
||||||
|
const scheduleQRModalClose = () => {
|
||||||
|
clearQRCloseTimer();
|
||||||
|
qrCloseTimerRef.current = window.setTimeout(/* 当前回调处理二维码成功后的延迟收束。 */ () => {
|
||||||
|
qrCloseTimerRef.current = null;
|
||||||
|
setShowQRModal(false);
|
||||||
|
void onLoginSuccess();
|
||||||
|
}, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(/* 当前回调管理二维码异步资源的页面生命周期。 */ () => {
|
||||||
|
// cleanup 清理页面卸载时仍存在的二维码请求、轮询和定时器。
|
||||||
|
const cleanup = () => {
|
||||||
|
stopQRPolling();
|
||||||
|
qrRequestGateRef.current?.cancel();
|
||||||
|
qrGenerateAbortRef.current?.abort();
|
||||||
|
clearQRCloseTimer();
|
||||||
|
};
|
||||||
|
return cleanup;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// completeAndPersistQRSession 完成二维码风控验证并持久化授权结果。
|
||||||
|
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null): Promise<string> => {
|
||||||
|
// response 保存风控验证完成接口返回值。
|
||||||
|
const response = await completeQRVerification(sessionId, target?.id);
|
||||||
|
if (!response.success || !response.account_id) {
|
||||||
|
throw new Error(response.message || '保存扫码授权失败');
|
||||||
|
}
|
||||||
|
return response.account_id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// startQRLogin 启动二维码生成、轮询和成功后的账号持久化流程。
|
||||||
|
const startQRLogin = async (target?: AccountDetail): Promise<void> => {
|
||||||
|
stopQRPolling();
|
||||||
|
qrGenerateAbortRef.current?.abort();
|
||||||
|
// controller 控制当前二维码生成请求的取消。
|
||||||
|
const controller = new AbortController();
|
||||||
|
qrGenerateAbortRef.current = controller;
|
||||||
|
// requestGeneration 标识当前二维码生成请求代次。
|
||||||
|
const requestGeneration = qrRequestGateRef.current!.next();
|
||||||
|
clearQRCloseTimer();
|
||||||
|
// targetAccount 保存当前二维码授权目标账号。
|
||||||
|
const targetAccount = target || null;
|
||||||
|
setQrReauthTarget(targetAccount);
|
||||||
|
setShowQRModal(true);
|
||||||
|
setQrStatus('loading');
|
||||||
|
setQrErrorMessage('');
|
||||||
|
setQrCodeUrl('');
|
||||||
|
setVerificationScreenshot('');
|
||||||
|
setFaceQrUrl('');
|
||||||
|
try {
|
||||||
|
// response 保存二维码生成接口返回值。
|
||||||
|
const response = await generateQRLogin({ signal: controller.signal });
|
||||||
|
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||||
|
if (!response.success || !response.qr_code_url || !response.session_id) {
|
||||||
|
throw new Error(response.message || '闲鱼未返回可用的登录二维码');
|
||||||
|
}
|
||||||
|
|
||||||
|
// sessionId 保存后端生成的二维码登录会话标识。
|
||||||
|
const sessionId = response.session_id;
|
||||||
|
setQrCodeUrl(response.qr_code_url);
|
||||||
|
setQrStatus('waiting');
|
||||||
|
qrPollerRef.current?.start(sessionId, checkQRLoginStatus, {
|
||||||
|
onSuccess: /* 当前回调处理二维码登录成功结果。 */ async () => {
|
||||||
|
try {
|
||||||
|
await completeAndPersistQRSession(sessionId, targetAccount);
|
||||||
|
} catch (/* error 表示二维码授权结果持久化错误。 */ error) {
|
||||||
|
console.error('保存扫码授权失败', error);
|
||||||
|
setQrStatus('error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setQrStatus('success');
|
||||||
|
scheduleQRModalClose();
|
||||||
|
},
|
||||||
|
onScanned: /* 当前回调处理二维码已扫描状态。 */ () => {
|
||||||
|
setQrStatus('waiting');
|
||||||
|
},
|
||||||
|
onTerminalError: /* 当前回调处理二维码终止状态。 */ () => {
|
||||||
|
setQrStatus('error');
|
||||||
|
},
|
||||||
|
onPollError: /* 当前回调处理二维码轮询错误。 */ error => {
|
||||||
|
console.error('轮询扫码状态失败', error);
|
||||||
|
setQrStatus('error');
|
||||||
|
},
|
||||||
|
onVerificationRequired: /* 当前回调处理二维码风控验证状态。 */ statusResponse => {
|
||||||
|
setQrStatus('verification');
|
||||||
|
if (statusResponse.face_qr_url) setFaceQrUrl(statusResponse.face_qr_url);
|
||||||
|
if (statusResponse.verification_screenshot) setVerificationScreenshot(statusResponse.verification_screenshot);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (/* error 表示二维码生成或请求取消错误。 */ error) {
|
||||||
|
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||||
|
if (controller.signal.aborted) return;
|
||||||
|
setQrErrorMessage(error instanceof Error ? error.message : '二维码获取失败,请稍后重试');
|
||||||
|
setQrStatus('error');
|
||||||
|
} finally {
|
||||||
|
if (qrGenerateAbortRef.current === controller) qrGenerateAbortRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
showQRModal,
|
||||||
|
qrCodeUrl,
|
||||||
|
qrStatus,
|
||||||
|
qrErrorMessage,
|
||||||
|
verificationScreenshot,
|
||||||
|
faceQrUrl,
|
||||||
|
qrReauthTarget,
|
||||||
|
startQRLogin,
|
||||||
|
closeQRModal,
|
||||||
|
};
|
||||||
|
};
|
||||||
+34
-12
@@ -1,23 +1,27 @@
|
|||||||
import { afterEach,expect,test,vi } from 'vitest';
|
import { afterEach,expect,test,vi } from 'vitest';
|
||||||
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
|
import { createLatestRequestGate,createQRLoginPoller } from './qrPolling';
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// flushMicrotasks 刷新微任务队列。
|
||||||
const flushMicrotasks = async () => {
|
const flushMicrotasks = async () => {
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
};
|
};
|
||||||
|
|
||||||
test('QR poller clears the previous interval before starting another session', () => {
|
test('QR poller clears the previous interval before starting another session', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
// checkStatus check状态,负责当前功能中的对应处理。
|
||||||
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
|
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
|
||||||
|
// handlers 处理当前用户操作(rs)。
|
||||||
const handlers = {
|
const handlers = {
|
||||||
onSuccess: vi.fn(),
|
onSuccess: vi.fn(),
|
||||||
onTerminalError: vi.fn(),
|
onTerminalError: vi.fn(),
|
||||||
onPollError: vi.fn(),
|
onPollError: vi.fn(),
|
||||||
};
|
};
|
||||||
|
// poller poller,负责当前功能中的对应处理。
|
||||||
const poller = createQRLoginPoller();
|
const poller = createQRLoginPoller();
|
||||||
|
|
||||||
poller.start('sid-1', checkStatus, handlers);
|
poller.start('sid-1', checkStatus, handlers);
|
||||||
@@ -28,13 +32,17 @@ test('QR poller clears the previous interval before starting another session', (
|
|||||||
expect(checkStatus).toHaveBeenCalledWith('sid-2', expect.any(AbortSignal));
|
expect(checkStatus).toHaveBeenCalledWith('sid-2', expect.any(AbortSignal));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('QR poller stops on success and terminal errors', async () => {
|
test('QR poller stops on success and terminal errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
// checkStatus check状态,负责当前功能中的对应处理。
|
||||||
const checkStatus = vi.fn()
|
const checkStatus = vi.fn()
|
||||||
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
|
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
|
||||||
.mockResolvedValueOnce({ status: 'expired' });
|
.mockResolvedValueOnce({ status: 'expired' });
|
||||||
|
// onSuccess 响应当前用户操作(Success)。
|
||||||
const onSuccess = vi.fn();
|
const onSuccess = vi.fn();
|
||||||
|
// onTerminalError 响应当前用户操作(Terminal错误)。
|
||||||
const onTerminalError = vi.fn();
|
const onTerminalError = vi.fn();
|
||||||
|
// poller poller,负责当前功能中的对应处理。
|
||||||
const poller = createQRLoginPoller();
|
const poller = createQRLoginPoller();
|
||||||
|
|
||||||
poller.start('sid-1', checkStatus, {
|
poller.start('sid-1', checkStatus, {
|
||||||
@@ -62,8 +70,9 @@ test('QR poller stops on success and terminal errors', async () => {
|
|||||||
expect(poller.isActive()).toBe(false);
|
expect(poller.isActive()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('QR poller keeps polling during verification and stops on thrown errors', async () => {
|
test('QR poller keeps polling during verification and stops on thrown errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
// checkStatus check状态,负责当前功能中的对应处理。
|
||||||
const checkStatus = vi.fn()
|
const checkStatus = vi.fn()
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
status: 'verification_required',
|
status: 'verification_required',
|
||||||
@@ -71,8 +80,11 @@ test('QR poller keeps polling during verification and stops on thrown errors', a
|
|||||||
face_qr_url: 'https://face.example',
|
face_qr_url: 'https://face.example',
|
||||||
})
|
})
|
||||||
.mockRejectedValueOnce(new Error('network down'));
|
.mockRejectedValueOnce(new Error('network down'));
|
||||||
|
// onVerificationRequired 响应当前用户操作(VerificationRequired)。
|
||||||
const onVerificationRequired = vi.fn();
|
const onVerificationRequired = vi.fn();
|
||||||
|
// onPollError 响应当前用户操作(轮询函数错误)。
|
||||||
const onPollError = vi.fn();
|
const onPollError = vi.fn();
|
||||||
|
// poller poller,负责当前功能中的对应处理。
|
||||||
const poller = createQRLoginPoller();
|
const poller = createQRLoginPoller();
|
||||||
|
|
||||||
poller.start('sid-1', checkStatus, {
|
poller.start('sid-1', checkStatus, {
|
||||||
@@ -97,12 +109,15 @@ test('QR poller keeps polling during verification and stops on thrown errors', a
|
|||||||
expect(poller.isActive()).toBe(false);
|
expect(poller.isActive()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('QR poller never overlaps slow status requests', async () => {
|
test('QR poller never overlaps slow status requests', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
let resolveStatus: ((value: { status: string }) => void) | undefined;
|
// resolveStatus resolve状态,负责当前功能中的对应处理。
|
||||||
const checkStatus = vi.fn(() => new Promise<{ status: string }>(resolve => {
|
let resolveStatus: ((value: { /** status 表示状态。 */ status: string }) => void) | undefined;
|
||||||
|
// checkStatus check状态,负责当前功能中的对应处理。
|
||||||
|
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ () => new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ resolve => {
|
||||||
resolveStatus = resolve;
|
resolveStatus = resolve;
|
||||||
}));
|
}));
|
||||||
|
// poller poller,负责当前功能中的对应处理。
|
||||||
const poller = createQRLoginPoller();
|
const poller = createQRLoginPoller();
|
||||||
poller.start('slow-session', checkStatus, {
|
poller.start('slow-session', checkStatus, {
|
||||||
onSuccess: vi.fn(),
|
onSuccess: vi.fn(),
|
||||||
@@ -120,9 +135,12 @@ test('QR poller never overlaps slow status requests', async () => {
|
|||||||
poller.stop();
|
poller.stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('latest request gate rejects stale generation after switch or cancel', () => {
|
test('latest request gate rejects stale generation after switch or cancel', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// gate gate,负责当前功能中的对应处理。
|
||||||
const gate = createLatestRequestGate();
|
const gate = createLatestRequestGate();
|
||||||
|
// first 首项。
|
||||||
const first = gate.next();
|
const first = gate.next();
|
||||||
|
// second second,负责当前功能中的对应处理。
|
||||||
const second = gate.next();
|
const second = gate.next();
|
||||||
|
|
||||||
expect(gate.isCurrent(first)).toBe(false);
|
expect(gate.isCurrent(first)).toBe(false);
|
||||||
@@ -132,16 +150,20 @@ test('latest request gate rejects stale generation after switch or cancel', () =
|
|||||||
expect(gate.isCurrent(second)).toBe(false);
|
expect(gate.isCurrent(second)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('stopping QR polling aborts the in-flight status request without reporting an error', async () => {
|
test('stopping QR polling aborts the in-flight status request without reporting an error', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
// onPollError 响应当前用户操作(轮询函数错误)。
|
||||||
const onPollError = vi.fn();
|
const onPollError = vi.fn();
|
||||||
|
// observedSignal observedSignal,负责当前功能中的对应处理。
|
||||||
let observedSignal: AbortSignal | undefined;
|
let observedSignal: AbortSignal | undefined;
|
||||||
const checkStatus = vi.fn((_sessionId: string, signal?: AbortSignal) => {
|
// checkStatus check状态,负责当前功能中的对应处理。
|
||||||
|
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ (_sessionId: string, signal?: AbortSignal) => {
|
||||||
observedSignal = signal;
|
observedSignal = signal;
|
||||||
return new Promise<{ status: string }>((_resolve, reject) => {
|
return new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ (_resolve, reject) => {
|
||||||
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
signal?.addEventListener('abort', /* 当前回调处理用户交互或异步状态变化。 */ () => reject(new DOMException('aborted', 'AbortError')), { once: true });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
// poller poller,负责当前功能中的对应处理。
|
||||||
const poller = createQRLoginPoller();
|
const poller = createQRLoginPoller();
|
||||||
poller.start('sid', checkStatus, { onSuccess: vi.fn(), onTerminalError: vi.fn(), onPollError });
|
poller.start('sid', checkStatus, { onSuccess: vi.fn(), onTerminalError: vi.fn(), onPollError });
|
||||||
await vi.advanceTimersByTimeAsync(2000);
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
// QRLoginStatusResult 描述二维码登录状态接口返回的可选字段。
|
||||||
|
export interface QRLoginStatusResult {
|
||||||
|
// status 表示当前二维码登录状态。
|
||||||
|
status?: string;
|
||||||
|
// cookies 表示登录成功后返回的凭证字符串。
|
||||||
|
cookies?: string;
|
||||||
|
// unb 表示闲鱼账号的用户标识。
|
||||||
|
unb?: string;
|
||||||
|
// verification_url 表示风控验证地址。
|
||||||
|
verification_url?: string;
|
||||||
|
// verification_screenshot 表示风控验证截图地址。
|
||||||
|
verification_screenshot?: string;
|
||||||
|
// face_qr_url 表示人脸验证二维码地址。
|
||||||
|
face_qr_url?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// QRLoginPollerTimers 描述轮询器使用的定时器依赖,便于测试替换时间源。
|
||||||
|
interface QRLoginPollerTimers {
|
||||||
|
// setInterval 表示创建轮询定时器的函数。
|
||||||
|
setInterval: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>;
|
||||||
|
// clearInterval 表示清理轮询定时器的函数。
|
||||||
|
clearInterval: (id: ReturnType<typeof setInterval>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// QRLoginPollHandlers 描述二维码轮询的状态回调契约。
|
||||||
|
export interface QRLoginPollHandlers {
|
||||||
|
// onSuccess 表示二维码登录成功后的回调。
|
||||||
|
onSuccess: (status: QRLoginStatusResult) => void | Promise<void>;
|
||||||
|
// onScanned 表示二维码被扫描后的回调。
|
||||||
|
onScanned?: (status: QRLoginStatusResult) => void;
|
||||||
|
// onVerificationRequired 表示需要风控验证时的回调。
|
||||||
|
onVerificationRequired?: (status: QRLoginStatusResult) => void;
|
||||||
|
// onTerminalError 表示登录流程终止错误的回调。
|
||||||
|
onTerminalError: (status: QRLoginStatusResult) => void;
|
||||||
|
// onPollError 表示轮询请求失败的回调。
|
||||||
|
onPollError: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// terminalQRStatuses 保存二维码登录不可继续的终止状态集合。
|
||||||
|
const terminalQRStatuses = new Set(['expired', 'cancelled', 'error', 'not_found']);
|
||||||
|
|
||||||
|
// createLatestRequestGate 让只能由最后一次用户操作提交结果的异步请求拥有明确代次。
|
||||||
|
export const createLatestRequestGate = () => {
|
||||||
|
// generation 保存当前请求代次。
|
||||||
|
let generation = 0;
|
||||||
|
return {
|
||||||
|
// next 生成下一次请求代次并使旧请求失效。
|
||||||
|
next: () => {
|
||||||
|
generation += 1;
|
||||||
|
return generation;
|
||||||
|
},
|
||||||
|
// cancel 让所有尚未返回的请求失效。
|
||||||
|
cancel: () => {
|
||||||
|
generation += 1;
|
||||||
|
},
|
||||||
|
// isCurrent 判断候选请求是否仍属于最新代次。
|
||||||
|
isCurrent: /* currentCheck 判断候选请求是否仍属于最新代次。 */ (candidate: number) => candidate === generation,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// createQRLoginPoller 创建二维码登录轮询器,并隔离请求重叠和过期回调。
|
||||||
|
export const createQRLoginPoller = (
|
||||||
|
timers: QRLoginPollerTimers = {
|
||||||
|
setInterval: globalThis.setInterval.bind(globalThis),
|
||||||
|
clearInterval: globalThis.clearInterval.bind(globalThis),
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
// interval 保存当前轮询定时器句柄。
|
||||||
|
let interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
// requestController 保存当前轮询请求的取消控制器。
|
||||||
|
let requestController: AbortController | null = null;
|
||||||
|
// inFlightGeneration 保存正在执行请求的代次,避免请求重叠。
|
||||||
|
let inFlightGeneration = -1;
|
||||||
|
// generation 保存轮询器当前生命周期代次。
|
||||||
|
let generation = 0;
|
||||||
|
|
||||||
|
// stop 停止轮询、取消正在执行的请求并使旧回调失效。
|
||||||
|
const stop = () => {
|
||||||
|
generation += 1;
|
||||||
|
requestController?.abort();
|
||||||
|
requestController = null;
|
||||||
|
if (interval !== null) {
|
||||||
|
timers.clearInterval(interval);
|
||||||
|
interval = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// start 启动指定会话的二维码状态轮询。
|
||||||
|
const start = (
|
||||||
|
sessionId: string,
|
||||||
|
checkStatus: (sessionId: string, signal?: AbortSignal) => Promise<QRLoginStatusResult>,
|
||||||
|
handlers: QRLoginPollHandlers,
|
||||||
|
intervalMs = 2000,
|
||||||
|
) => {
|
||||||
|
stop();
|
||||||
|
// currentGeneration 保存本次轮询生命周期代次。
|
||||||
|
const currentGeneration = generation;
|
||||||
|
requestController = new AbortController();
|
||||||
|
// signal 保存本次轮询请求使用的取消信号。
|
||||||
|
const signal = requestController.signal;
|
||||||
|
interval = timers.setInterval(/* 当前回调触发二维码状态检查。 */ () => {
|
||||||
|
if (inFlightGeneration === currentGeneration || currentGeneration !== generation) return;
|
||||||
|
inFlightGeneration = currentGeneration;
|
||||||
|
void (/* 当前回调执行一次二维码状态检查并分发结果。 */ async () => {
|
||||||
|
try {
|
||||||
|
// statusResponse 保存二维码状态接口响应。
|
||||||
|
const statusResponse = await checkStatus(sessionId, signal);
|
||||||
|
if (statusResponse.status === 'success') {
|
||||||
|
stop();
|
||||||
|
await handlers.onSuccess(statusResponse);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (statusResponse.status === 'scanned') {
|
||||||
|
handlers.onScanned?.(statusResponse);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (statusResponse.status === 'verification_required') {
|
||||||
|
handlers.onVerificationRequired?.(statusResponse);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (statusResponse.status && terminalQRStatuses.has(statusResponse.status)) {
|
||||||
|
stop();
|
||||||
|
handlers.onTerminalError(statusResponse);
|
||||||
|
}
|
||||||
|
} catch (/* error 表示二维码状态请求错误。 */ error) {
|
||||||
|
if (signal.aborted || currentGeneration !== generation) return;
|
||||||
|
stop();
|
||||||
|
handlers.onPollError(error);
|
||||||
|
} finally {
|
||||||
|
if (inFlightGeneration === currentGeneration) inFlightGeneration = -1;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, intervalMs);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
stop,
|
||||||
|
// isActive 判断轮询器当前是否仍有活动定时器。
|
||||||
|
isActive: /* activeCheck 判断轮询器当前是否仍有活动定时器。 */ () => interval !== null,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { describe,expect,test } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||||
|
import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime';
|
||||||
|
|
||||||
|
// account 创建运行状态测试使用的最小账号对象。
|
||||||
|
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
|
||||||
|
id: 'account-1',
|
||||||
|
enabled: true,
|
||||||
|
auto_confirm: false,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Accounts runtime state', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
test('最新在线状态替换风控恢复中的旧提示', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// result 是合并当前运行状态后的账号列表。
|
||||||
|
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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('晚到达的旧状态响应不会覆盖当前账号状态', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// current 是当前页面已经展示的较新账号状态。
|
||||||
|
const current = account({
|
||||||
|
runtime_state: 'online',
|
||||||
|
runtime_message: '消息服务连接正常',
|
||||||
|
runtime_updated_at: '2026-07-13T13:16:02+08:00',
|
||||||
|
});
|
||||||
|
// result 处理结果。
|
||||||
|
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('缺少对应运行状态时保留原账号对象', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// current 是没有新运行状态可合并的账号对象。
|
||||||
|
const current = account();
|
||||||
|
expect(mergeAccountRuntimeStatuses([current], {})[0]).toBe(current);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('时间戳缺失或无效时不误判为旧状态', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
expect(isOlderStatus(undefined, '2026-01-01T00:00:00Z')).toBe(false);
|
||||||
|
expect(isOlderStatus('invalid', '2026-01-01T00:00:00Z')).toBe(false);
|
||||||
|
expect(isOlderStatus('2026-01-02T00:00:00Z', '2026-01-01T00:00:00Z')).toBe(true);
|
||||||
|
expect(isOlderStatus('2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('所有运行状态都映射到稳定的中文展示', /* 当前回调处理用户交互或异步状态变化。 */ () => {
|
||||||
|
// states 是运行状态到中文标签的完整断言表。
|
||||||
|
const states = [
|
||||||
|
['online', '在线'], ['starting', '连接中'], ['connecting', '连接中'], ['reconnecting', '重连中'],
|
||||||
|
['auth_expired', '登录已失效'], ['verification_required', '需要验证'], ['runtime_conflict', '运行状态冲突'], ['error', '运行异常'], ['stopped', '运行异常'],
|
||||||
|
] as const;
|
||||||
|
states.forEach(
|
||||||
|
// state 是需要验证展示文案的运行状态和预期标签。
|
||||||
|
([state, label]) => expect(accountRuntimePresentation(account({ runtime_state: state })).label).toBe(label),
|
||||||
|
);
|
||||||
|
expect(accountRuntimePresentation(account({ enabled: false, runtime_state: 'online' })).label).toBe('已停用');
|
||||||
|
expect(accountRuntimePresentation(account({ runtime_state: 'disabled' })).label).toBe('已停用');
|
||||||
|
expect(accountRuntimePresentation(account()).label).toBe('状态检测中');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import type { AccountDetail } from './api';
|
||||||
|
import type { AccountRuntimeStatus } from './api';
|
||||||
|
import type { AccountRuntimePresentation } from './types';
|
||||||
|
|
||||||
|
// isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。
|
||||||
|
export const isOlderStatus = (currentUpdatedAt?: string, incomingUpdatedAt?: string): boolean => {
|
||||||
|
if (!currentUpdatedAt || !incomingUpdatedAt) return false;
|
||||||
|
// currentTime 是账号当前已展示快照的时间戳。
|
||||||
|
const currentTime = Date.parse(currentUpdatedAt);
|
||||||
|
// incomingTime 是本次轮询返回快照的时间戳。
|
||||||
|
const incomingTime = Date.parse(incomingUpdatedAt);
|
||||||
|
return Number.isFinite(currentTime) && Number.isFinite(incomingTime) && incomingTime < currentTime;
|
||||||
|
};
|
||||||
|
|
||||||
|
// mergeAccountRuntimeStatuses 将最新运行时快照合并到账号列表,并拒绝过期响应。
|
||||||
|
export const mergeAccountRuntimeStatuses = (
|
||||||
|
accounts: AccountDetail[],
|
||||||
|
statuses: Record<string, AccountRuntimeStatus>,
|
||||||
|
): AccountDetail[] => accounts.map(
|
||||||
|
// account 是待合并运行时快照的账号对象。
|
||||||
|
account => {
|
||||||
|
// status 是服务端按账号 ID 返回的运行时状态。
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// accountRuntimePresentation 将后端运行状态转换为列表徽标和状态点样式。
|
||||||
|
export const accountRuntimePresentation = (account: AccountDetail): AccountRuntimePresentation => {
|
||||||
|
if (!account.enabled || account.runtime_state === 'disabled') {
|
||||||
|
return { label: '已停用', badge: 'bg-gray-100 text-gray-500', dot: 'bg-gray-300' };
|
||||||
|
}
|
||||||
|
switch (account.runtime_state) {
|
||||||
|
case 'online':
|
||||||
|
return { label: '在线', badge: 'bg-green-100 text-green-700', dot: 'bg-green-500' };
|
||||||
|
case 'starting':
|
||||||
|
case 'connecting':
|
||||||
|
return { label: '连接中', badge: 'bg-blue-100 text-blue-700', dot: 'bg-blue-500' };
|
||||||
|
case 'reconnecting':
|
||||||
|
return { label: '重连中', badge: 'bg-amber-100 text-amber-700', dot: 'bg-amber-500' };
|
||||||
|
case 'auth_expired':
|
||||||
|
return { label: '登录已失效', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
|
||||||
|
case 'verification_required':
|
||||||
|
return { label: '需要验证', badge: 'bg-orange-100 text-orange-700', dot: 'bg-orange-500' };
|
||||||
|
case 'runtime_conflict':
|
||||||
|
return { label: '运行状态冲突', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
|
||||||
|
case 'error':
|
||||||
|
case 'stopped':
|
||||||
|
return { label: '运行异常', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
|
||||||
|
default:
|
||||||
|
return { label: '状态检测中', badge: 'bg-gray-100 text-gray-600', dot: 'bg-gray-400' };
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { expect,test } from 'vitest';
|
||||||
|
import type { AccountDetail } from '../../../shared/api-contract/accounts';
|
||||||
|
import {
|
||||||
|
buildAccountLoginInfoUpdate,
|
||||||
|
isCurrentAccountRequest,
|
||||||
|
passwordLoginViewFromStatus,
|
||||||
|
shouldUpdateAccountPause,
|
||||||
|
} from './state';
|
||||||
|
|
||||||
|
// account 是账号编辑状态测试使用的最小领域对象。
|
||||||
|
const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
|
||||||
|
id: 'account-1',
|
||||||
|
enabled: true,
|
||||||
|
auto_confirm: false,
|
||||||
|
username: 'old-user',
|
||||||
|
show_browser: false,
|
||||||
|
pause_duration: 60,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
test('账号切换后只接受当前请求代次和账号的响应',
|
||||||
|
// 旧账号响应即使更晚返回,也不能覆盖当前编辑账号。
|
||||||
|
() => {
|
||||||
|
expect(isCurrentAccountRequest(2, 2, 'account-2', 'account-2')).toBe(true);
|
||||||
|
expect(isCurrentAccountRequest(1, 2, 'account-2', 'account-2')).toBe(false);
|
||||||
|
expect(isCurrentAccountRequest(2, 2, 'account-1', 'account-2')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('编辑子模块共享同一账号边界,旧绑定、AI 和密码登录响应全部失效',
|
||||||
|
// 三类异步子模块都使用相同的代次与账号判定,防止旧弹窗响应污染新账号。
|
||||||
|
() => {
|
||||||
|
// currentGeneration 当前请求代次,负责当前功能中的对应处理。
|
||||||
|
const currentGeneration = 4;
|
||||||
|
// currentAccountId 当前账号标识,负责当前功能中的对应处理。
|
||||||
|
const currentAccountId = 'account-4';
|
||||||
|
expect(isCurrentAccountRequest(3, currentGeneration, 'account-3', currentAccountId)).toBe(false);
|
||||||
|
expect(isCurrentAccountRequest(currentGeneration, currentGeneration, currentAccountId, currentAccountId)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('暂停时长未变化时不会重复启动已结束的暂停',
|
||||||
|
// 相同的时长只保留当前状态,不自动重新提交暂停请求。
|
||||||
|
() => {
|
||||||
|
expect(shouldUpdateAccountPause(60, account({ paused: false }))).toBe(false);
|
||||||
|
expect(shouldUpdateAccountPause(30, account({ paused: true }))).toBe(true);
|
||||||
|
expect(shouldUpdateAccountPause(0, account({ paused: true }))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('凭证编辑不提交空白密码,并支持明确清空密码',
|
||||||
|
// 登录账号或浏览器开关变化时,空白密码不能覆盖已有凭证。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'new-user',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: true,
|
||||||
|
clear_password: false,
|
||||||
|
})).toEqual({ username: 'new-user', show_browser: true });
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'old-user',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: false,
|
||||||
|
clear_password: true,
|
||||||
|
})).toEqual({ username: 'old-user', show_browser: false, clear_password: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('密码登录风控和失败状态统一转换且不暴露验证链接',
|
||||||
|
// 风控状态只展示二维码和提示,失败状态展示后端错误说明。
|
||||||
|
() => {
|
||||||
|
expect(passwordLoginViewFromStatus({
|
||||||
|
status: 'verification_required',
|
||||||
|
message: '需要人脸验证',
|
||||||
|
verification_url: 'https://verification.example',
|
||||||
|
qr_code_url: 'https://qr.example',
|
||||||
|
})).toEqual({
|
||||||
|
sessionId: '',
|
||||||
|
status: 'verification_required',
|
||||||
|
message: '需要人脸验证',
|
||||||
|
qrCodeUrl: 'https://qr.example',
|
||||||
|
});
|
||||||
|
expect(passwordLoginViewFromStatus({ status: 'failed', error: '凭证失效' })).toMatchObject({
|
||||||
|
status: 'failed',
|
||||||
|
message: '凭证失效',
|
||||||
|
qrCodeUrl: '',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('登录字段更新不会用空白密码覆盖已有凭证',
|
||||||
|
// 账号或浏览器开关变化时只提交真正变化的非敏感字段。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account({ username: 'old-user', show_browser: true }), {
|
||||||
|
username: 'new-user',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: false,
|
||||||
|
})).toEqual({ username: 'new-user', show_browser: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('登录字段更新只在用户输入新密码时提交密码',
|
||||||
|
// 用户输入新密码后才允许将密码字段写入设置补丁。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'old-user',
|
||||||
|
login_password: 'new-secret',
|
||||||
|
show_browser: false,
|
||||||
|
})).toEqual({ username: 'old-user', login_password: 'new-secret', show_browser: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('登录字段没有变化时不生成更新补丁',
|
||||||
|
// 没有任何登录字段变化时避免发起无意义的设置请求。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'old-user',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: false,
|
||||||
|
})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('登录字段支持明确清空密码',
|
||||||
|
// 清空密码必须由用户显式勾选,不能由空白输入隐式触发。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'old-user',
|
||||||
|
login_password: '',
|
||||||
|
show_browser: false,
|
||||||
|
clear_password: true,
|
||||||
|
})).toEqual({ username: 'old-user', show_browser: false, clear_password: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('明确清空密码优先于同时输入的新密码',
|
||||||
|
// 同时存在清空和输入时遵循显式清空意图,避免写入新密码。
|
||||||
|
() => {
|
||||||
|
expect(buildAccountLoginInfoUpdate(account(), {
|
||||||
|
username: 'old-user',
|
||||||
|
login_password: 'new-secret',
|
||||||
|
show_browser: false,
|
||||||
|
clear_password: true,
|
||||||
|
})).toEqual({ username: 'old-user', show_browser: false, clear_password: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('暂停时长相同不会重新启动账号暂停',
|
||||||
|
// 暂停时长没有变化时保持当前状态,避免重复写入暂停记录。
|
||||||
|
() => {
|
||||||
|
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: false })).toBe(false);
|
||||||
|
expect(shouldUpdateAccountPause(60, { pause_duration: 60, paused: true })).toBe(false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import type { AccountDetail } from './api';
|
||||||
|
import type { PasswordLoginStatusResponse } from './api';
|
||||||
|
import type { AccountEditForm,PasswordLoginView } from './types';
|
||||||
|
|
||||||
|
// AccountLoginEditFields 描述账号编辑表单中参与登录信息比较的字段。
|
||||||
|
export type AccountLoginEditFields = Pick<AccountEditForm, 'username' | 'login_password' | 'show_browser'> & Pick<Partial<AccountEditForm>, 'clear_password'>;
|
||||||
|
|
||||||
|
// AccountLoginInfoPayload 描述需要提交给后端的登录信息变更。
|
||||||
|
export interface AccountLoginInfoPayload {
|
||||||
|
// username 是新的闲鱼登录账号。
|
||||||
|
username: string;
|
||||||
|
// login_password 是用户本次输入的新密码。
|
||||||
|
login_password?: string;
|
||||||
|
// clear_password 表示清空服务端已保存密码。
|
||||||
|
clear_password?: boolean;
|
||||||
|
// show_browser 表示密码登录时是否展示浏览器。
|
||||||
|
show_browser: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// shouldUpdateAccountPause 判断暂停时长是否真的发生变化,避免无意重启已结束的暂停。
|
||||||
|
export const shouldUpdateAccountPause = (
|
||||||
|
requestedMinutes: number,
|
||||||
|
account: Pick<AccountDetail, 'pause_duration' | 'paused'>,
|
||||||
|
): boolean => requestedMinutes !== (account.pause_duration || 0);
|
||||||
|
|
||||||
|
// buildAccountLoginInfoUpdate 只生成真正变化的登录字段,并拒绝提交空白密码。
|
||||||
|
export const buildAccountLoginInfoUpdate = (
|
||||||
|
account: AccountDetail,
|
||||||
|
form: AccountLoginEditFields,
|
||||||
|
): AccountLoginInfoPayload | null => {
|
||||||
|
// usernameChanged 表示登录账号是否被修改。
|
||||||
|
const usernameChanged = form.username !== (account.username || '');
|
||||||
|
// showBrowserChanged 表示登录浏览器展示开关是否被修改。
|
||||||
|
const showBrowserChanged = form.show_browser !== (account.show_browser || false);
|
||||||
|
// passwordChanged 表示用户是否输入了新的非空密码。
|
||||||
|
const passwordChanged = form.login_password !== '';
|
||||||
|
// passwordCleared 表示用户是否明确要求清空密码。
|
||||||
|
const passwordCleared = form.clear_password === true;
|
||||||
|
if (!usernameChanged && !showBrowserChanged && !passwordChanged && !passwordCleared) return null;
|
||||||
|
|
||||||
|
// payload 是提交给账号设置接口的登录信息补丁。
|
||||||
|
const payload: AccountLoginInfoPayload = {
|
||||||
|
username: form.username,
|
||||||
|
show_browser: form.show_browser,
|
||||||
|
};
|
||||||
|
if (passwordCleared) {
|
||||||
|
payload.clear_password = true;
|
||||||
|
} else if (passwordChanged) {
|
||||||
|
payload.login_password = form.login_password;
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
};
|
||||||
|
|
||||||
|
// isCurrentAccountRequest 判断账号切换后异步响应是否仍属于当前请求。
|
||||||
|
export const isCurrentAccountRequest = (
|
||||||
|
requestGeneration: number,
|
||||||
|
currentGeneration: number,
|
||||||
|
requestAccountId: string,
|
||||||
|
currentAccountId: string,
|
||||||
|
): boolean => requestGeneration === currentGeneration && requestAccountId === currentAccountId;
|
||||||
|
|
||||||
|
// passwordLoginViewFromStatus 将密码登录接口状态转换为编辑弹窗状态。
|
||||||
|
export const passwordLoginViewFromStatus = (result: PasswordLoginStatusResponse): PasswordLoginView => {
|
||||||
|
if (result.status === 'success') {
|
||||||
|
return {
|
||||||
|
sessionId: '',
|
||||||
|
status: 'success',
|
||||||
|
message: result.message || '账号密码登录成功,授权信息已更新',
|
||||||
|
qrCodeUrl: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (result.status === 'processing' || result.status === 'verification_required') {
|
||||||
|
return {
|
||||||
|
sessionId: '',
|
||||||
|
status: result.status,
|
||||||
|
message: result.message || (result.status === 'verification_required' ? '账号触发风控,需要完成人脸识别' : '登录处理中'),
|
||||||
|
qrCodeUrl: result.qr_code_url || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
sessionId: '',
|
||||||
|
status: 'failed',
|
||||||
|
message: result.error || result.message || '密码登录失败,请检查账号信息后重试',
|
||||||
|
qrCodeUrl: '',
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { act,renderHook } from '@testing-library/react';
|
||||||
|
import type { Dispatch,SetStateAction } from 'react';
|
||||||
|
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts';
|
||||||
|
import {
|
||||||
|
cancelPasswordLogin,
|
||||||
|
checkPasswordLoginStatus,
|
||||||
|
getAccountAISettings,
|
||||||
|
getAccountBindings,
|
||||||
|
getLongLoginSettings,
|
||||||
|
getNotificationChannels,
|
||||||
|
passwordLogin,
|
||||||
|
setLongLoginSettings,
|
||||||
|
updateAccountAISettings,
|
||||||
|
updateAccountPauseDuration,
|
||||||
|
updateAccountSettings,
|
||||||
|
} from './api';
|
||||||
|
import { useAccountSubmodules,type AccountModalType } from './submoduleHooks';
|
||||||
|
import type { AccountEditForm } from './types';
|
||||||
|
|
||||||
|
vi.mock('./api', /* accountsSubmoduleApiMockFactory 提供账号子模块 Hook 的确定性 API 替身。 */ () => ({
|
||||||
|
cancelPasswordLogin: vi.fn(),
|
||||||
|
checkPasswordLoginStatus: vi.fn(),
|
||||||
|
getAccountAISettings: vi.fn(),
|
||||||
|
getAccountBindings: vi.fn(),
|
||||||
|
getLongLoginSettings: vi.fn(),
|
||||||
|
getNotificationChannels: vi.fn(),
|
||||||
|
passwordLogin: vi.fn(),
|
||||||
|
setLongLoginSettings: vi.fn(),
|
||||||
|
updateAccountAISettings: vi.fn(),
|
||||||
|
updateAccountPauseDuration: vi.fn(),
|
||||||
|
updateAccountSettings: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// cancelPasswordMock 是取消密码登录的可控替身。
|
||||||
|
const cancelPasswordMock = vi.mocked(cancelPasswordLogin);
|
||||||
|
// passwordStatusMock 是密码登录状态查询的可控替身。
|
||||||
|
const passwordStatusMock = vi.mocked(checkPasswordLoginStatus);
|
||||||
|
// accountAIMock 是账号 AI 设置读取的可控替身。
|
||||||
|
const accountAIMock = vi.mocked(getAccountAISettings);
|
||||||
|
// bindingsMock 是账号通知绑定读取的可控替身。
|
||||||
|
const bindingsMock = vi.mocked(getAccountBindings);
|
||||||
|
// longLoginMock 是长期登录状态读取的可控替身。
|
||||||
|
const longLoginMock = vi.mocked(getLongLoginSettings);
|
||||||
|
// channelsMock 是通知渠道读取的可控替身。
|
||||||
|
const channelsMock = vi.mocked(getNotificationChannels);
|
||||||
|
// passwordLoginMock 是密码登录启动的可控替身。
|
||||||
|
const passwordLoginMock = vi.mocked(passwordLogin);
|
||||||
|
// setLongLoginMock 是长期登录保存的可控替身。
|
||||||
|
const setLongLoginMock = vi.mocked(setLongLoginSettings);
|
||||||
|
// updateAIMock 是账号 AI 设置保存的可控替身。
|
||||||
|
const updateAIMock = vi.mocked(updateAccountAISettings);
|
||||||
|
// pauseMock 是账号暂停时长更新的可控替身。
|
||||||
|
const pauseMock = vi.mocked(updateAccountPauseDuration);
|
||||||
|
// updateAccountMock 是账号编辑表单保存的可控替身。
|
||||||
|
const updateAccountMock = vi.mocked(updateAccountSettings);
|
||||||
|
|
||||||
|
// accountFixture 是账号编辑和登录流程使用的账号对象。
|
||||||
|
const accountFixture = { id: 'account-1', enabled: true, value: 'old-cookie', remark: '旧备注', auto_confirm: false, pause_duration: 0, username: 'user@example.com', login_password: 'old-password', show_browser: false } as AccountDetail;
|
||||||
|
// editFormFixture 是账号编辑弹窗的初始表单。
|
||||||
|
const editFormFixture: AccountEditForm = { remark: '新备注', cookie: 'new-cookie', auto_confirm: true, pause_duration: 60, username: 'user@example.com', login_password: 'new-password', show_browser: true, showLoginPassword: false, clear_password: false };
|
||||||
|
// aiFixture 是账号 AI 设置的服务端配置。
|
||||||
|
const aiFixture: AIReplySettings = { ai_enabled: true, max_discount_percent: 20, max_discount_amount: 50, max_bargain_rounds: 2, custom_prompts: '请礼貌回复' };
|
||||||
|
|
||||||
|
describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知绑定和密码登录。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置账号子模块 API 替身。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
channelsMock.mockResolvedValue({ success: true, data: [{ id: '1', name: '邮件', type: 'email', enabled: true } as never] });
|
||||||
|
bindingsMock.mockResolvedValue([1]);
|
||||||
|
longLoginMock.mockResolvedValue({ can_open_long_login: true, enabled: false });
|
||||||
|
setLongLoginMock.mockResolvedValue({ can_open_long_login: true, enabled: true });
|
||||||
|
accountAIMock.mockResolvedValue(aiFixture as never);
|
||||||
|
updateAIMock.mockResolvedValue({ success: true });
|
||||||
|
updateAccountMock.mockResolvedValue({ success: true } as never);
|
||||||
|
pauseMock.mockResolvedValue({ success: true, paused: true, paused_until: 12345 } as never);
|
||||||
|
passwordLoginMock.mockResolvedValue({ success: true, session_id: 'session-1', status: 'processing', message: '处理中' });
|
||||||
|
passwordStatusMock.mockResolvedValue({ status: 'success', message: '登录成功' });
|
||||||
|
cancelPasswordMock.mockResolvedValue({ success: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('打开编辑和AI弹窗后可以保存账号、绑定、长期登录和暂停设置', /* 当前回调验证账号编辑子模块的成功路径。 */ async () => {
|
||||||
|
// setEditingAccount 是编辑账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是编辑弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn();
|
||||||
|
// setEditForm 是编辑表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是保存成功后的账号列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是账号子模块 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// editHookFactory 创建账号编辑场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// editAction 打开账号编辑弹窗并加载关联数据。
|
||||||
|
async () => hook.result.current.openEditModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.longLogin.canOpen).toBe(true);
|
||||||
|
expect(hook.result.current.notifChannels).toHaveLength(1);
|
||||||
|
expect(hook.result.current.selectedChannelIds).toEqual([1]);
|
||||||
|
expect(setEditForm).toHaveBeenCalledWith(expect.objectContaining({ cookie: '', login_password: '' }));
|
||||||
|
await act(
|
||||||
|
// toggleAction 切换通知渠道绑定。
|
||||||
|
() => hook.result.current.toggleNotificationChannel(2),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.bindingsDirty).toBe(true);
|
||||||
|
await act(
|
||||||
|
// longLoginAction 切换长期登录设置。
|
||||||
|
async () => hook.result.current.handleLongLoginToggle(),
|
||||||
|
);
|
||||||
|
expect(setLongLoginMock).toHaveBeenCalledWith('account-1', true);
|
||||||
|
await act(
|
||||||
|
// saveEditAction 保存账号表单和通知绑定。
|
||||||
|
async () => hook.result.current.handleSaveEdit(),
|
||||||
|
);
|
||||||
|
expect(updateAccountMock).toHaveBeenCalledWith('account-1', expect.objectContaining({ remark: '新备注', cookie: 'new-cookie', channel_ids: [1, 2] }));
|
||||||
|
expect(loadAccounts).toHaveBeenCalled();
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// aiAction 打开 AI 设置弹窗并加载账号配置。
|
||||||
|
async () => hook.result.current.openAIModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.aiSettings).toEqual(aiFixture);
|
||||||
|
await act(
|
||||||
|
// saveAIAction 保存 AI 设置并关闭弹窗。
|
||||||
|
async () => hook.result.current.handleSaveAISettings(),
|
||||||
|
);
|
||||||
|
expect(updateAIMock).toHaveBeenCalledWith('account-1', aiFixture);
|
||||||
|
await act(
|
||||||
|
// pauseAction 重新暂停账号并刷新列表。
|
||||||
|
async () => hook.result.current.handleRestartPause(),
|
||||||
|
);
|
||||||
|
expect(pauseMock).toHaveBeenCalledWith('account-1', 60);
|
||||||
|
// pauseUpdater 是暂停成功后写回编辑账号状态的函数式更新器。
|
||||||
|
let pauseUpdater: ((current: AccountDetail | null) => AccountDetail | null) | undefined;
|
||||||
|
for (const call /* call 是编辑账号状态替身记录的一次调用参数。 */ of setEditingAccount.mock.calls) {
|
||||||
|
if (typeof call[0] === 'function') {
|
||||||
|
pauseUpdater = call[0] as (current: AccountDetail | null) => AccountDetail | null;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(pauseUpdater?.(accountFixture)).toMatchObject({ pause_duration: 60, paused: true, paused_until: 12345 });
|
||||||
|
expect(pauseUpdater?.(null)).toBeNull();
|
||||||
|
|
||||||
|
setLongLoginMock.mockRejectedValueOnce(new Error('长登录保存失败'));
|
||||||
|
await act(
|
||||||
|
// longLoginErrorAction 验证长期登录保存失败提示。
|
||||||
|
async () => hook.result.current.handleLongLoginToggle(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.longLogin.error).toBe('长登录保存失败');
|
||||||
|
|
||||||
|
updateAIMock.mockRejectedValueOnce(new Error('AI保存失败'));
|
||||||
|
await act(
|
||||||
|
// aiSaveErrorAction 验证 AI 设置保存失败后的状态清理。
|
||||||
|
async () => hook.result.current.handleSaveAISettings(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.saving).toBe(false);
|
||||||
|
|
||||||
|
updateAccountMock.mockRejectedValueOnce(new Error('账号保存失败'));
|
||||||
|
await act(
|
||||||
|
// editSaveErrorAction 验证账号编辑保存失败后的状态清理。
|
||||||
|
async () => hook.result.current.handleSaveEdit(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.saving).toBe(false);
|
||||||
|
|
||||||
|
pauseMock.mockRejectedValueOnce(new Error('暂停失败'));
|
||||||
|
await act(
|
||||||
|
// pauseErrorAction 验证重新暂停失败后的状态清理。
|
||||||
|
async () => hook.result.current.handleRestartPause(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.saving).toBe(false);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('密码登录成功后刷新账号,取消动作可以终止会话', /* 当前回调验证密码登录轮询和取消路径。 */ async () => {
|
||||||
|
// setEditingAccount 是密码登录测试所需的账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是密码登录测试所需的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn() as unknown as Dispatch<SetStateAction<AccountModalType>>;
|
||||||
|
// setEditForm 是密码登录成功后清理密码的状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是密码登录成功后的列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是密码登录场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// passwordHookFactory 创建密码登录场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// passwordAction 启动密码登录并等待成功状态。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(passwordLoginMock).toHaveBeenCalledWith(expect.objectContaining({ account_id: 'account-1', account: 'user@example.com' }), expect.anything());
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('success');
|
||||||
|
expect(loadAccounts).toHaveBeenCalled();
|
||||||
|
// passwordUpdater 是密码登录成功后清空密码字段的函数式更新器。
|
||||||
|
let passwordUpdater: ((current: AccountEditForm) => AccountEditForm) | undefined;
|
||||||
|
for (const call /* call 是密码表单状态替身记录的一次调用参数。 */ of setEditForm.mock.calls) {
|
||||||
|
if (typeof call[0] === 'function') {
|
||||||
|
passwordUpdater = call[0] as (current: AccountEditForm) => AccountEditForm;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(passwordUpdater?.(editFormFixture)).toMatchObject({ login_password: '', showLoginPassword: false });
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// cancelAction 取消当前密码登录会话并回到空闲状态。
|
||||||
|
async () => hook.result.current.handleCancelPasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(cancelPasswordMock).toHaveBeenCalledWith('session-1');
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('idle');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('密码登录启动失败和状态查询失败时展示错误', /* 当前回调验证密码登录的异常状态转换。 */ async () => {
|
||||||
|
// setEditingAccount 是密码登录异常测试的账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是密码登录异常测试的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn() as unknown as Dispatch<SetStateAction<AccountModalType>>;
|
||||||
|
// setEditForm 是密码登录异常测试的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是密码登录异常测试的列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是密码登录异常场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// passwordErrorHookFactory 创建密码登录异常场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
|
||||||
|
passwordLoginMock.mockResolvedValueOnce({ success: false, message: '账号密码错误' });
|
||||||
|
await act(
|
||||||
|
// startErrorAction 验证密码登录启动失败状态。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('failed');
|
||||||
|
expect(hook.result.current.passwordLoginView.message).toBe('账号密码错误');
|
||||||
|
|
||||||
|
passwordLoginMock.mockResolvedValueOnce({ success: true, session_id: 'session-2', status: 'processing', message: '处理中' });
|
||||||
|
passwordStatusMock.mockRejectedValueOnce(new Error('状态查询失败'));
|
||||||
|
await act(
|
||||||
|
// statusErrorAction 验证密码登录状态查询失败转换。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('failed');
|
||||||
|
expect(hook.result.current.passwordLoginView.message).toBe('状态查询失败');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('绑定、长期登录和AI请求失败时保留可恢复状态', /* 当前回调验证账号子模块的失败隔离分支。 */ async () => {
|
||||||
|
// setEditingAccount 是失败场景的账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是失败场景的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn();
|
||||||
|
// setEditForm 是失败场景的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是失败场景的列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
channelsMock.mockRejectedValueOnce(new Error('渠道失败'));
|
||||||
|
bindingsMock.mockRejectedValueOnce(new Error('绑定失败'));
|
||||||
|
longLoginMock.mockRejectedValueOnce(new Error('长登录失败'));
|
||||||
|
// hook 是账号子模块失败场景的渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// errorHookFactory 创建失败隔离场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// editErrorAction 打开编辑弹窗并等待失败结果收口。
|
||||||
|
async () => hook.result.current.openEditModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.bindingsLoadError).toContain('绑定加载失败');
|
||||||
|
expect(hook.result.current.longLogin.error).toContain('无法读取');
|
||||||
|
await act(
|
||||||
|
// aiErrorAction 打开AI弹窗并隔离读取失败。
|
||||||
|
async () => hook.result.current.openAIModal(accountFixture),
|
||||||
|
);
|
||||||
|
accountAIMock.mockRejectedValueOnce(new Error('AI读取失败'));
|
||||||
|
await act(
|
||||||
|
// aiRetryAction 再次读取AI设置以覆盖异常路径。
|
||||||
|
async () => hook.result.current.openAIModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.saving).toBe(false);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('通知渠道单独失败并可关闭 AI 弹窗', /* 当前回调验证通知渠道隔离和弹窗清理边界。 */ async () => {
|
||||||
|
// setEditingAccount 是通知渠道边界测试的账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是通知渠道边界测试的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn();
|
||||||
|
// setEditForm 是通知渠道边界测试的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是通知渠道边界测试的列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
channelsMock.mockRejectedValueOnce(new Error('渠道读取失败'));
|
||||||
|
// hook 是通知渠道单独失败场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// bindingsErrorHookFactory 创建通知渠道单独失败场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// editAction 打开编辑弹窗并等待通知渠道请求完成。
|
||||||
|
async () => hook.result.current.openEditModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.bindingsLoadError).toContain('通知渠道列表加载失败');
|
||||||
|
await act(
|
||||||
|
// aiAction 打开 AI 设置弹窗。
|
||||||
|
async () => hook.result.current.openAIModal(accountFixture),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// closeAIAction 关闭 AI 设置弹窗并清理请求代次。
|
||||||
|
() => hook.result.current.closeAIModal(),
|
||||||
|
);
|
||||||
|
expect(setActiveModal).toHaveBeenCalledWith(null);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('密码登录处理中和失败状态都能关闭会话', /* 当前回调验证密码登录中间状态与关闭清理。 */ async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
// setEditingAccount 是密码登录中间状态的账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是密码登录中间状态的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn() as unknown as Dispatch<SetStateAction<AccountModalType>>;
|
||||||
|
// setEditForm 是密码登录中间状态的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是密码登录中间状态的列表刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是密码登录中间状态场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// processingHookFactory 创建密码登录中间状态场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
passwordStatusMock.mockResolvedValueOnce({ status: 'processing', message: '处理中' });
|
||||||
|
await act(
|
||||||
|
// processingAction 启动并进入密码登录处理中状态。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('processing');
|
||||||
|
await act(
|
||||||
|
// pollTimerAction 推进密码登录状态轮询定时器。
|
||||||
|
async () => { await vi.advanceTimersByTimeAsync(1_500); },
|
||||||
|
);
|
||||||
|
expect(hook.result.current.passwordLoginView.status).toBe('success');
|
||||||
|
passwordLoginMock.mockResolvedValueOnce({ success: true, session_id: 'session-2', status: 'processing', message: '处理中' });
|
||||||
|
passwordStatusMock.mockResolvedValueOnce({ status: 'processing', message: '处理中' });
|
||||||
|
await act(
|
||||||
|
// secondProcessingAction 再次进入处理中状态以验证关闭时取消会话。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
cancelPasswordMock.mockRejectedValueOnce(new Error('取消失败'));
|
||||||
|
await act(
|
||||||
|
// closeAction 关闭编辑弹窗并取消处理中会话。
|
||||||
|
async () => hook.result.current.closeEditModal(),
|
||||||
|
);
|
||||||
|
expect(cancelPasswordMock).toHaveBeenCalledWith('session-2');
|
||||||
|
hook.unmount();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('通知绑定可移除且 AI 默认值与密码登录终态可归一化', /* 当前回调验证账号子模块的派生默认值和终态分支。 */ async () => {
|
||||||
|
// setEditingAccount 是派生默认值测试的编辑账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是派生默认值测试的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn();
|
||||||
|
// setEditForm 是派生默认值测试的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是派生默认值测试的账号刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是通知绑定移除和密码终态场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// derivedHookFactory 创建派生默认值场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// editAction 打开编辑弹窗并加载通知绑定。
|
||||||
|
async () => hook.result.current.openEditModal(accountFixture),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// removeBindingAction 移除已经绑定的通知渠道。
|
||||||
|
() => hook.result.current.toggleNotificationChannel(1),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.selectedChannelIds).toEqual([]);
|
||||||
|
|
||||||
|
accountAIMock.mockResolvedValueOnce({ ai_enabled: undefined, max_discount_percent: undefined, max_discount_amount: undefined, max_bargain_rounds: undefined, custom_prompts: undefined } as never);
|
||||||
|
await act(
|
||||||
|
// defaultAIAction 读取缺少字段的 AI 设置并应用默认值。
|
||||||
|
async () => hook.result.current.openAIModal(accountFixture),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.aiSettings).toMatchObject({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
|
||||||
|
|
||||||
|
passwordLoginMock.mockResolvedValueOnce({ success: true, session_id: 'session-failed', status: 'processing', message: '处理中' });
|
||||||
|
passwordStatusMock.mockResolvedValueOnce({ status: 'failed', message: '密码登录失败' });
|
||||||
|
await act(
|
||||||
|
// failedStatusAction 验证密码登录失败终态不再继续轮询。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.passwordLoginView).toMatchObject({ status: 'failed', message: '密码登录失败' });
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('没有编辑账号时阻止编辑、AI、暂停和密码登录动作', /* 当前回调验证账号子模块空上下文守卫。 */ async () => {
|
||||||
|
// setEditingAccount 是空上下文守卫所需的编辑账号状态替身。
|
||||||
|
const setEditingAccount = vi.fn();
|
||||||
|
// setActiveModal 是空上下文守卫所需的弹窗状态替身。
|
||||||
|
const setActiveModal = vi.fn();
|
||||||
|
// setEditForm 是空上下文守卫所需的表单状态替身。
|
||||||
|
const setEditForm = vi.fn();
|
||||||
|
// loadAccounts 是空上下文守卫所需的账号刷新替身。
|
||||||
|
const loadAccounts = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是空编辑账号场景的子模块 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// emptyAccountHookFactory 创建空编辑账号场景的子模块 Hook。
|
||||||
|
() => useAccountSubmodules({ editingAccount: null, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// longLoginGuardAction 阻止空账号长期登录操作。
|
||||||
|
async () => hook.result.current.handleLongLoginToggle(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// aiGuardAction 阻止空账号 AI 保存操作。
|
||||||
|
async () => hook.result.current.handleSaveAISettings(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// editGuardAction 阻止空账号编辑保存操作。
|
||||||
|
async () => hook.result.current.handleSaveEdit(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// pauseGuardAction 阻止空账号暂停操作。
|
||||||
|
async () => hook.result.current.handleRestartPause(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// passwordGuardAction 阻止空账号密码登录操作。
|
||||||
|
async () => hook.result.current.handlePasswordLogin(),
|
||||||
|
);
|
||||||
|
expect(setLongLoginMock).not.toHaveBeenCalled();
|
||||||
|
expect(updateAIMock).not.toHaveBeenCalled();
|
||||||
|
expect(updateAccountMock).not.toHaveBeenCalled();
|
||||||
|
expect(pauseMock).not.toHaveBeenCalled();
|
||||||
|
expect(passwordLoginMock).not.toHaveBeenCalled();
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
import { useCallback,useEffect,useRef,useState,type Dispatch,type SetStateAction } from 'react';
|
||||||
|
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
|
||||||
|
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||||
|
import { cancelPasswordLogin,checkPasswordLoginStatus,getAccountAISettings,getAccountBindings,getLongLoginSettings,getNotificationChannels,passwordLogin,setLongLoginSettings,updateAccountAISettings,updateAccountPauseDuration,updateAccountSettings } from './api';
|
||||||
|
import { buildAccountLoginInfoUpdate,isCurrentAccountRequest,passwordLoginViewFromStatus,shouldUpdateAccountPause } from './state';
|
||||||
|
import type { AccountEditForm,LongLoginState,PasswordLoginView } from './types';
|
||||||
|
|
||||||
|
/** AccountList 当前编辑弹窗类型。 */
|
||||||
|
export type AccountModalType = 'edit' | 'ai-settings' | null;
|
||||||
|
|
||||||
|
/** AccountList 子模块 Hook 的输入。 */
|
||||||
|
export type AccountSubmoduleOptions = {
|
||||||
|
/** 当前编辑账号。 */
|
||||||
|
editingAccount: AccountDetail | null;
|
||||||
|
/** 写入当前编辑账号。 */
|
||||||
|
setEditingAccount: Dispatch<SetStateAction<AccountDetail | null>>;
|
||||||
|
/** 当前编辑弹窗类型。 */
|
||||||
|
setActiveModal: Dispatch<SetStateAction<AccountModalType>>;
|
||||||
|
/** 当前编辑表单。 */
|
||||||
|
editForm: AccountEditForm;
|
||||||
|
/** 更新编辑表单。 */
|
||||||
|
setEditForm: Dispatch<SetStateAction<AccountEditForm>>;
|
||||||
|
/** 刷新账号列表。 */
|
||||||
|
loadAccounts: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 账号编辑、AI、通知绑定和密码登录子模块共享状态。 */
|
||||||
|
export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setActiveModal, editForm, setEditForm, loadAccounts }: AccountSubmoduleOptions) => {
|
||||||
|
// longLogin 保存官方长登录设置状态。
|
||||||
|
const [longLogin, setLongLogin] = useState<LongLoginState>({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||||
|
// notifChannels 保存可供账号绑定的通知渠道。
|
||||||
|
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||||
|
// selectedChannelIds 保存当前选中的通知渠道。
|
||||||
|
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
|
||||||
|
// bindingsLoaded 表示绑定关系是否成功加载。
|
||||||
|
const [bindingsLoaded, setBindingsLoaded] = useState(false);
|
||||||
|
// bindingsLoading 表示通知绑定请求是否进行中。
|
||||||
|
const [bindingsLoading, setBindingsLoading] = useState(false);
|
||||||
|
// bindingsDirty 表示用户是否修改过通知绑定。
|
||||||
|
const [bindingsDirty, setBindingsDirty] = useState(false);
|
||||||
|
// bindingsLoadError 保存通知绑定加载错误。
|
||||||
|
const [bindingsLoadError, setBindingsLoadError] = useState('');
|
||||||
|
// aiSettings 保存账号 AI 编辑草稿。
|
||||||
|
const [aiSettings, setAiSettings] = useState<AIReplySettings>({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
|
||||||
|
// saving 表示编辑、AI 或暂停动作是否正在保存。
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
// passwordLoginView 保存密码登录刷新授权状态。
|
||||||
|
const [passwordLoginView, setPasswordLoginView] = useState<PasswordLoginView>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||||
|
// bindingsSequence 隔离账号切换后的绑定响应。
|
||||||
|
const bindingsSequence = useRef(0);
|
||||||
|
// bindingsAbort 保存通知绑定请求控制器。
|
||||||
|
const bindingsAbort = useRef<AbortController | null>(null);
|
||||||
|
// longLoginSequence 隔离账号切换后的长登录响应。
|
||||||
|
const longLoginSequence = useRef(0);
|
||||||
|
// longLoginAbort 保存长登录状态读取控制器。
|
||||||
|
const longLoginAbort = useRef<AbortController | null>(null);
|
||||||
|
// aiSequence 隔离账号切换后的 AI 响应。
|
||||||
|
const aiSequence = useRef(0);
|
||||||
|
// aiAbort 保存 AI 查询控制器。
|
||||||
|
const aiAbort = useRef<AbortController | null>(null);
|
||||||
|
// passwordGeneration 隔离密码登录轮询响应。
|
||||||
|
const passwordGeneration = useRef(0);
|
||||||
|
// passwordAccount 保存密码登录所属账号。
|
||||||
|
const passwordAccount = useRef('');
|
||||||
|
// passwordAbort 保存密码登录状态查询控制器。
|
||||||
|
const passwordAbort = useRef<AbortController | null>(null);
|
||||||
|
// passwordTimer 保存下一次密码登录轮询定时器。
|
||||||
|
const passwordTimer = useRef<number | null>(null);
|
||||||
|
|
||||||
|
/** 清理密码登录轮询定时器。 */
|
||||||
|
// clearPasswordTimerCallback 是 React 稳定的定时器清理函数。
|
||||||
|
const clearPasswordTimer = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
|
||||||
|
if (passwordTimer.current !== null) {
|
||||||
|
window.clearTimeout(passwordTimer.current);
|
||||||
|
passwordTimer.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/** 加载当前账号通知渠道和绑定关系,并隔离过期响应。 */
|
||||||
|
// loadNotificationBindingsCallback 是通知绑定加载回调。
|
||||||
|
const loadNotificationBindings = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (accountId: string): Promise<void> => {
|
||||||
|
// sequence 是通知绑定请求的递增代次。
|
||||||
|
const sequence = ++bindingsSequence.current;
|
||||||
|
bindingsAbort.current?.abort();
|
||||||
|
// controller 控制当前通知绑定请求的取消。
|
||||||
|
const controller = new AbortController();
|
||||||
|
bindingsAbort.current = controller;
|
||||||
|
setBindingsLoading(true);
|
||||||
|
setBindingsLoaded(false);
|
||||||
|
setBindingsDirty(false);
|
||||||
|
setBindingsLoadError('');
|
||||||
|
// bindingResults 保存通知渠道和账号绑定的并行结果。
|
||||||
|
const [channelsResult, bindingsResult] = await Promise.allSettled([
|
||||||
|
getNotificationChannels({ signal: controller.signal }),
|
||||||
|
getAccountBindings(accountId, { signal: controller.signal }),
|
||||||
|
]);
|
||||||
|
if (!isCurrentAccountRequest(sequence, bindingsSequence.current, accountId, accountId)) return;
|
||||||
|
if (channelsResult.status === 'fulfilled') setNotifChannels(channelsResult.value.data || []);
|
||||||
|
else { setNotifChannels([]); setBindingsLoadError('通知渠道列表加载失败,请重试'); }
|
||||||
|
if (bindingsResult.status === 'fulfilled') { setSelectedChannelIds(bindingsResult.value || []); setBindingsLoaded(true); }
|
||||||
|
else { setSelectedChannelIds([]); setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定'); }
|
||||||
|
setBindingsLoading(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/** 切换一个通知渠道绑定。 */
|
||||||
|
// toggleNotificationChannelCallback 是通知渠道切换回调。
|
||||||
|
const toggleNotificationChannel = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ (channelId: number) => {
|
||||||
|
setSelectedChannelIds(/* 当前回调处理集合中的单个元素。 */ current => current.includes(channelId) ? current.filter(/* 当前回调处理集合中的单个元素。 */ id => id !== channelId) : [...current, channelId]);
|
||||||
|
setBindingsDirty(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/** 打开账号编辑弹窗并并行读取绑定和长登录状态。 */
|
||||||
|
// openEditModalCallback 是账号编辑弹窗打开回调。
|
||||||
|
const openEditModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (account: AccountDetail): Promise<void> => {
|
||||||
|
// longLoginRequest 是当前长登录读取请求代次。
|
||||||
|
const longLoginRequest = ++longLoginSequence.current;
|
||||||
|
longLoginAbort.current?.abort();
|
||||||
|
// longLoginController 控制当前长登录读取请求的取消。
|
||||||
|
const longLoginController = new AbortController();
|
||||||
|
longLoginAbort.current = longLoginController;
|
||||||
|
passwordGeneration.current += 1;
|
||||||
|
passwordAccount.current = account.id;
|
||||||
|
passwordAbort.current?.abort();
|
||||||
|
clearPasswordTimer();
|
||||||
|
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||||
|
setEditingAccount(account);
|
||||||
|
// 摘要接口不会返回 Cookie 或密码明文;编辑表单只接收本次用户主动输入的秘密。
|
||||||
|
setEditForm({ remark: account.remark || '', cookie: '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
|
||||||
|
setActiveModal('edit');
|
||||||
|
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||||
|
// longLoginResult 保存长登录设置读取结果。
|
||||||
|
const [, longLoginResult] = await Promise.allSettled([loadNotificationBindings(account.id), getLongLoginSettings(account.id, { signal: longLoginController.signal })]);
|
||||||
|
if (longLoginRequest !== longLoginSequence.current) return;
|
||||||
|
if (longLoginResult.status === 'fulfilled') setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
|
||||||
|
else setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
|
||||||
|
}, [clearPasswordTimer, loadNotificationBindings, setActiveModal, setEditForm, setEditingAccount]);
|
||||||
|
|
||||||
|
/** 切换官方长登录设置。 */
|
||||||
|
// handleLongLoginToggleCallback 是长登录设置切换回调。
|
||||||
|
const handleLongLoginToggle = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
|
||||||
|
// enabled 是本次准备提交的长登录开关值。
|
||||||
|
const enabled = !longLogin.enabled;
|
||||||
|
setLongLogin(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, saving: true, error: '' }));
|
||||||
|
try {
|
||||||
|
// result 保存长登录设置接口返回值。
|
||||||
|
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||||
|
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||||
|
} catch (/* error 保存长登录开关请求的失败原因,供弹窗展示且不泄露凭证。 */ error) {
|
||||||
|
// error 保存长登录设置保存失败原因。
|
||||||
|
setLongLogin(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||||
|
}
|
||||||
|
}, [editingAccount, longLogin]);
|
||||||
|
|
||||||
|
/** 打开 AI 设置并隔离过期账号响应。 */
|
||||||
|
// openAIModalCallback 是 AI 设置弹窗打开回调。
|
||||||
|
const openAIModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (account: AccountDetail): Promise<void> => {
|
||||||
|
// sequence 是 AI 设置请求的递增代次。
|
||||||
|
const sequence = ++aiSequence.current;
|
||||||
|
aiAbort.current?.abort();
|
||||||
|
// controller 控制当前 AI 设置请求的取消。
|
||||||
|
const controller = new AbortController();
|
||||||
|
aiAbort.current = controller;
|
||||||
|
setEditingAccount(account);
|
||||||
|
setActiveModal('ai-settings');
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
// settings 保存当前账号的 AI 设置。
|
||||||
|
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||||
|
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
|
||||||
|
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' });
|
||||||
|
} catch (/* error 保存 AI 设置读取请求的失败原因,过期请求不会更新当前界面。 */ error) {
|
||||||
|
// error 保存 AI 设置读取失败原因。
|
||||||
|
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
|
||||||
|
} finally {
|
||||||
|
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) setSaving(false);
|
||||||
|
}
|
||||||
|
}, [setActiveModal, setEditingAccount]);
|
||||||
|
|
||||||
|
/** 保存 AI 设置并刷新账号列表。 */
|
||||||
|
// handleSaveAISettingsCallback 是 AI 设置保存回调。
|
||||||
|
const handleSaveAISettings = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!editingAccount || saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await updateAccountAISettings(editingAccount.id, aiSettings);
|
||||||
|
setActiveModal(null);
|
||||||
|
await loadAccounts();
|
||||||
|
} catch (/* error 保存 AI 设置提交请求的失败原因,转换为通用错误提示。 */ error) {
|
||||||
|
// error 保存 AI 设置保存失败原因。
|
||||||
|
console.error('更新 AI 设置失败:', error);
|
||||||
|
} finally { setSaving(false); }
|
||||||
|
}, [aiSettings, editingAccount, loadAccounts, saving, setActiveModal]);
|
||||||
|
|
||||||
|
/** 保存账号编辑表单和通知绑定。 */
|
||||||
|
// handleSaveEditCallback 是账号编辑表单保存回调。
|
||||||
|
const handleSaveEdit = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!editingAccount || saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
// payload 保存需要提交的账号编辑补丁。
|
||||||
|
const payload: Parameters<typeof updateAccountSettings>[1] = {};
|
||||||
|
if (editForm.remark !== (editingAccount.remark || '')) payload.remark = editForm.remark;
|
||||||
|
// 编辑表单中的 Cookie 只有用户本次输入时才会提交,避免从账号摘要读取或回填明文。
|
||||||
|
if (editForm.cookie) payload.cookie = editForm.cookie;
|
||||||
|
if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm;
|
||||||
|
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration;
|
||||||
|
// loginInfo 保存登录字段变更补丁。
|
||||||
|
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
|
||||||
|
if (loginInfo) Object.assign(payload, loginInfo);
|
||||||
|
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) payload.channel_ids = selectedChannelIds;
|
||||||
|
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
|
||||||
|
setActiveModal(null);
|
||||||
|
await loadAccounts();
|
||||||
|
} catch (/* error 保存账号设置提交请求的失败原因,转换为通用错误提示。 */ error) {
|
||||||
|
// error 保存账号编辑保存失败原因。
|
||||||
|
console.error('更新账号失败:', error);
|
||||||
|
} finally { setSaving(false); }
|
||||||
|
}, [bindingsDirty, bindingsLoaded, editForm, editingAccount, loadAccounts, selectedChannelIds, saving, setActiveModal]);
|
||||||
|
|
||||||
|
/** 按当前暂停时长重新暂停账号。 */
|
||||||
|
// handleRestartPauseCallback 是重新暂停账号回调。
|
||||||
|
const handleRestartPause = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!editingAccount || editForm.pause_duration <= 0 || saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
// result 保存重新暂停接口返回的账号状态。
|
||||||
|
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
|
||||||
|
setEditingAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
|
||||||
|
await loadAccounts();
|
||||||
|
} catch (/* error 保存重新暂停请求的失败原因,仅输出不含凭证的诊断信息。 */ error) { console.error('重新暂停失败:', error); }
|
||||||
|
finally { setSaving(false); }
|
||||||
|
}, [editForm.pause_duration, editingAccount, loadAccounts, saving, setEditingAccount]);
|
||||||
|
|
||||||
|
/** 按账号和请求代次轮询密码登录状态。 */
|
||||||
|
// pollPasswordLoginCallback 是密码登录状态轮询回调。
|
||||||
|
const pollPasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (sessionId: string, generation: number, accountId: string): Promise<void> => {
|
||||||
|
passwordAbort.current?.abort();
|
||||||
|
// controller 控制当前密码登录状态查询的取消。
|
||||||
|
const controller = new AbortController();
|
||||||
|
passwordAbort.current = controller;
|
||||||
|
try {
|
||||||
|
// result 保存后端返回的密码登录状态。
|
||||||
|
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
|
||||||
|
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
|
||||||
|
// nextView 是面向编辑弹窗展示的状态。
|
||||||
|
const nextView = { ...passwordLoginViewFromStatus(result), sessionId };
|
||||||
|
if (result.status === 'success') {
|
||||||
|
clearPasswordTimer();
|
||||||
|
setPasswordLoginView(nextView);
|
||||||
|
setEditForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, login_password: '', showLoginPassword: false }));
|
||||||
|
await loadAccounts();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.status === 'processing' || result.status === 'verification_required') {
|
||||||
|
setPasswordLoginView(nextView);
|
||||||
|
clearPasswordTimer();
|
||||||
|
passwordTimer.current = window.setTimeout(/* 当前回调处理用户交互或异步状态变化。 */ () => void pollPasswordLogin(sessionId, generation, accountId), 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearPasswordTimer();
|
||||||
|
setPasswordLoginView(nextView);
|
||||||
|
} catch (/* error 保存密码登录状态查询的失败原因,过期代次不会覆盖当前状态。 */ error) {
|
||||||
|
// error 保存密码登录状态查询失败原因。
|
||||||
|
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
|
||||||
|
clearPasswordTimer();
|
||||||
|
setPasswordLoginView({ sessionId, status: 'failed', message: error instanceof Error ? error.message : '查询密码登录状态失败', qrCodeUrl: '' });
|
||||||
|
}
|
||||||
|
}, [clearPasswordTimer, loadAccounts, setEditForm]);
|
||||||
|
|
||||||
|
/** 启动账号密码登录刷新授权。 */
|
||||||
|
// handlePasswordLoginCallback 是密码登录启动回调。
|
||||||
|
const handlePasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
if (!editingAccount) return;
|
||||||
|
// accountName 是本次登录使用的闲鱼账号名。
|
||||||
|
const accountName = editForm.username.trim();
|
||||||
|
if (!accountName || !editForm.login_password) return;
|
||||||
|
clearPasswordTimer();
|
||||||
|
passwordAbort.current?.abort();
|
||||||
|
// generation 是本次密码登录请求的递增代次。
|
||||||
|
const generation = ++passwordGeneration.current;
|
||||||
|
passwordAccount.current = editingAccount.id;
|
||||||
|
// startController 控制密码登录启动请求的取消。
|
||||||
|
const startController = new AbortController();
|
||||||
|
passwordAbort.current = startController;
|
||||||
|
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
|
||||||
|
try {
|
||||||
|
// result 保存密码登录启动接口返回值。
|
||||||
|
const result = await passwordLogin({ account_id: editingAccount.id, account: accountName, password: editForm.login_password, show_browser: editForm.show_browser }, { signal: startController.signal });
|
||||||
|
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.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, editingAccount.id);
|
||||||
|
} catch (/* error 保存密码登录启动请求的失败原因,转换为安全的登录提示。 */ error) {
|
||||||
|
// error 保存密码登录启动失败原因。
|
||||||
|
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
|
||||||
|
setPasswordLoginView({ sessionId: '', status: 'failed', message: error instanceof Error ? error.message : '启动密码登录失败', qrCodeUrl: '' });
|
||||||
|
}
|
||||||
|
}, [clearPasswordTimer, editForm.login_password, editForm.show_browser, editForm.username, editingAccount, pollPasswordLogin]);
|
||||||
|
|
||||||
|
/** 取消当前密码登录会话。 */
|
||||||
|
// handleCancelPasswordLoginCallback 是密码登录取消回调。
|
||||||
|
const handleCancelPasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
// sessionId 是当前待取消的密码登录会话。
|
||||||
|
const sessionId = passwordLoginView.sessionId;
|
||||||
|
passwordGeneration.current += 1;
|
||||||
|
passwordAccount.current = '';
|
||||||
|
passwordAbort.current?.abort();
|
||||||
|
clearPasswordTimer();
|
||||||
|
if (sessionId) await cancelPasswordLogin(sessionId).catch(/* 当前回调处理异步操作结果。 */ () => undefined);
|
||||||
|
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||||
|
}, [clearPasswordTimer, passwordLoginView.sessionId]);
|
||||||
|
|
||||||
|
/** 关闭编辑弹窗并取消未完成的子模块请求。 */
|
||||||
|
// closeEditModalCallback 是编辑弹窗关闭回调。
|
||||||
|
const closeEditModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
|
||||||
|
bindingsAbort.current?.abort();
|
||||||
|
longLoginSequence.current += 1;
|
||||||
|
longLoginAbort.current?.abort();
|
||||||
|
aiAbort.current?.abort();
|
||||||
|
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') await handleCancelPasswordLogin();
|
||||||
|
setActiveModal(null);
|
||||||
|
}, [handleCancelPasswordLogin, passwordLoginView.status, setActiveModal]);
|
||||||
|
|
||||||
|
/** 关闭 AI 设置弹窗并取消读取请求。 */
|
||||||
|
// closeAIModalCallback 是 AI 设置弹窗关闭回调。
|
||||||
|
const closeAIModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
|
||||||
|
aiSequence.current += 1;
|
||||||
|
aiAbort.current?.abort();
|
||||||
|
setActiveModal(null);
|
||||||
|
}, [setActiveModal]);
|
||||||
|
|
||||||
|
// cleanupSubmodulesEffect 在 Hook 卸载时取消所有子模块请求。
|
||||||
|
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => {
|
||||||
|
bindingsAbort.current?.abort();
|
||||||
|
longLoginAbort.current?.abort();
|
||||||
|
aiAbort.current?.abort();
|
||||||
|
passwordAbort.current?.abort();
|
||||||
|
clearPasswordTimer();
|
||||||
|
}, [clearPasswordTimer]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
longLogin, notifChannels, selectedChannelIds, bindingsLoaded, bindingsLoading, bindingsDirty, bindingsLoadError,
|
||||||
|
aiSettings, saving, passwordLoginView, setAiSettings, setBindingsDirty, setEditForm, openEditModal,
|
||||||
|
closeEditModal, openAIModal, closeAIModal, loadNotificationBindings, toggleNotificationChannel,
|
||||||
|
handleLongLoginToggle, handleSaveAISettings, handleSaveEdit, handleRestartPause, handlePasswordLogin,
|
||||||
|
handleCancelPasswordLogin,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import type { Dispatch,SetStateAction } from 'react';
|
||||||
|
import type { AccountDetail,AIReplySettings,NotificationChannel } from './api';
|
||||||
|
|
||||||
|
// AccountEditForm 描述账号编辑弹窗中的可编辑字段。
|
||||||
|
export interface AccountEditForm {
|
||||||
|
// remark 是账号备注。
|
||||||
|
remark: string;
|
||||||
|
// cookie 是手工维护的授权 Cookie。
|
||||||
|
cookie: string;
|
||||||
|
// auto_confirm 表示是否自动确认发货。
|
||||||
|
auto_confirm: boolean;
|
||||||
|
// pause_duration 是账号订单处理暂停时长,单位为分钟。
|
||||||
|
pause_duration: number;
|
||||||
|
// username 是用于密码登录的闲鱼账号。
|
||||||
|
username: string;
|
||||||
|
// login_password 是本次输入或已保存的登录密码。
|
||||||
|
login_password: string;
|
||||||
|
// show_browser 表示密码登录时是否展示浏览器窗口。
|
||||||
|
show_browser: boolean;
|
||||||
|
// showLoginPassword 控制密码输入框是否显示明文。
|
||||||
|
showLoginPassword: boolean;
|
||||||
|
// clear_password 表示保存时清空服务端密码。
|
||||||
|
clear_password: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// PasswordLoginView 描述密码登录刷新授权的异步状态。
|
||||||
|
export interface PasswordLoginView {
|
||||||
|
// sessionId 是后端创建的密码登录会话标识。
|
||||||
|
sessionId: string;
|
||||||
|
// status 是当前密码登录阶段。
|
||||||
|
status: 'idle' | 'processing' | 'verification_required' | 'success' | 'failed';
|
||||||
|
// message 是面向用户展示的状态说明。
|
||||||
|
message: string;
|
||||||
|
// qrCodeUrl 是风控人脸验证二维码地址。
|
||||||
|
qrCodeUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// LongLoginState 描述闲鱼官方长登录设置的读取和保存状态。
|
||||||
|
export interface LongLoginState {
|
||||||
|
// loading 表示正在读取长登录设置。
|
||||||
|
loading: boolean;
|
||||||
|
// saving 表示正在保存长登录设置。
|
||||||
|
saving: boolean;
|
||||||
|
// canOpen 表示当前账号是否允许修改长登录设置。
|
||||||
|
canOpen: boolean;
|
||||||
|
// enabled 表示闲鱼官方当前是否启用长登录。
|
||||||
|
enabled: boolean;
|
||||||
|
// error 保存读取或保存失败的用户可见说明。
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountRuntimePresentation 是账号运行状态在列表中的展示信息。
|
||||||
|
export interface AccountRuntimePresentation {
|
||||||
|
// label 是状态徽标文本。
|
||||||
|
label: string;
|
||||||
|
// badge 是状态徽标使用的 Tailwind 样式。
|
||||||
|
badge: string;
|
||||||
|
// dot 是头像旁状态点使用的 Tailwind 样式。
|
||||||
|
dot: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountEditModalProps 描述账号编辑组件需要的状态和交互回调。
|
||||||
|
export interface AccountEditModalProps {
|
||||||
|
// account 是当前正在编辑的账号。
|
||||||
|
account: AccountDetail;
|
||||||
|
// editForm 是编辑表单的当前值。
|
||||||
|
editForm: AccountEditForm;
|
||||||
|
// setEditForm 更新编辑表单字段。
|
||||||
|
setEditForm: Dispatch<SetStateAction<AccountEditForm>>;
|
||||||
|
// saving 表示保存或立即暂停动作正在执行。
|
||||||
|
saving: boolean;
|
||||||
|
// onClose 关闭编辑弹窗并取消未完成的登录操作。
|
||||||
|
onClose: () => void | Promise<void>;
|
||||||
|
// onSave 保存账号编辑内容。
|
||||||
|
onSave: () => void | Promise<void>;
|
||||||
|
// onRestartPause 按当前时长重新暂停账号。
|
||||||
|
onRestartPause: () => void | Promise<void>;
|
||||||
|
// longLogin 是官方长登录设置状态。
|
||||||
|
longLogin: LongLoginState;
|
||||||
|
// onToggleLongLogin 切换官方长登录设置。
|
||||||
|
onToggleLongLogin: () => void | Promise<void>;
|
||||||
|
// passwordLoginView 是密码登录刷新授权状态。
|
||||||
|
passwordLoginView: PasswordLoginView;
|
||||||
|
// onPasswordLogin 启动密码登录刷新授权。
|
||||||
|
onPasswordLogin: () => void | Promise<void>;
|
||||||
|
// onCancelPasswordLogin 取消当前密码登录会话。
|
||||||
|
onCancelPasswordLogin: () => void | Promise<void>;
|
||||||
|
// notifChannels 是可供账号绑定的通知渠道。
|
||||||
|
notifChannels: NotificationChannel[];
|
||||||
|
// selectedChannelIds 是当前已选中的通知渠道 ID。
|
||||||
|
selectedChannelIds: number[];
|
||||||
|
// bindingsLoaded 表示通知绑定是否成功加载。
|
||||||
|
bindingsLoaded: boolean;
|
||||||
|
// bindingsLoading 表示通知渠道和绑定关系正在加载。
|
||||||
|
bindingsLoading: boolean;
|
||||||
|
// bindingsLoadError 是通知绑定加载失败的说明。
|
||||||
|
bindingsLoadError: string;
|
||||||
|
// onRetryBindings 重新加载当前账号的通知绑定。
|
||||||
|
onRetryBindings: () => void | Promise<void>;
|
||||||
|
// onToggleChannel 切换一个通知渠道的选中状态。
|
||||||
|
onToggleChannel: (channelId: number) => void;
|
||||||
|
// onSettingsDirty 标记通知绑定已被用户修改。
|
||||||
|
onSettingsDirty: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountAISettingsState 是账号列表合并 AI 配置时使用的索引结构。
|
||||||
|
export type AccountAISettingsState = Record<string, AIReplySettings>;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,78 @@
|
|||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardAppendResponse,
|
||||||
|
CardBatchResponse,
|
||||||
|
MutationIDResponse,OperationResponse
|
||||||
|
} from '../../../shared/api-contract/cards';
|
||||||
|
import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client';
|
||||||
|
import { collectionFrom } from '../../../shared/http/contract';
|
||||||
|
export type * from '../../../shared/api-contract/cards';
|
||||||
|
// Cards
|
||||||
|
// normalizeCard 归一化卡密数据。
|
||||||
|
const normalizeCard = (item: any): Card => {
|
||||||
|
// apiConfig 卡密接口配置,用于当前 API 处理流程。
|
||||||
|
let apiConfig = item.api_config;
|
||||||
|
if (typeof apiConfig === 'string' && apiConfig.trim()) {
|
||||||
|
try {
|
||||||
|
apiConfig = JSON.parse(apiConfig);
|
||||||
|
} catch {
|
||||||
|
apiConfig = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {...item, api_config: apiConfig || undefined} as Card;
|
||||||
|
};
|
||||||
|
|
||||||
|
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
|
||||||
|
const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
|
||||||
|
...data,
|
||||||
|
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
|
||||||
|
});
|
||||||
|
|
||||||
|
// getCards 读取卡密列表。
|
||||||
|
export const getCards = async (options?: RequestControlOptions): Promise<Card[]> => {
|
||||||
|
// res 接口响应结果,用于当前 API 处理流程。
|
||||||
|
const res = await get<unknown>('/api/v1/cards', undefined, options);
|
||||||
|
// cards 卡密列表,用于当前 API 处理流程。
|
||||||
|
const cards = collectionFrom<Card>(res, ['cards', 'data', 'items']);
|
||||||
|
return cards.map(normalizeCard);
|
||||||
|
};
|
||||||
|
|
||||||
|
// createCard 创建卡密组。
|
||||||
|
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
|
||||||
|
return post('/api/v1/cards', cardPayload(data));
|
||||||
|
};
|
||||||
|
|
||||||
|
// updateCard 更新卡密组。
|
||||||
|
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
|
||||||
|
return put(`/api/v1/cards/${cardId}`, cardPayload(data));
|
||||||
|
};
|
||||||
|
|
||||||
|
// deleteCard 删除卡密组。
|
||||||
|
export const deleteCard = async (cardId: string | number): Promise<OperationResponse> => {
|
||||||
|
return del(`/api/v1/cards/${cardId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// getCardDetails 读取卡密组详情。
|
||||||
|
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
|
||||||
|
// card 卡密详情,用于当前 API 处理流程。
|
||||||
|
const card = await get<Card>(`/api/v1/cards/${cardId}/details`);
|
||||||
|
return normalizeCard(card);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 批量创建卡密组(上传表格)
|
||||||
|
export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise<CardBatchResponse> => {
|
||||||
|
// 批量创建接口返回总行数、成功数、失败数和逐行结果。
|
||||||
|
// CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。
|
||||||
|
// rows 中的 id 只在创建成功时返回。
|
||||||
|
// rows 中的 error 只在对应行失败时返回。
|
||||||
|
// 表单上传方式和接口路径保持不变。
|
||||||
|
// 此处只收紧 TypeScript 响应契约。
|
||||||
|
const body = new FormData();
|
||||||
|
body.append('file', file);
|
||||||
|
return postForm('/api/v1/cards/batch', body, options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 往 data 类型卡密组批量追加卡密号
|
||||||
|
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
|
||||||
|
return post(`/api/v1/cards/${cardId}/append-data`, { content }, options);
|
||||||
|
};
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { expect,test } from 'vitest';
|
||||||
|
import type { Card } from '../../../shared/api-contract/cards';
|
||||||
|
import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState';
|
||||||
|
|
||||||
|
// cards 是卡密筛选测试使用的最小卡密组列表。
|
||||||
|
const cards = [
|
||||||
|
{ id: 1, name: '年终总结 PPT', type: 'text', enabled: true },
|
||||||
|
{ id: 2, name: '年终总结兑换码', type: 'data', enabled: true },
|
||||||
|
{ id: 3, name: '产品介绍 PPT', type: 'text', enabled: false },
|
||||||
|
] as Card[];
|
||||||
|
|
||||||
|
test('卡密筛选同时满足类型和名称条件',
|
||||||
|
// 类型和名称筛选必须使用 AND 语义,避免展示无关库存。
|
||||||
|
() => {
|
||||||
|
expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
|
||||||
|
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('追加预览会去除空行并裁剪每行空白',
|
||||||
|
// 预览数量与最终提交内容共用同一套规范化规则。
|
||||||
|
() => {
|
||||||
|
expect(previewAppendContent(' VIP-001\n\nVIP-002 \n ')).toEqual(['VIP-001', 'VIP-002']);
|
||||||
|
expect(canSubmitAppend('2', ' VIP-001\n', false)).toBe(true);
|
||||||
|
expect(canSubmitAppend('2', '\n', false)).toBe(false);
|
||||||
|
expect(canSubmitAppend('2', 'VIP-001', true)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('追加目标切换后拒绝旧请求响应和旧代次响应',
|
||||||
|
// 用户切换卡密组或关闭弹窗后,旧追加请求不能覆盖当前状态。
|
||||||
|
() => {
|
||||||
|
expect(isCurrentCardRequest(3, 3, '2', '2')).toBe(true);
|
||||||
|
expect(isCurrentCardRequest(2, 3, '2', '2')).toBe(false);
|
||||||
|
expect(isCurrentCardRequest(3, 3, '2', '3')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('卡密筛选忽略名称周围空白并支持大小写无关匹配',
|
||||||
|
// 用户输入的名称关键字会先裁剪空白,再进行不区分大小写的匹配。
|
||||||
|
() => {
|
||||||
|
expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import type { Card } from './api';
|
||||||
|
|
||||||
|
// filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。
|
||||||
|
export const filterCards = (
|
||||||
|
cards: Card[],
|
||||||
|
typeFilter: Card['type'] | '',
|
||||||
|
nameSearch: string,
|
||||||
|
): Card[] => {
|
||||||
|
// keyword 是去除首尾空格并转为小写的名称搜索词。
|
||||||
|
const keyword = nameSearch.trim().toLocaleLowerCase();
|
||||||
|
return cards.filter(
|
||||||
|
// card 是待判断是否符合筛选条件的卡密组。
|
||||||
|
card => (
|
||||||
|
(!typeFilter || card.type === typeFilter)
|
||||||
|
&& (!keyword || card.name.toLocaleLowerCase().includes(keyword))
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// previewAppendContent 将追加文本转换为去除空行后的卡密预览列表。
|
||||||
|
export const previewAppendContent = (content: string): string[] => content
|
||||||
|
.split('\n')
|
||||||
|
.map(
|
||||||
|
// line 是追加文本中的单行原始内容。
|
||||||
|
line => line.trim(),
|
||||||
|
)
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
// canSubmitAppend 判断当前追加表单是否具备目标卡密组和有效内容。
|
||||||
|
export const canSubmitAppend = (targetId: string, content: string, busy: boolean): boolean => Boolean(
|
||||||
|
targetId && previewAppendContent(content).length > 0 && !busy,
|
||||||
|
);
|
||||||
|
|
||||||
|
// isCurrentCardRequest 判断卡密目标切换后响应是否仍属于当前请求。
|
||||||
|
export const isCurrentCardRequest = (
|
||||||
|
requestGeneration: number,
|
||||||
|
currentGeneration: number,
|
||||||
|
requestTargetId: string,
|
||||||
|
currentTargetId: string,
|
||||||
|
): boolean => requestGeneration === currentGeneration && requestTargetId === currentTargetId;
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { act,renderHook } from '@testing-library/react';
|
||||||
|
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { Card } from '../../../shared/api-contract/cards';
|
||||||
|
import { useCardActions } from './cardActions';
|
||||||
|
|
||||||
|
// cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。
|
||||||
|
const cardActionMocks = vi.hoisted(/* cardActionMockFactory 创建卡密动作 API 替身。 */ () => ({
|
||||||
|
createCard: vi.fn(),
|
||||||
|
deleteCard: vi.fn(),
|
||||||
|
updateCard: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('./api', /* cardApiMockFactory 提供卡密动作 API 替身。 */ () => ({
|
||||||
|
createCard: cardActionMocks.createCard,
|
||||||
|
deleteCard: cardActionMocks.deleteCard,
|
||||||
|
updateCard: cardActionMocks.updateCard,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// cardFixture 表示卡密动作 Hook 使用的 data 类型卡密组。
|
||||||
|
const cardFixture: Card = {
|
||||||
|
id: 1,
|
||||||
|
name: '库存一',
|
||||||
|
type: 'data',
|
||||||
|
data_content: 'A\nB',
|
||||||
|
description: '测试库存',
|
||||||
|
enabled: true,
|
||||||
|
delay_seconds: 0,
|
||||||
|
created_at: '2026-08-15T00:00:00Z',
|
||||||
|
updated_at: '2026-08-15T00:00:00Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
// textCardFixture 表示用于筛选和新增测试的文本类型卡密组。
|
||||||
|
const textCardFixture: Card = {
|
||||||
|
...cardFixture,
|
||||||
|
id: 2,
|
||||||
|
name: '文案二',
|
||||||
|
type: 'text',
|
||||||
|
data_content: undefined,
|
||||||
|
text_content: '感谢购买',
|
||||||
|
};
|
||||||
|
|
||||||
|
// createCardHook 创建卡密动作 Hook 并注入库存刷新替身。
|
||||||
|
const createCardHook = () => {
|
||||||
|
// loadCards 是卡密动作完成后的库存刷新替身。
|
||||||
|
const loadCards = vi.fn().mockResolvedValue(undefined);
|
||||||
|
// hook 是卡密动作 Hook 的渲染结果。
|
||||||
|
const hook = renderHook(/* hookFactory 创建卡密动作 Hook。 */ () => useCardActions({ cards: [cardFixture, textCardFixture], loadCards }));
|
||||||
|
return { hook, loadCards };
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('useCardActions 卡密动作协调器', /* 当前回调验证卡密筛选、编辑、新增、删除和展示动作。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置卡密 API 和浏览器提示替身。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
cardActionMocks.createCard.mockResolvedValue({ success: true, id: 3 });
|
||||||
|
cardActionMocks.deleteCard.mockResolvedValue({ success: true });
|
||||||
|
cardActionMocks.updateCard.mockResolvedValue({ success: true });
|
||||||
|
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密动作提示。 */ () => undefined);
|
||||||
|
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(/* 当前回调恢复卡密测试浏览器替身。 */ () => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('按类型和名称筛选卡密并保存编辑草稿', /* 当前回调验证卡密筛选和编辑提交。 */ async () => {
|
||||||
|
// actionContext 保存卡密编辑 Hook 和库存刷新替身。
|
||||||
|
const { hook, loadCards } = createCardHook();
|
||||||
|
expect(hook.result.current.dataCards).toEqual([cardFixture]);
|
||||||
|
act(/* filterAction 筛选文本类型卡密。 */ () => hook.result.current.setTypeFilter('text'));
|
||||||
|
expect(hook.result.current.filteredCards).toEqual([textCardFixture]);
|
||||||
|
act(/* searchAction 写入卡密名称搜索词。 */ () => hook.result.current.setNameSearch('文案'));
|
||||||
|
expect(hook.result.current.filteredCards).toEqual([textCardFixture]);
|
||||||
|
|
||||||
|
act(/* editAction 打开卡密编辑弹窗。 */ () => hook.result.current.handleEdit(textCardFixture));
|
||||||
|
act(/* editPatchAction 更新卡密编辑名称。 */ () => hook.result.current.setEditForm(current => ({ ...current, name: '新文案' })));
|
||||||
|
await act(/* saveEditAction 保存卡密编辑草稿。 */ async () => hook.result.current.handleSaveEdit());
|
||||||
|
expect(cardActionMocks.updateCard).toHaveBeenCalledWith(2, expect.objectContaining({ name: '新文案', text_content: '感谢购买' }));
|
||||||
|
expect(loadCards).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('新增卡密校验不同类型内容并刷新库存', /* 当前回调验证卡密新增表单校验和 API 载荷。 */ async () => {
|
||||||
|
// actionContext 保存卡密新增 Hook 和库存刷新替身。
|
||||||
|
const { hook, loadCards } = createCardHook();
|
||||||
|
act(/* openAddAction 打开新增卡密弹窗。 */ () => hook.result.current.setShowAddModal(true));
|
||||||
|
await act(/* emptyAddAction 提交空表单触发名称校验。 */ async () => hook.result.current.handleAddCard());
|
||||||
|
expect(window.alert).toHaveBeenCalledWith('请输入卡密名称');
|
||||||
|
|
||||||
|
act(/* formAction 写入新增文本卡密表单。 */ () => hook.result.current.setAddForm(current => ({ ...current, name: '新文案', type: 'text', content: '欢迎' })));
|
||||||
|
await act(/* addAction 提交新增文本卡密。 */ async () => hook.result.current.handleAddCard());
|
||||||
|
expect(cardActionMocks.createCard).toHaveBeenCalledWith(expect.objectContaining({ name: '新文案', type: 'text', text_content: '欢迎' }));
|
||||||
|
expect(loadCards).toHaveBeenCalledTimes(1);
|
||||||
|
expect(hook.result.current.showAddModal).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('删除取消、删除失败和状态切换失败均不制造虚假成功', /* 当前回调验证卡密删除和启停异常分支。 */ async () => {
|
||||||
|
// actionContext 保存卡密删除 Hook 和库存刷新替身。
|
||||||
|
const { hook, loadCards } = createCardHook();
|
||||||
|
vi.mocked(window.confirm).mockReturnValueOnce(false);
|
||||||
|
await act(/* cancelDeleteAction 取消卡密删除确认。 */ async () => hook.result.current.handleDelete(1));
|
||||||
|
expect(cardActionMocks.deleteCard).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
cardActionMocks.deleteCard.mockRejectedValueOnce(new Error('删除失败'));
|
||||||
|
await act(/* errorDeleteAction 执行失败的卡密删除。 */ async () => hook.result.current.handleDelete(1));
|
||||||
|
expect(window.alert).toHaveBeenCalledWith('删除失败');
|
||||||
|
expect(loadCards).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
cardActionMocks.updateCard.mockRejectedValueOnce(new Error('状态失败'));
|
||||||
|
await act(/* toggleAction 执行失败的卡密启停切换。 */ async () => hook.result.current.toggleCardStatus(cardFixture));
|
||||||
|
expect(loadCards).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('复制卡密标识和下载模板均提供浏览器动作', /* 当前回调验证卡密复制和模板下载边界。 */ async () => {
|
||||||
|
// actionContext 保存卡密展示动作 Hook 和库存刷新替身。
|
||||||
|
const { hook } = createCardHook();
|
||||||
|
// writeText 保存剪贴板写入替身。
|
||||||
|
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||||
|
Object.assign(navigator, { clipboard: { writeText } });
|
||||||
|
await act(/* copyAction 复制卡密组标识。 */ async () => hook.result.current.copyCardID(1));
|
||||||
|
expect(writeText).toHaveBeenCalledWith('1');
|
||||||
|
expect(window.alert).toHaveBeenCalledWith('已复制卡密组ID:1');
|
||||||
|
|
||||||
|
// createObjectURL 替换模板文件对象地址创建动作。
|
||||||
|
const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:card-template');
|
||||||
|
// revokeObjectURL 替换模板临时地址释放动作。
|
||||||
|
const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(/* revokeAction 释放模板临时地址。 */ () => undefined);
|
||||||
|
// click 替换模板下载链接触发动作。
|
||||||
|
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(/* clickAction 触发模板下载。 */ () => undefined);
|
||||||
|
hook.result.current.downloadCardTemplate();
|
||||||
|
expect(createObjectURL).toHaveBeenCalled();
|
||||||
|
expect(click).toHaveBeenCalled();
|
||||||
|
expect(revokeObjectURL).toHaveBeenCalledWith('blob:card-template');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
|
||||||
|
import type { Card } from './api';
|
||||||
|
import { createCard,deleteCard,updateCard } from './api';
|
||||||
|
import { filterCards } from './batchState';
|
||||||
|
import type { AddCardForm,EditCardForm } from './types';
|
||||||
|
|
||||||
|
// emptyAddForm 创建新增卡密组表单的初始值。
|
||||||
|
export const emptyAddForm = (): AddCardForm => ({
|
||||||
|
name: '',
|
||||||
|
type: 'data',
|
||||||
|
content: '',
|
||||||
|
description: '',
|
||||||
|
enabled: true,
|
||||||
|
delay_seconds: 0,
|
||||||
|
api_method: 'GET',
|
||||||
|
api_timeout: 10,
|
||||||
|
api_headers: '',
|
||||||
|
api_params: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
// CardActionsOptions 描述卡密动作协调器依赖的库存状态和刷新操作。
|
||||||
|
export interface CardActionsOptions {
|
||||||
|
// cards 保存当前卡密组列表。
|
||||||
|
cards: Card[];
|
||||||
|
// loadCards 刷新卡密组列表。
|
||||||
|
loadCards: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CardActionsState 暴露卡密页面的短暂状态、筛选状态和动作函数。
|
||||||
|
export interface CardActionsState {
|
||||||
|
// dataCards 保存可追加库存的 data 类型卡密组。
|
||||||
|
dataCards: Card[];
|
||||||
|
// filteredCards 保存筛选后的卡密组列表。
|
||||||
|
filteredCards: Card[];
|
||||||
|
// typeFilter 保存当前卡密类型筛选条件。
|
||||||
|
typeFilter: Card['type'] | '';
|
||||||
|
// setTypeFilter 更新卡密类型筛选条件。
|
||||||
|
setTypeFilter: Dispatch<SetStateAction<Card['type'] | ''>>;
|
||||||
|
// nameSearch 保存当前卡密名称搜索文本。
|
||||||
|
nameSearch: string;
|
||||||
|
// setNameSearch 更新卡密名称搜索文本。
|
||||||
|
setNameSearch: Dispatch<SetStateAction<string>>;
|
||||||
|
// showEditModal 表示编辑卡密弹窗是否打开。
|
||||||
|
showEditModal: boolean;
|
||||||
|
// setShowEditModal 更新编辑弹窗展示状态。
|
||||||
|
setShowEditModal: Dispatch<SetStateAction<boolean>>;
|
||||||
|
// showAddModal 表示新增卡密弹窗是否打开。
|
||||||
|
showAddModal: boolean;
|
||||||
|
// setShowAddModal 更新新增弹窗展示状态。
|
||||||
|
setShowAddModal: Dispatch<SetStateAction<boolean>>;
|
||||||
|
// selectedCard 保存当前正在编辑的卡密组。
|
||||||
|
selectedCard: Card | null;
|
||||||
|
// editForm 保存当前卡密编辑草稿。
|
||||||
|
editForm: EditCardForm;
|
||||||
|
// setEditForm 更新当前卡密编辑草稿。
|
||||||
|
setEditForm: Dispatch<SetStateAction<EditCardForm>>;
|
||||||
|
// addForm 保存当前新增卡密表单。
|
||||||
|
addForm: AddCardForm;
|
||||||
|
// setAddForm 更新当前新增卡密表单。
|
||||||
|
setAddForm: Dispatch<SetStateAction<AddCardForm>>;
|
||||||
|
// handleEdit 打开指定卡密组的编辑弹窗。
|
||||||
|
handleEdit: (card: Card) => void;
|
||||||
|
// handleSaveEdit 保存当前卡密编辑草稿。
|
||||||
|
handleSaveEdit: () => Promise<void>;
|
||||||
|
// handleDelete 删除指定卡密组并刷新库存。
|
||||||
|
handleDelete: (id: string | number) => Promise<void>;
|
||||||
|
// handleAddCard 创建新的卡密组并刷新库存。
|
||||||
|
handleAddCard: () => Promise<void>;
|
||||||
|
// toggleCardStatus 切换指定卡密组的启用状态。
|
||||||
|
toggleCardStatus: (card: Card) => Promise<void>;
|
||||||
|
// copyCardID 复制卡密组标识并提供失败回退。
|
||||||
|
copyCardID: (id: string | number) => Promise<void>;
|
||||||
|
// downloadCardTemplate 下载批量导入模板文件。
|
||||||
|
downloadCardTemplate: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// cardErrorMessage 将未知异常转换为稳定的卡密操作提示。
|
||||||
|
const cardErrorMessage = (error: unknown, fallback: string): string => error instanceof Error ? error.message : fallback;
|
||||||
|
|
||||||
|
// useCardActions 集中管理卡密新增、编辑、删除、筛选和展示动作。
|
||||||
|
export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardActionsState => {
|
||||||
|
// showEditModal 表示编辑卡密弹窗是否打开。
|
||||||
|
const [showEditModal, setShowEditModal] = useState(false);
|
||||||
|
// showAddModal 表示新增卡密弹窗是否打开。
|
||||||
|
const [showAddModal, setShowAddModal] = useState(false);
|
||||||
|
// selectedCard 保存当前正在编辑的卡密组。
|
||||||
|
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
|
||||||
|
// editForm 保存当前卡密编辑草稿。
|
||||||
|
const [editForm, setEditForm] = useState<EditCardForm>({});
|
||||||
|
// addForm 保存当前新增卡密表单。
|
||||||
|
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
|
||||||
|
// typeFilter 保存当前卡密类型筛选条件。
|
||||||
|
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
|
||||||
|
// nameSearch 保存当前卡密名称搜索文本。
|
||||||
|
const [nameSearch, setNameSearch] = useState('');
|
||||||
|
// dataCards 保存可追加库存的 data 类型卡密组。
|
||||||
|
const dataCards = useMemo(/* dataCardsMemo 按类型派生可追加库存列表。 */ () => cards.filter(/* dataCardFilter 筛选 data 类型卡密组。 */ card => card.type === 'data'), [cards]);
|
||||||
|
// filteredCards 保存应用类型和名称条件后的卡密列表。
|
||||||
|
const filteredCards = useMemo(
|
||||||
|
/* filteredCardsMemo 根据当前条件派生卡密列表。 */ () => filterCards(cards, typeFilter, nameSearch),
|
||||||
|
[cards, nameSearch, typeFilter],
|
||||||
|
);
|
||||||
|
|
||||||
|
// handleEdit 打开指定卡密组的编辑弹窗并初始化草稿。
|
||||||
|
const handleEdit = useCallback(/* editAction 打开卡密编辑弹窗。 */ (card: Card) => {
|
||||||
|
setSelectedCard(card);
|
||||||
|
setEditForm({
|
||||||
|
id: card.id,
|
||||||
|
name: card.name || '',
|
||||||
|
type: card.type || 'text',
|
||||||
|
api_url: card.api_config?.url || '',
|
||||||
|
api_method: card.api_config?.method || 'GET',
|
||||||
|
api_timeout: card.api_config?.timeout || 10,
|
||||||
|
api_headers: card.api_config?.headers || '',
|
||||||
|
api_params: card.api_config?.params || '',
|
||||||
|
text_content: card.text_content || '',
|
||||||
|
data_content: card.data_content || '',
|
||||||
|
image_url: card.image_url || '',
|
||||||
|
delay_seconds: card.delay_seconds || 0,
|
||||||
|
description: card.description || '',
|
||||||
|
enabled: card.enabled,
|
||||||
|
});
|
||||||
|
setShowEditModal(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// handleSaveEdit 保存当前卡密编辑草稿并刷新库存。
|
||||||
|
const handleSaveEdit = useCallback(/* saveEditAction 保存卡密编辑草稿。 */ async () => {
|
||||||
|
if (!selectedCard) return;
|
||||||
|
if (!editForm.name?.trim()) {
|
||||||
|
alert('请输入卡密名称');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!editForm.type) {
|
||||||
|
alert('请选择卡密类型');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// updateData 保存映射到卡密更新接口的字段。
|
||||||
|
const updateData: Partial<Card> = {
|
||||||
|
name: editForm.name.trim(),
|
||||||
|
type: editForm.type,
|
||||||
|
description: editForm.description?.trim(),
|
||||||
|
delay_seconds: editForm.delay_seconds || 0,
|
||||||
|
enabled: editForm.enabled ?? true,
|
||||||
|
};
|
||||||
|
if (editForm.type === 'api') {
|
||||||
|
updateData.api_config = {
|
||||||
|
url: editForm.api_url?.trim() || '',
|
||||||
|
method: editForm.api_method || 'GET',
|
||||||
|
timeout: editForm.api_timeout || 10,
|
||||||
|
headers: editForm.api_headers?.trim() || undefined,
|
||||||
|
params: editForm.api_params?.trim() || undefined,
|
||||||
|
};
|
||||||
|
} else if (editForm.type === 'text') {
|
||||||
|
updateData.text_content = editForm.text_content?.trim() || '';
|
||||||
|
} else if (editForm.type === 'data') {
|
||||||
|
updateData.data_content = editForm.data_content?.trim() || '';
|
||||||
|
} else if (editForm.type === 'image') {
|
||||||
|
updateData.image_url = editForm.image_url?.trim() || '';
|
||||||
|
}
|
||||||
|
await updateCard(selectedCard.id, updateData);
|
||||||
|
setShowEditModal(false);
|
||||||
|
await loadCards();
|
||||||
|
} catch (/* error 表示卡密编辑请求异常。 */ error: unknown) {
|
||||||
|
console.error('更新卡密失败:', error);
|
||||||
|
alert(cardErrorMessage(error, '更新失败,请重试'));
|
||||||
|
}
|
||||||
|
}, [editForm, loadCards, selectedCard]);
|
||||||
|
|
||||||
|
// handleDelete 删除指定卡密组并刷新库存。
|
||||||
|
const handleDelete = useCallback(/* deleteAction 删除卡密组。 */ async (id: string | number) => {
|
||||||
|
if (!confirm('确认删除该卡密吗?')) return;
|
||||||
|
try {
|
||||||
|
await deleteCard(id);
|
||||||
|
await loadCards();
|
||||||
|
} catch (/* error 表示卡密删除请求异常。 */ error: unknown) {
|
||||||
|
console.error('删除卡密失败:', error);
|
||||||
|
alert(cardErrorMessage(error, '删除失败,请重试'));
|
||||||
|
}
|
||||||
|
}, [loadCards]);
|
||||||
|
|
||||||
|
// handleAddCard 校验新增表单、创建卡密组并刷新库存。
|
||||||
|
const handleAddCard = useCallback(/* addAction 创建新的卡密组。 */ async () => {
|
||||||
|
if (!addForm.name.trim()) {
|
||||||
|
alert('请输入卡密名称');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!addForm.content.trim()) {
|
||||||
|
alert(addForm.type === 'api' ? '请输入 API 地址' : '请输入卡密内容');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// payload 保存新增卡密组的接口载荷。
|
||||||
|
const payload: Partial<Card> = {
|
||||||
|
name: addForm.name.trim(),
|
||||||
|
type: addForm.type,
|
||||||
|
description: addForm.description.trim(),
|
||||||
|
enabled: addForm.enabled,
|
||||||
|
delay_seconds: addForm.delay_seconds,
|
||||||
|
};
|
||||||
|
if (addForm.type === 'text') payload.text_content = addForm.content.trim();
|
||||||
|
if (addForm.type === 'data') payload.data_content = addForm.content.trim();
|
||||||
|
if (addForm.type === 'image') payload.image_url = addForm.content.trim();
|
||||||
|
if (addForm.type === 'api') {
|
||||||
|
payload.api_config = {
|
||||||
|
url: addForm.content.trim(),
|
||||||
|
method: addForm.api_method,
|
||||||
|
timeout: addForm.api_timeout,
|
||||||
|
headers: addForm.api_headers.trim() || undefined,
|
||||||
|
params: addForm.api_params.trim() || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
await createCard(payload);
|
||||||
|
setShowAddModal(false);
|
||||||
|
setAddForm(emptyAddForm());
|
||||||
|
await loadCards();
|
||||||
|
} catch (/* error 表示卡密创建请求异常。 */ error: unknown) {
|
||||||
|
console.error('添加卡密失败:', error);
|
||||||
|
alert(cardErrorMessage(error, '添加失败,请重试'));
|
||||||
|
}
|
||||||
|
}, [addForm, loadCards]);
|
||||||
|
|
||||||
|
// toggleCardStatus 切换指定卡密组的启用状态并刷新库存。
|
||||||
|
const toggleCardStatus = useCallback(/* toggleAction 切换卡密启用状态。 */ async (card: Card) => {
|
||||||
|
try {
|
||||||
|
await updateCard(card.id, { ...card, enabled: !card.enabled });
|
||||||
|
await loadCards();
|
||||||
|
} catch (/* error 表示卡密状态更新异常。 */ error: unknown) {
|
||||||
|
console.error('切换状态失败:', error);
|
||||||
|
}
|
||||||
|
}, [loadCards]);
|
||||||
|
|
||||||
|
// copyCardID 复制卡密组标识,剪贴板不可用时回退到提示框。
|
||||||
|
const copyCardID = useCallback(/* copyAction 复制卡密组标识。 */ async (id: string | number) => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(String(id));
|
||||||
|
alert(`已复制卡密组ID:${id}`);
|
||||||
|
} catch {
|
||||||
|
prompt('复制卡密组ID', String(id));
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// downloadCardTemplate 生成并下载卡密批量导入模板。
|
||||||
|
const downloadCardTemplate = useCallback(/* downloadAction 下载卡密导入模板。 */ () => {
|
||||||
|
// headers 保存模板列名。
|
||||||
|
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
|
||||||
|
// rows 保存模板示例数据。
|
||||||
|
const rows = [
|
||||||
|
['VIP月卡', 'data', 'VIP-MONTH-001\nVIP-MONTH-002\nVIP-MONTH-003', '按行消费的卡密队列', '是', '0', '否', '', ''],
|
||||||
|
['感谢文案', 'text', '感谢购买,如有问题联系客服~', '固定文本', '是', '0', '否', '', ''],
|
||||||
|
['教程图', 'image', 'https://cdn.example.com/tutorial.jpg', '图片URL', '是', '0', '否', '', ''],
|
||||||
|
];
|
||||||
|
// csv 保存转义后的模板文本。
|
||||||
|
const csv = [headers, ...rows]
|
||||||
|
.map(/* csvRowMap 处理模板中的每一行。 */ row => row.map(/* csvCellMap 转义模板单元格。 */ cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
|
||||||
|
.join('\n');
|
||||||
|
// blob 保存生成的 CSV 文件对象。
|
||||||
|
const blob = new Blob(['' + csv], { type: 'text/csv;charset=utf-8' });
|
||||||
|
// url 保存模板文件的临时对象地址。
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
// link 保存触发浏览器下载的临时链接。
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = '卡密组批量导入模板.csv';
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dataCards,
|
||||||
|
filteredCards,
|
||||||
|
typeFilter,
|
||||||
|
setTypeFilter,
|
||||||
|
nameSearch,
|
||||||
|
setNameSearch,
|
||||||
|
showEditModal,
|
||||||
|
setShowEditModal,
|
||||||
|
showAddModal,
|
||||||
|
setShowAddModal,
|
||||||
|
selectedCard,
|
||||||
|
editForm,
|
||||||
|
setEditForm,
|
||||||
|
addForm,
|
||||||
|
setAddForm,
|
||||||
|
handleEdit,
|
||||||
|
handleSaveEdit,
|
||||||
|
handleDelete,
|
||||||
|
handleAddCard,
|
||||||
|
toggleCardStatus,
|
||||||
|
copyCardID,
|
||||||
|
downloadCardTemplate,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { FileDown,ListPlus,Loader2,Plus,Upload,X } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import type { Card } from '../api';
|
||||||
|
import type { CardBatchModalProps } from '../types';
|
||||||
|
|
||||||
|
// BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。
|
||||||
|
export const BatchCardImportModal: React.FC<CardBatchModalProps> = ({
|
||||||
|
dataCards,
|
||||||
|
downloadCardTemplate,
|
||||||
|
...state
|
||||||
|
}) => {
|
||||||
|
// handleFileChange 保存用户选择的批量导入文件。
|
||||||
|
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
state.setBatchFile(event.target.files?.[0] || null);
|
||||||
|
};
|
||||||
|
// handleAppendContentChange 更新追加文本并保留原始换行,预览由 Hook 派生。
|
||||||
|
const handleAppendContentChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
|
state.setAppendContent(event.target.value);
|
||||||
|
};
|
||||||
|
// handleTargetChange 切换追加库存目标卡密组。
|
||||||
|
const handleTargetChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
|
state.setAppendTargetId(event.target.value);
|
||||||
|
};
|
||||||
|
// handleClose 关闭弹窗并取消当前批量请求。
|
||||||
|
const handleClose = () => state.closeBatchModal();
|
||||||
|
// handleCreateTab 切换到批量创建页签。
|
||||||
|
const handleCreateTab = () => state.setBatchTab('create');
|
||||||
|
// handleAppendTab 切换到库存追加页签。
|
||||||
|
const handleAppendTab = () => state.setBatchTab('append');
|
||||||
|
// handleRetryCreate 重试最近一次批量创建。
|
||||||
|
const handleRetryCreate = () => void state.handleRetryBatchCreate();
|
||||||
|
// handleRetryAppend 重试最近一次库存追加。
|
||||||
|
const handleRetryAppend = () => void state.handleRetryBatchAppend();
|
||||||
|
// completedBatchResult 只保留包含逐行统计的成功批量结果。
|
||||||
|
const completedBatchResult = state.batchResult && 'rows' in state.batchResult ? state.batchResult : null;
|
||||||
|
// renderCardOption 渲染追加目标卡密组的下拉选项。
|
||||||
|
const renderCardOption = (card: Card) => <option key={card.id} value={String(card.id)}>{card.name}(ID: {card.id})</option>;
|
||||||
|
// handleSubmitCreate 提交批量创建请求。
|
||||||
|
const handleSubmitCreate = () => void state.handleBatchCreate();
|
||||||
|
// handleSubmitAppend 提交批量追加请求。
|
||||||
|
const handleSubmitAppend = () => void state.handleBatchAppend();
|
||||||
|
|
||||||
|
if (!state.showBatchModal) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="modal-overlay">
|
||||||
|
<div className="modal-container" style={{ maxWidth: '40rem' }}>
|
||||||
|
<div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between">
|
||||||
|
<h3 className="text-xl font-extrabold text-gray-900">批量导入卡密</h3>
|
||||||
|
<button onClick={handleClose} className="w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center">
|
||||||
|
<X className="w-5 h-5 text-gray-600" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-6 py-5 space-y-5">
|
||||||
|
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
|
||||||
|
<button onClick={handleCreateTab} className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${state.batchTab === 'create' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
|
||||||
|
<ListPlus className="w-4 h-4" />批量创建卡密组
|
||||||
|
</button>
|
||||||
|
<button onClick={handleAppendTab} className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${state.batchTab === 'append' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
|
||||||
|
<Upload className="w-4 h-4" />往单个组充卡密
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{state.batchTab === 'create' ? (
|
||||||
|
<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;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<button onClick={downloadCardTemplate} className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors">
|
||||||
|
<FileDown className="w-4 h-4" />下载模板
|
||||||
|
</button>
|
||||||
|
<label className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors">
|
||||||
|
<Upload className="w-4 h-4" />{state.batchFile ? state.batchFile.name : '选择 .xlsx / .csv / .tsv'}
|
||||||
|
<input type="file" accept=".xlsx,.csv,.tsv" className="hidden" onChange={handleFileChange} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{state.batchResult?.error && (
|
||||||
|
<div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3">
|
||||||
|
<span>{state.batchResult.error}</span>
|
||||||
|
<button type="button" onClick={handleRetryCreate} disabled={!state.batchFile || state.batchBusy} className="font-bold whitespace-nowrap">重试</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{completedBatchResult && (
|
||||||
|
<div className="rounded-xl border border-gray-200 p-4 space-y-2">
|
||||||
|
<div className="text-sm font-bold text-gray-900">共 {completedBatchResult.total} 行 · 成功 {completedBatchResult.created} · 失败 {completedBatchResult.failed}</div>
|
||||||
|
{completedBatchResult.failed > 0 && (
|
||||||
|
<div className="max-h-48 overflow-y-auto space-y-1">
|
||||||
|
{completedBatchResult.rows.filter(
|
||||||
|
// row 是批量结果中的单行处理记录。
|
||||||
|
row => !row.success,
|
||||||
|
).map(
|
||||||
|
// row 是待展示失败说明的单行结果。
|
||||||
|
row => (
|
||||||
|
<div key={row.row_no} className="text-xs text-red-600">第 {row.row_no} 行「{row.name}」:{row.error}</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{dataCards.length === 0 ? (
|
||||||
|
<div className="rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800">暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="block text-sm font-bold text-gray-800">选择卡密组</label>
|
||||||
|
<select value={state.appendTargetId} onChange={handleTargetChange} className="w-full ios-input px-4 py-3 rounded-xl text-sm">
|
||||||
|
{dataCards.map(renderCardOption)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="block text-sm font-bold text-gray-800">卡密号(每行一个)</label>
|
||||||
|
<textarea value={state.appendContent} onChange={handleAppendContentChange} placeholder={'VIP-001\nVIP-002\nVIP-003'} className="w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y" />
|
||||||
|
<p className="text-xs text-gray-500">预览:{state.appendPreview.length} 个有效卡密,空行自动忽略。</p>
|
||||||
|
</div>
|
||||||
|
{state.appendError && (
|
||||||
|
<div className="rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3">
|
||||||
|
<span>{state.appendError}</span>
|
||||||
|
<button type="button" onClick={handleRetryAppend} disabled={state.batchBusy} className="font-bold whitespace-nowrap">重试</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{state.appendResult && <div className="rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold">已追加 {state.appendResult.added} 个卡密</div>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
|
||||||
|
<button onClick={handleClose} className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors">关闭</button>
|
||||||
|
{state.batchTab === 'create' ? (
|
||||||
|
<button onClick={handleSubmitCreate} disabled={!state.batchFile || state.batchBusy} className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">
|
||||||
|
{state.batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}{state.batchBusy ? '处理中...' : '上传创建'}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button onClick={handleSubmitAppend} disabled={!state.appendTargetId || state.appendPreview.length === 0 || state.batchBusy || dataCards.length === 0} className="ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50">
|
||||||
|
{state.batchBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}{state.batchBusy ? '处理中...' : '追加卡密'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { Code,CreditCard,FileText,Image as ImageIcon } from 'lucide-react';
|
||||||
|
import React from 'react';
|
||||||
|
import type { Card } from '../api';
|
||||||
|
|
||||||
|
// CardIconProps 描述库存图标所需的卡密类型参数。
|
||||||
|
interface CardIconProps {
|
||||||
|
// type 是当前卡密组的交付类型。
|
||||||
|
type: Card['type'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// CardIcon 根据卡密类型渲染稳定的库存图标,避免在列表组件内声明子组件。
|
||||||
|
export const CardIcon: React.FC<CardIconProps> = ({ type }) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'text':
|
||||||
|
return <FileText className="w-5 h-5 text-blue-500" />;
|
||||||
|
case 'image':
|
||||||
|
return <ImageIcon className="w-5 h-5 text-purple-500" />;
|
||||||
|
case 'api':
|
||||||
|
return <Code className="w-5 h-5 text-blue-500" />;
|
||||||
|
default:
|
||||||
|
return <CreditCard className="w-5 h-5 text-gray-500" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { act,renderHook,waitFor } from '@testing-library/react';
|
||||||
|
import { beforeEach,describe,expect,test,vi } from 'vitest';
|
||||||
|
import type { Card } from '../../../shared/api-contract/cards';
|
||||||
|
import { appendCardData,batchCreateCards,getCards } from './api';
|
||||||
|
import { useCardBatchActions,useCardsData } from './hooks';
|
||||||
|
|
||||||
|
vi.mock('./api', /* cardsApiMockFactory 提供卡密 Hook 的确定性 API 替身。 */ () => ({
|
||||||
|
appendCardData: vi.fn(),
|
||||||
|
batchCreateCards: vi.fn(),
|
||||||
|
getCards: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// appendCardMock 是卡密追加请求的可控替身。
|
||||||
|
const appendCardMock = vi.mocked(appendCardData);
|
||||||
|
// batchCreateMock 是卡密批量创建请求的可控替身。
|
||||||
|
const batchCreateMock = vi.mocked(batchCreateCards);
|
||||||
|
// getCardsMock 是卡密库存加载请求的可控替身。
|
||||||
|
const getCardsMock = vi.mocked(getCards);
|
||||||
|
|
||||||
|
// cardFixture 是 data 类型卡密组的完整测试对象。
|
||||||
|
const cardFixture: Card = { id: 1, name: '库存一', type: 'data', enabled: true, data_content: 'old', created_at: '2026-01-01', updated_at: '2026-01-01' };
|
||||||
|
// loadCardsFixture 是批量操作完成后的库存刷新替身。
|
||||||
|
const loadCardsFixture = vi.fn().mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
describe('useCardsData 与 useCardBatchActions', /* 当前回调处理卡密库存和批量操作 Hook。 */ () => {
|
||||||
|
beforeEach(/* 当前回调重置卡密 API 替身和日志输出。 */ () => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
getCardsMock.mockResolvedValue([cardFixture]);
|
||||||
|
appendCardMock.mockResolvedValue({ success: true, added: 2 });
|
||||||
|
batchCreateMock.mockResolvedValue({ success: true, total: 1, created: 1, failed: 0, rows: [{ row_no: 1, success: true, id: 2, name: '新库存' }] });
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(
|
||||||
|
// errorImplementation 屏蔽卡密加载失败测试中的日志输出。
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('库存加载成功并支持批量追加和创建', /* 当前回调验证卡密 Hook 的成功路径。 */ async () => {
|
||||||
|
// dataHook 是卡密库存 Hook 的渲染结果。
|
||||||
|
const dataHook = renderHook(
|
||||||
|
// cardsHookFactory 创建卡密库存 Hook。
|
||||||
|
() => useCardsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待卡密库存加载完成。
|
||||||
|
() => expect(dataHook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(dataHook.result.current.cards).toEqual([cardFixture]);
|
||||||
|
dataHook.unmount();
|
||||||
|
|
||||||
|
// batchHook 是批量操作 Hook 的渲染结果。
|
||||||
|
const batchHook = renderHook(
|
||||||
|
// batchHookFactory 创建批量操作 Hook。
|
||||||
|
() => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// openAction 打开批量操作弹窗。
|
||||||
|
() => batchHook.result.current.openBatchModal(),
|
||||||
|
);
|
||||||
|
expect(batchHook.result.current.showBatchModal).toBe(true);
|
||||||
|
expect(batchHook.result.current.appendTargetId).toBe('1');
|
||||||
|
await act(
|
||||||
|
// appendContentAction 写入待追加的卡密文本。
|
||||||
|
() => batchHook.result.current.setAppendContent(' line-1\n\nline-2 '),
|
||||||
|
);
|
||||||
|
expect(batchHook.result.current.appendPreview).toEqual(['line-1', 'line-2']);
|
||||||
|
await act(
|
||||||
|
// appendAction 提交卡密追加请求。
|
||||||
|
async () => batchHook.result.current.handleBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(appendCardMock).toHaveBeenCalledWith('1', ' line-1\n\nline-2 ', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||||
|
expect(batchHook.result.current.appendResult).toEqual({ added: 2 });
|
||||||
|
await act(
|
||||||
|
// batchFileAction 写入批量创建文件。
|
||||||
|
() => batchHook.result.current.setBatchFile(new File(['name'], 'cards.csv')),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// createAction 提交批量创建请求。
|
||||||
|
async () => batchHook.result.current.handleBatchCreate(),
|
||||||
|
);
|
||||||
|
expect(batchCreateMock).toHaveBeenCalledWith(expect.any(File), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||||
|
expect(batchHook.result.current.batchResult).toMatchObject({ created: 1 });
|
||||||
|
await act(
|
||||||
|
// createRetryAction 重试当前批量创建文件。
|
||||||
|
async () => batchHook.result.current.handleRetryBatchCreate(),
|
||||||
|
);
|
||||||
|
expect(batchCreateMock).toHaveBeenCalledTimes(2);
|
||||||
|
await act(
|
||||||
|
// closeAction 关闭批量操作弹窗并取消当前请求。
|
||||||
|
() => batchHook.result.current.closeBatchModal(),
|
||||||
|
);
|
||||||
|
expect(batchHook.result.current.showBatchModal).toBe(false);
|
||||||
|
batchHook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('库存加载和追加失败时保留可见错误', /* 当前回调验证卡密 Hook 的失败路径。 */ async () => {
|
||||||
|
getCardsMock.mockRejectedValueOnce(new Error('库存读取失败'));
|
||||||
|
// dataHook 是库存加载失败场景的 Hook 渲染结果。
|
||||||
|
const dataHook = renderHook(
|
||||||
|
// failedCardsHookFactory 创建库存加载失败场景的 Hook。
|
||||||
|
() => useCardsData(),
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// loadingAssertion 等待库存失败请求收束。
|
||||||
|
() => expect(dataHook.result.current.loading).toBe(false),
|
||||||
|
);
|
||||||
|
expect(dataHook.result.current.cards).toEqual([]);
|
||||||
|
dataHook.unmount();
|
||||||
|
|
||||||
|
appendCardMock.mockRejectedValueOnce(new Error('追加失败'));
|
||||||
|
// batchHook 是追加失败场景的批量操作 Hook 渲染结果。
|
||||||
|
const batchHook = renderHook(
|
||||||
|
// failedBatchHookFactory 创建追加失败场景的批量 Hook。
|
||||||
|
() => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// targetAction 设置追加目标卡密组。
|
||||||
|
() => batchHook.result.current.setAppendTargetId('1'),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// contentAction 写入追加失败测试内容。
|
||||||
|
() => batchHook.result.current.setAppendContent('line-1'),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// failedAppendAction 提交会失败的追加请求。
|
||||||
|
async () => batchHook.result.current.handleBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(batchHook.result.current.appendError).toBe('追加失败');
|
||||||
|
expect(batchHook.result.current.batchBusy).toBe(false);
|
||||||
|
|
||||||
|
batchCreateMock.mockRejectedValueOnce(new Error('创建失败'));
|
||||||
|
await act(
|
||||||
|
// fileAction 写入批量创建失败测试文件。
|
||||||
|
() => batchHook.result.current.setBatchFile(new File(['name'], 'cards.csv')),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// createErrorAction 提交失败的批量创建请求。
|
||||||
|
async () => batchHook.result.current.handleBatchCreate(),
|
||||||
|
);
|
||||||
|
expect(batchHook.result.current.batchResult).toEqual({ error: '创建失败' });
|
||||||
|
|
||||||
|
appendCardMock.mockResolvedValueOnce({ success: true, added: 1 });
|
||||||
|
await act(
|
||||||
|
// appendRetryAction 重试当前卡密追加。
|
||||||
|
async () => batchHook.result.current.handleRetryBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(appendCardMock).toHaveBeenCalledTimes(2);
|
||||||
|
|
||||||
|
await act(
|
||||||
|
// targetSwitchAction 切换追加目标以阻止旧目标重试。
|
||||||
|
() => batchHook.result.current.setAppendTargetId('2'),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// staleRetryAction 验证切换目标后不再提交旧目标请求。
|
||||||
|
async () => batchHook.result.current.handleRetryBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(appendCardMock).toHaveBeenCalledTimes(2);
|
||||||
|
batchHook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('批量创建和追加的前置条件阻止空操作', /* 当前回调验证卡密批量操作的空输入守卫。 */ async () => {
|
||||||
|
// hook 是空库存和空输入守卫场景的批量 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// guardHookFactory 创建批量操作守卫场景的 Hook。
|
||||||
|
() => useCardBatchActions({ dataCards: [], loadCards: loadCardsFixture }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// emptyCreateAction 在没有文件时阻止批量创建。
|
||||||
|
async () => hook.result.current.handleBatchCreate(),
|
||||||
|
);
|
||||||
|
expect(batchCreateMock).not.toHaveBeenCalled();
|
||||||
|
await act(
|
||||||
|
// emptyAppendAction 在没有目标和内容时阻止卡密追加。
|
||||||
|
async () => hook.result.current.handleBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(appendCardMock).not.toHaveBeenCalled();
|
||||||
|
await act(
|
||||||
|
// emptyRetryAction 在没有上次目标时阻止追加重试。
|
||||||
|
async () => hook.result.current.handleRetryBatchAppend(),
|
||||||
|
);
|
||||||
|
expect(appendCardMock).not.toHaveBeenCalled();
|
||||||
|
await act(
|
||||||
|
// openAction 打开空库存批量弹窗并验证目标为空。
|
||||||
|
() => hook.result.current.openBatchModal(),
|
||||||
|
);
|
||||||
|
expect(hook.result.current.appendTargetId).toBe('');
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('库存刷新时丢弃先发出的旧响应', /* 当前回调验证卡密库存请求代次隔离。 */ async () => {
|
||||||
|
// resolveFirst 是旧库存请求的完成控制器。
|
||||||
|
let resolveFirst: (value: Card[]) => void = () => undefined;
|
||||||
|
// firstRequest 是保持未完成的旧库存请求 Promise。
|
||||||
|
const firstRequest = new Promise<Card[]>(/* firstExecutor 保存旧请求完成函数。 */ resolve => { resolveFirst = resolve; });
|
||||||
|
getCardsMock.mockReset();
|
||||||
|
getCardsMock.mockReturnValueOnce(firstRequest);
|
||||||
|
getCardsMock.mockResolvedValueOnce([]);
|
||||||
|
// hook 是库存刷新竞态场景的 Hook 渲染结果。
|
||||||
|
const hook = renderHook(
|
||||||
|
// staleCardsHookFactory 创建库存旧响应场景的 Hook。
|
||||||
|
() => useCardsData(),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// refreshAction 发起第二次库存刷新并使首次请求过期。
|
||||||
|
async () => hook.result.current.loadCards(),
|
||||||
|
);
|
||||||
|
resolveFirst([cardFixture]);
|
||||||
|
await act(
|
||||||
|
// staleResolveAction 完成已过期的首次库存响应。
|
||||||
|
async () => { await firstRequest; },
|
||||||
|
);
|
||||||
|
expect(hook.result.current.cards).toEqual([]);
|
||||||
|
hook.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('批量创建在卸载时取消未完成请求', /* 当前回调验证批量表单卸载后不再允许晚到上传响应更新状态。 */ async () => {
|
||||||
|
// uploadSignal 保存批量创建接口收到的取消信号。
|
||||||
|
let uploadSignal: AbortSignal | undefined;
|
||||||
|
batchCreateMock.mockImplementation(
|
||||||
|
// pendingCreate 保持上传请求未完成,以便验证 Hook 卸载时主动取消。
|
||||||
|
(_file, requestOptions) => {
|
||||||
|
uploadSignal = requestOptions?.signal;
|
||||||
|
return new Promise(/* pendingCreateExecutor 故意不完成上传 Promise,直到 Hook 卸载取消请求。 */ () => undefined);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// hook 是带有上传文件的批量创建 Hook。
|
||||||
|
const hook = renderHook(
|
||||||
|
// batchHookFactory 创建批量操作 Hook。
|
||||||
|
() => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// fileAction 写入将要上传的卡密文件。
|
||||||
|
() => hook.result.current.setBatchFile(new File(['name'], 'cards.csv')),
|
||||||
|
);
|
||||||
|
await act(
|
||||||
|
// createAction 发起尚未完成的上传但不等待其结束。
|
||||||
|
() => { void hook.result.current.handleBatchCreate(); },
|
||||||
|
);
|
||||||
|
await waitFor(
|
||||||
|
// uploadStartedAssertion 等待上传请求拿到取消信号。
|
||||||
|
() => expect(uploadSignal).toBeDefined(),
|
||||||
|
);
|
||||||
|
hook.unmount();
|
||||||
|
expect(uploadSignal?.aborted).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loaded 100 of 929 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user