Files
live-hub-py/web/frontend/src/pages/AccountCheckPage.tsx
T
yml2213 eec42aa8a7 feat(check): 账号检测新增「按账号选择」—— 旧的手动输入与逻辑完整保留
按反馈是**增加**而不是**替换**:旧路径一行未动,新路径另起一条。

## 两套来源并存

| | 手动输入(旧,默认) | 选择账号(新) |
| --- | --- | --- |
| 来源 | 粘贴文本 | 库里账号的凭据(不用人工粘贴) |
| 条目 `account_id` | **无** | 有 |
| 结果落账号时间线 | **否**(保持旧行为) | 是,新事件类型 `account_check` |
| 批次 / 并发 / 重试 / 代理 / 导出 zip | 完全不变 | 完全不变 |

**旧路径的「不发事件」是刻意的**:粘贴进来的账号没有归属,凭空造一条没有账号的
事件只是污染时间线。`parse_account_check_lines`、`export_line`、zip 分组全部未动,
有用例专门钉住这一点。

## 「选择账号」支持筛选(按反馈补充)

不是给一个扁平下拉,而是先按条件缩小范围再决定选法:

- 筛选:**标签 / 生命周期状态 / CK 健康**(复用账号列表同一套 `_filter_accounts_query`,
  两处口径不会不一致)
- 选法:手动多选(选项随筛选刷新)**或**「按筛选全选」(含列表里没显示出来的)

服务端支持 `select_all_matching + 各筛选条件`,与账号列表批量操作的字段形状一致。
可见性沿用账号域口径:客服只能检测自己名下的账号(越权 id 直接 403)。

## 结果表加账号回链

「选择账号」模式下条目带 `account_id`,账号列变成可点链接 → 直接跳到账号详情,
结果也在那里的时间线上。

## 排查中修掉两个 bug(都不是测试发现的)

**① `registry.create` 漏传 `account_id`**
它构造 `AccountCheckItemState` 时没把 `account_id` 从输入复制过去。
后果:批次照跑、结果照显示、zip 照导出,**事件永远不发且没有任何报错**。
是「跑一次真实检测再查事件表」才发现的(查出来 0 条)。已补,并加了用例。

**② 终态判断写成「键存在」而不是「非空」**
`_run_one` 置 `running` 时会显式传 `finished_at=None`,而判断写的是
`"finished_at" in updates` → **中间态也发事件**,于是时间线上记的是
`账号检查:running`;真正的终态再发时撞同一个幂等键被**静默丢弃** ——
结果是「只有一条,但记错了」,比没有更糟。

改成判非空。此处暴露了一个**假绿的用例**:我原来的「中间态不发事件」用例
没传 `finished_at=None`(与真实调用不一致),所以放过了这个 bug;
而且它还缺 `session.commit()`,在 MySQL REPEATABLE READ 下根本看不到
另一个会话刚提交的行 —— 双重假绿。两处都修了,并做了反向验证
(改回旧判断 → 用例立刻红)。

## 验证

- `TZ=Asia/Shanghai`:**520 passed / 6 skipped**(新增 17 条检测模式用例)
- `TZ=UTC`(检测 + 迁移)20 passed;ruff 全绿;前端 build 通过、lint 0 errors
- **真实端到端**:用真实库账号起批次 → 检测跑完(斗鱼返回「账号已认证」)→
  事件确实落库;清掉脏数据后用**与 `_run_one` 完全相同的调用序列**复验:
  两次 `_set_item` 只产生一条事件,且 title 是
  `账号检测:账号已认证`、`status=account_verified`(不再记成 running)

注:验证时真实触发了几次斗鱼登录检测(开发库那两个账号),结果都是「已认证」。
2026-10-04 17:34:58 +08:00

568 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Button, Radio, Select, Card, Col, Input, InputNumber, Popconfirm, Row, Space, Statistic, Switch, Table, Tag, Typography,
} from 'antd';
import { message } from '../utils/antdMessage';
import type { TableProps } from 'antd';
import { DownloadOutlined, PlayCircleOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons';
import { accountApi, accountCheckApi, type AccountCheckBatch, type AccountCheckItem } from '../api/modules';
import { formatTime } from '../utils/time';
import { getErrorMessage } from '../utils/error';
const { TextArea } = Input;
const { Text, Title } = Typography;
const FORM_STORAGE_KEY = 'douyu_account_check_form';
const BATCH_STORAGE_KEY = 'douyu_account_check_batch_id';
const STATUS_LABELS: Record<string, string> = {
pending: '等待',
running: '检测中',
account_cancelled: '账号已注销',
password_wrong: '账号密码错误',
account_unverified: '账号未认证',
account_verified: '账号已认证',
account_auth_unknown: '认证状态未知',
error: '检测失败',
stopped: '已停止',
};
const STATUS_COLORS: Record<string, string> = {
pending: 'default',
running: 'processing',
account_cancelled: 'error',
password_wrong: 'error',
account_unverified: 'warning',
account_verified: 'success',
account_auth_unknown: 'warning',
error: 'error',
stopped: 'warning',
};
const FINISHED_BATCH_STATUS = new Set(['finished', 'stopped', 'error']);
const RUNNING_BATCH_STATUS = new Set(['pending', 'running']);
function readStoredText() {
try {
return localStorage.getItem(FORM_STORAGE_KEY) || '';
} catch {
return '';
}
}
function readStoredBatchId() {
try {
return localStorage.getItem(BATCH_STORAGE_KEY) || '';
} catch {
return '';
}
}
function readStoredNumber(key: string, fallback: number) {
try {
const raw = localStorage.getItem(key);
if (raw === null) return fallback;
const value = Number(raw);
return Number.isFinite(value) ? value : fallback;
} catch {
return fallback;
}
}
function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
function fileTimestamp() {
const d = new Date();
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
}
export default function AccountCheckPage() {
// 两种来源:手动粘贴(旧,默认)与按账号选择(新)。
// 旧模式**完全保留** —— 包括它的解析、批次、导出逻辑。
const [sourceMode, setSourceMode] = useState<'text' | 'accounts'>('text');
const [selectedAccountIds, setSelectedAccountIds] = useState<number[]>([]);
const [accountOptions, setAccountOptions] = useState<{ value: number; label: string }[]>([]);
// 「选择账号」的筛选:与账号列表同一套条件,避免两处口径不一致
const [pickAllMatching, setPickAllMatching] = useState(false);
const [pickTag, setPickTag] = useState('');
const [pickStatus, setPickStatus] = useState('');
const [pickCk, setPickCk] = useState('');
const [tagOptions, setTagOptions] = useState<string[]>([]);
const [text, setText] = useState(readStoredText);
const [concurrency, setConcurrency] = useState(() => readStoredNumber('account_check_concurrency', 3));
const [maxTotalTime, setMaxTotalTime] = useState(() => readStoredNumber('account_check_max_total_time', 300));
const [maxLoginRetries, setMaxLoginRetries] = useState(() => readStoredNumber('account_check_max_login_retries', 0));
const [useProxy, setUseProxy] = useState(() => localStorage.getItem('account_check_use_proxy') === 'true');
const navigate = useNavigate();
const [batch, setBatch] = useState<AccountCheckBatch | null>(null);
const [starting, setStarting] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [stopping, setStopping] = useState(false);
const [downloading, setDownloading] = useState(false);
const restoredBatchRef = useRef(false);
const batchId = batch?.batch_id || '';
const isRunning = !!batch && RUNNING_BATCH_STATUS.has(batch.status);
const canDownload = !!batch && FINISHED_BATCH_STATUS.has(batch.status);
const loadBatchById = useCallback(async (id: string) => {
if (!id) return;
setRefreshing(true);
try {
const data = await accountCheckApi.getBatch(id);
setBatch(data);
localStorage.setItem(BATCH_STORAGE_KEY, data.batch_id);
} catch (e: unknown) {
const err = getErrorMessage(e);
if (err.includes('批次不存在') || err.includes('服务已重启')) {
localStorage.removeItem(BATCH_STORAGE_KEY);
setBatch(null);
message.warning('上次账号检测批次已不存在,已清除恢复记录');
} else {
message.error(err);
}
} finally {
setRefreshing(false);
}
}, []);
const refreshBatch = useCallback(async () => {
if (!batchId) return;
await loadBatchById(batchId);
}, [batchId, loadBatchById]);
useEffect(() => {
localStorage.setItem(FORM_STORAGE_KEY, text);
}, [text]);
useEffect(() => {
localStorage.setItem('account_check_concurrency', String(concurrency));
}, [concurrency]);
useEffect(() => {
localStorage.setItem('account_check_max_total_time', String(maxTotalTime));
}, [maxTotalTime]);
useEffect(() => {
localStorage.setItem('account_check_max_login_retries', String(maxLoginRetries));
}, [maxLoginRetries]);
useEffect(() => {
localStorage.setItem('account_check_use_proxy', String(useProxy));
}, [useProxy]);
useEffect(() => {
if (restoredBatchRef.current) return;
restoredBatchRef.current = true;
const storedBatchId = readStoredBatchId();
if (storedBatchId) {
loadBatchById(storedBatchId);
}
}, [loadBatchById]);
useEffect(() => {
if (!isRunning || !batchId) return undefined;
const timer = window.setInterval(() => {
refreshBatch();
}, 2000);
return () => window.clearInterval(timer);
}, [batchId, isRunning, refreshBatch]);
const statusCounts = useMemo(() => batch?.status_counts || {}, [batch?.status_counts]);
const categoryStats = useMemo(() => [
{ title: '已注销', value: statusCounts.account_cancelled || 0 },
{ title: '密码错误', value: statusCounts.password_wrong || 0 },
{ title: '未认证', value: statusCounts.account_unverified || 0 },
{ title: '已认证', value: statusCounts.account_verified || 0 },
], [statusCounts]);
useEffect(() => {
if (sourceMode !== 'accounts') return;
let alive = true;
void (async () => {
try {
const data = await accountApi.listPaged({
page: 1,
page_size: 200,
search: '',
tag: pickTag || undefined,
status: pickStatus || undefined,
ck_status: pickCk || undefined,
});
if (!alive) return;
setAccountOptions(
data.items.map((item) => ({
value: item.id,
label: `${item.username}(#${item.id})`,
})),
);
} catch (e: unknown) {
message.error(getErrorMessage(e));
}
})();
return () => { alive = false; };
}, [sourceMode, pickTag, pickStatus, pickCk]);
useEffect(() => {
if (sourceMode !== 'accounts' || tagOptions.length > 0) return;
void accountApi
.listTags()
.then(setTagOptions)
.catch(() => {
// 标签拉不到不影响检测,退化为无标签筛选
});
}, [sourceMode, tagOptions.length]);
const handleStart = async () => {
if (sourceMode === 'accounts') {
if (!pickAllMatching && selectedAccountIds.length === 0) {
message.warning('请先选择要检测的账号,或打开「按筛选全选」');
return;
}
} else if (!text.trim()) {
message.warning('请先导入账号');
return;
}
setStarting(true);
try {
const data = await accountCheckApi.start({
// 二选一:账号模式不传 text,文本模式不传 account_ids
text: sourceMode === 'text' ? text : '',
account_ids:
sourceMode === 'accounts' && !pickAllMatching ? selectedAccountIds : [],
select_all_matching: sourceMode === 'accounts' && pickAllMatching,
tag: pickTag,
status: pickStatus,
ck_status: pickCk,
concurrency,
max_total_time: maxTotalTime,
max_login_retries: maxLoginRetries,
use_proxy: useProxy,
});
setBatch(data);
localStorage.setItem(BATCH_STORAGE_KEY, data.batch_id);
message.success(`账号检测批次已启动,共 ${data.total} 个账号`);
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setStarting(false);
}
};
const handleStop = async () => {
if (!batchId) return;
setStopping(true);
try {
const result = await accountCheckApi.stop(batchId);
message.success(result.message);
refreshBatch();
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setStopping(false);
}
};
const handleDownload = async () => {
if (!batchId) return;
setDownloading(true);
try {
const blob = await accountCheckApi.download(batchId);
downloadBlob(blob instanceof Blob ? blob : new Blob([blob]), `account-check-${fileTimestamp()}.zip`);
message.success('已下载压缩包');
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setDownloading(false);
}
};
const columns: TableProps<AccountCheckItem>['columns'] = [
{ title: '行', dataIndex: 'line', width: 70 },
{
title: '账号',
dataIndex: 'username',
width: 180,
ellipsis: true,
// 「按账号选择」模式下条目带 account_id → 回链到账号详情,
// 一眼从检测结果跳到该账号(结果也会在那里的时间线上)。
render: (username: string, record: AccountCheckItem) => (
record.account_id ? (
<Button
type="link"
size="small"
style={{ padding: 0 }}
onClick={() => navigate(`/accounts/${record.account_id}`)}
>
{username}
</Button>
) : username
),
},
{ title: '邮箱', dataIndex: 'email', width: 220, ellipsis: true },
{
title: '状态',
dataIndex: 'status',
width: 130,
render: (status: string) => (
<Tag color={STATUS_COLORS[status] || 'default'}>
{STATUS_LABELS[status] || status}
</Tag>
),
},
{ title: '消息', dataIndex: 'message', ellipsis: true },
{
title: '完成时间',
dataIndex: 'finished_at',
width: 180,
render: (value: string | null) => formatTime(value),
},
];
return (
<Space orientation="vertical" size={16} style={{ width: '100%' }}>
<Title level={3} style={{ margin: 0 }}>账号检测</Title>
<Card title="选择账号来源">
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
{/* 两种来源并存:手动粘贴是旧逻辑,一条没动;
按账号选择是新增的,凭据从库里取、结果写回账号时间线。 */}
<Radio.Group
value={sourceMode}
onChange={(event) => setSourceMode(event.target.value)}
disabled={isRunning}
optionType="button"
buttonStyle="solid"
options={[
{ value: 'text', label: '手动输入' },
{ value: 'accounts', label: '选择账号' },
]}
/>
{sourceMode === 'text' ? (
<TextArea
rows={9}
value={text}
onChange={(event) => setText(event.target.value)}
placeholder={'用户3751569049----19910724----eRRWGm@nnw.pw----aa778899\n用户1508769674|aa778899|CBXFbx@nnw.pw|aa778899'}
disabled={isRunning}
/>
) : (
<Space orientation="vertical" size={8} style={{ width: '100%' }}>
{/* 先按条件缩小范围,再决定「全选」还是「挑几个」——
与账号列表同一套筛选条件(标签/状态/CK)。 */}
<Space wrap size={8}>
<Select
allowClear
size="small"
style={{ width: 150 }}
placeholder="按标签筛选"
value={pickTag || undefined}
onChange={(v) => { setPickTag(v || ''); setSelectedAccountIds([]); }}
options={tagOptions.map((v) => ({ value: v, label: v }))}
disabled={isRunning}
/>
<Select
allowClear
size="small"
style={{ width: 130 }}
placeholder="按状态筛选"
value={pickStatus || undefined}
onChange={(v) => { setPickStatus(v || ''); setSelectedAccountIds([]); }}
options={[
{ value: 'active', label: '正常' },
{ value: 'invalid', label: 'CK 失效' },
{ value: 'manual', label: '待人工' },
{ value: 'imported', label: '未登录' },
{ value: 'disabled', label: '已停用' },
]}
disabled={isRunning}
/>
<Select
allowClear
size="small"
style={{ width: 120 }}
placeholder="按 CK 筛选"
value={pickCk || undefined}
onChange={(v) => { setPickCk(v || ''); setSelectedAccountIds([]); }}
options={[
{ value: 'invalid', label: 'CK 失效' },
{ value: 'valid', label: 'CK 正常' },
{ value: 'error', label: '检测异常' },
]}
disabled={isRunning}
/>
<Space size={4}>
<Switch
size="small"
checked={pickAllMatching}
onChange={setPickAllMatching}
disabled={isRunning}
/>
<Text>按筛选全选</Text>
</Space>
</Space>
{pickAllMatching ? (
<Text type="secondary">
将检测当前筛选条件下的全部账号(含列表里没显示出来的)。
</Text>
) : (
<Select
mode="multiple"
allowClear
showSearch
optionFilterProp="label"
style={{ width: '100%' }}
placeholder={
accountOptions.length
? `从筛选结果里选择(共 ${accountOptions.length} 个可挑)`
: '当前筛选下没有账号'
}
value={selectedAccountIds}
onChange={setSelectedAccountIds}
options={accountOptions}
disabled={isRunning}
maxTagCount="responsive"
/>
)}
<Text type="secondary">
凭据从账号库里取,结果会写进该账号的时间线;手动输入的账号没有归属,
结果只在批次与导出 zip 里(与以前一致)。
</Text>
</Space>
)}
<Row gutter={[12, 12]} align="bottom">
<Col xs={8} md={4}>
<Text type="secondary">并发</Text>
<InputNumber
min={1}
max={10}
value={concurrency}
onChange={(value) => setConcurrency(Number(value || 1))}
disabled={isRunning}
style={{ width: '100%' }}
/>
</Col>
<Col xs={8} md={4}>
<Text type="secondary">单账号超时</Text>
<Space.Compact style={{ width: '100%' }}>
<InputNumber
min={0}
max={3600}
step={30}
value={maxTotalTime}
onChange={(value) => setMaxTotalTime(Number(value ?? 0))}
disabled={isRunning}
style={{ width: '100%' }}
/>
<Button disabled>秒</Button>
</Space.Compact>
</Col>
<Col xs={8} md={4}>
<Text type="secondary">重试次数</Text>
<Space.Compact style={{ width: '100%' }}>
<InputNumber
min={0}
max={50}
value={maxLoginRetries}
onChange={(value) => setMaxLoginRetries(Number(value ?? 0))}
disabled={isRunning}
style={{ width: '100%' }}
/>
<Button disabled>次</Button>
</Space.Compact>
</Col>
<Col xs={12} md={4}>
<Text type="secondary">代理</Text>
<div style={{ height: 32, display: 'flex', alignItems: 'center' }}>
<Switch
checked={useProxy}
checkedChildren="开"
unCheckedChildren="关"
onChange={setUseProxy}
disabled={isRunning}
/>
</div>
</Col>
<Col xs={24} md={8}>
<Space wrap>
<Button
type="primary"
icon={<PlayCircleOutlined />}
loading={starting}
disabled={isRunning}
onClick={handleStart}
>
开始检测
</Button>
<Button
danger
icon={<StopOutlined />}
loading={stopping}
disabled={!isRunning}
onClick={handleStop}
>
停止
</Button>
<Popconfirm
title="清空导入内容?"
onConfirm={() => setText('')}
disabled={isRunning || !text}
okText="清空"
cancelText="取消"
>
<Button disabled={isRunning || !text}>清空</Button>
</Popconfirm>
</Space>
</Col>
</Row>
</Space>
</Card>
<Card
title="检测结果"
extra={(
<Space>
<Button icon={<ReloadOutlined />} loading={refreshing} disabled={!batchId} onClick={refreshBatch}>
刷新
</Button>
<Button icon={<DownloadOutlined />} loading={downloading} disabled={!canDownload} onClick={handleDownload}>
下载压缩包
</Button>
</Space>
)}
>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={12} md={4}><Statistic title="总数" value={batch?.total || 0} /></Col>
<Col xs={12} md={4}><Statistic title="完成" value={batch?.finished_count || 0} /></Col>
<Col xs={12} md={4}><Statistic title="运行中" value={batch?.running_count || 0} /></Col>
<Col xs={12} md={4}><Statistic title="失败" value={statusCounts.error || 0} /></Col>
<Col xs={12} md={4}><Statistic title="状态" value={batch ? batch.message : '-'} /></Col>
<Col xs={12} md={4}><Statistic title="批次" value={batchId || '-'} /></Col>
{categoryStats.map((item) => (
<Col xs={12} md={4} key={item.title}>
<Statistic title={item.title} value={item.value} />
</Col>
))}
</Row>
<Table
rowKey="line"
columns={columns}
dataSource={batch?.items || []}
loading={refreshing && !isRunning}
pagination={{ pageSize: 20, showSizeChanger: true }}
scroll={{ x: 920 }}
/>
</Card>
</Space>
);
}