S1 加好了列,本提交把**读与写一起切**过去。这是设计里「同一份数据的读与写必须
在同一个提交里切」的要求:先切读或先切写都会出现「写账号、读记录」的中间态,
跑起来不报错,只是默默用错数据。
## 核心改动
**判定「谁有 CK」不再借道登录记录**
- `cookie_holding_filter()` / `cookie_operable_filter()` / `cookie_holding_account_ids_query()`
/ `visible_douyu_task_accounts()` 全部改为作用于 `Account`;
- `cookie_operable_filter()` 的「在途排除」仍查 `login_tasks`(那是**某次尝试**的属性),
用 `NOT EXISTS` 子查询 + 迁移 0042 新增的 `(account_id, attempt_status)` 索引;
- 删除死代码 `latest_cookie_login_task()`;`latest_cookie()` 改为直接读账号。
**CK 写入**
- `_write_login_success()` 写 `Account.cookie / cookie_updated_at / cookie_source`;
- `_mark_attempt_failed()` 改看**账号**有没有 CK(决定是否沿用旧的失败语义);
- 检测模式的 `task.cookie = ""` **不再清空账号的 CK**(见下「行为变更」)。
**自动化作业按账号调度**
- `ck_health`:`_select_tasks` → `_select_accounts`,`db.query(Account)`;新增
`count_remaining()`(刻意不带 LIMIT,否则积压数恒等于批次上限);
- `ck_relogin`:同样按账号选行;结算改为「账号 + 本轮尝试记录」,
退避进度写账号;`settle_fresh_results(batch_id)` 按 `attempt_batch_id` 配对,
`run_ck_relogin` 把 **account_ids** 交给 runner;
- 顺带让**没有任何登录历史的账号**也能被巡检/重登(以前它们永远进不了队列)。
**登录批次**
- `LoginBatchRunner` 去掉 `relogin_task_ids`,重登与登录统一走 `account_ids`;
- 批次行复用逻辑重写:只保证「同一账号不并发两行」,不再关心「哪一行持有 CK」。
失败行复用同时看 `attempt_status`(账号有 CK 时 `_mark_attempt_failed` 刻意不动
`status`,只看 status 会永远命不中 → 每次失败刷一行)。
**删除护栏语义变更(用户可感知)**
- 去掉「持有 CK 的记录不可删」——CK 在账号上,删历史不再影响登录态,历史终于可清理;
- **保留**「在途尝试不可删」(批次线程正拿着那条记录)。
## 行为变更(需评审)
1. **账号检测不再清空 CK**。旧代码在 check 模式写 `task.cookie = ""`,而那时记录的
cookie 就是账号唯一凭证 —— 一次「批量检测」会把账号登录态删掉。解耦后
「检测账号凭据」与「CK 是否有效」本就是两件事(后者归 `ck_health` 判),
继续清空等于凭空制造不可逆的数据丢失(重登当前成功率极低)。
2. **Cookie 页的记录单位从「登录记录」变成「账号」**,所有接口的 id 入参/出参
变成 `account_id`;`DELETE /cookies/{id}` 清的是该账号的 CK,**必写审计**。
3. 重复检测从「同一账号多行持 CK」改为「**同一个 CK 出现在多个账号上**」——
后者才是真风险(两个账号共用一个登录态)。用 sha256 指纹分组:
CK 是 AES-GCM + 随机 nonce 加密,**同一明文每次密文都不同**,比密文永远比不出重复。
## 修掉一个真实并发缺陷
`_write_login_success` 原先被传入 `self.db`(runner 主会话),而它是在**工作线程**里
用 `worker_db` 执行的。`emit()` 会往 `account_events` 插一行,其 `account_id` 外键对
`accounts` 那一行加**共享锁**;这把锁加在另一个会话上,紧接着本会话的
`UPDATE accounts SET cookie=...` 就被自己人挡住 —— 实测 **50 秒后
`Lock wait timeout exceeded`,登录明明成功却写不回 CK**(改造前 UPDATE 打在
`login_tasks` 上所以没撞上)。改为传 `worker_db`:事件本就该和状态变更同事务提交,
顺带修掉跨线程共用一个 Session 的隐患。
## 验证
- 全量 pytest **368 passed / 6 skipped**;迁移链 3 passed;
- 前端 `tsc -b && vite build` 通过;
- `ruff check` / `ruff format --check` 全绿(顺带修掉 main 上遗留的 F821);
- 新增/改写的关键回归:**删掉全部登录历史后账号的 CK 与健康状态仍在**、
**无登录历史的账号也能进巡检队列**、结算不碰 CK、删除护栏改为在途语义。
仍未做(设计里排期的后续阶段):`account_lifecycle` 状态收口(S3)、事件发射点补齐(S4)、
业务事实直发事件(S5)、账号页重构(S6)。注意 `status` 目前只有模型默认值与迁移回填,
所以 `disabled/archived` 还没有任何写入方——S3 落地时要把自动化选行的状态过滤一起补上。
733 lines
25 KiB
TypeScript
733 lines
25 KiB
TypeScript
import { useEffect, useState, useCallback } from 'react';
|
||
import { Table, Button, Card, Row, Col, Statistic, Tag, Popconfirm, Space, Typography, Input, Select, theme, Dropdown, Tooltip, Modal, Alert, Empty } from 'antd';
|
||
import { message } from '../utils/antdMessage';
|
||
import { DownloadOutlined, DeleteOutlined, CopyOutlined, SearchOutlined, LoadingOutlined, ReloadOutlined, FilterOutlined, ScanOutlined } from '@ant-design/icons';
|
||
import { accountApi, cookieApi, type BasicSummary, type CookieCheckResult, type CookieDuplicateGroup, type CookieDuplicateResponse, type CookieItem } from '../api/modules';
|
||
import { usePermissions } from '../hooks/usePermissions';
|
||
import { formatTime } from '../utils/time';
|
||
import { getErrorMessage } from '../utils/error';
|
||
|
||
const { Text } = Typography;
|
||
|
||
/** 复制文本到剪贴板,兼容非安全上下文(http://非localhost) */
|
||
function copyToClipboard(text: string): Promise<void> {
|
||
if (navigator.clipboard?.writeText) {
|
||
return navigator.clipboard.writeText(text);
|
||
}
|
||
// fallback:利用 textarea + execCommand,兼容 http 远程访问
|
||
return new Promise((resolve, reject) => {
|
||
const ta = document.createElement('textarea');
|
||
ta.value = text;
|
||
ta.style.position = 'fixed';
|
||
ta.style.left = '-9999px';
|
||
document.body.appendChild(ta);
|
||
ta.select();
|
||
try {
|
||
const ok = document.execCommand('copy');
|
||
document.body.removeChild(ta);
|
||
if (ok) {
|
||
resolve();
|
||
} else {
|
||
reject(new Error('execCommand copy failed'));
|
||
}
|
||
} catch (e) {
|
||
document.body.removeChild(ta);
|
||
reject(e);
|
||
}
|
||
});
|
||
}
|
||
|
||
function parseAccountNames(text: string): string[] {
|
||
const seen = new Set<string>();
|
||
return text
|
||
.replace(/\r\n/g, '\n')
|
||
.replace(/\r/g, '\n')
|
||
.split('\n')
|
||
.map((name) => name.trim())
|
||
.filter((name) => name.length > 0 && !seen.has(name) && seen.add(name));
|
||
}
|
||
|
||
export default function CookiePage() {
|
||
const { token } = theme.useToken();
|
||
const [cookies, setCookies] = useState<CookieItem[]>([]);
|
||
const [loading, setLoading] = useState(false);
|
||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||
const [searchText, setSearchText] = useState('');
|
||
const [tagFilter, setTagFilter] = useState('');
|
||
const [tags, setTags] = useState<string[]>([]);
|
||
const [customNamesText, setCustomNamesText] = useState('');
|
||
const [customAccountNames, setCustomAccountNames] = useState<string[]>([]);
|
||
const [total, setTotal] = useState(0);
|
||
const [summary, setSummary] = useState<BasicSummary>({ total: 0, assigned_count: 0, unassigned_count: 0 });
|
||
const [pageSize, setPageSize] = useState(() => {
|
||
const v = localStorage.getItem('cookie_page_size');
|
||
return v ? Number(v) || 20 : 20;
|
||
});
|
||
const [currentPage, setCurrentPage] = useState(1);
|
||
const [checkingIds, setCheckingIds] = useState<Set<number>>(new Set());
|
||
const [checkResults, setCheckResults] = useState<Map<number, CookieCheckResult>>(new Map());
|
||
const [reloginIds, setReloginIds] = useState<Set<number>>(new Set());
|
||
const [duplicateOpen, setDuplicateOpen] = useState(false);
|
||
const [duplicateLoading, setDuplicateLoading] = useState(false);
|
||
const [duplicateResult, setDuplicateResult] = useState<CookieDuplicateResponse | null>(null);
|
||
const { can } = usePermissions();
|
||
|
||
const canView = can('cookie:view');
|
||
const canExport = can('cookie:export');
|
||
const canRelogin = can('login:batch');
|
||
|
||
const pollRelogin = (batchId: string, count: number) => {
|
||
let attempts = 0;
|
||
const timer = window.setInterval(async () => {
|
||
attempts += 1;
|
||
try {
|
||
const tasks = await cookieApi.loginTasks(batchId);
|
||
const done = tasks.every((t) => !['pending', 'running'].includes(t.status));
|
||
if (done) {
|
||
window.clearInterval(timer);
|
||
message.success(`重新登录完成: ${tasks.filter((t) => t.status === 'success').length}/${tasks.length} 个成功`);
|
||
loadCookies();
|
||
loadSummary();
|
||
} else if (attempts > 120) {
|
||
window.clearInterval(timer);
|
||
message.warning('重新登录超时,请到登录任务页查看进度');
|
||
}
|
||
} catch {
|
||
window.clearInterval(timer);
|
||
message.warning('查询重登进度失败,请稍后手动刷新');
|
||
}
|
||
}, 3000);
|
||
void count;
|
||
};
|
||
|
||
const handleRelogin = async (ids: number[]) => {
|
||
if (ids.length === 0) return;
|
||
setReloginIds((prev) => new Set([...prev, ...ids]));
|
||
try {
|
||
const res = await cookieApi.relogin(ids);
|
||
const tip = res.skipped > 0 ? `,${res.skipped} 条因账号缺少登录凭据被跳过` : '';
|
||
message.success(`已开始重新登录 ${res.count} 个账号${tip}`);
|
||
pollRelogin(res.batch_id, res.count);
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
} finally {
|
||
setReloginIds((prev) => {
|
||
const next = new Set(prev);
|
||
for (const id of ids) next.delete(id);
|
||
return next;
|
||
});
|
||
}
|
||
};
|
||
|
||
const handleReloginSelected = () => {
|
||
const ids = selectedRowKeys.map((k) => Number(k));
|
||
if (ids.length === 0) {
|
||
message.warning('请先选择要重新登录的 Cookie');
|
||
return;
|
||
}
|
||
void handleRelogin(ids);
|
||
};
|
||
|
||
const handleCheck = async (ids: number[]) => {
|
||
if (ids.length === 0) return;
|
||
setCheckingIds((prev) => new Set([...prev, ...ids]));
|
||
try {
|
||
const res = await cookieApi.check(ids);
|
||
const map = new Map(checkResults);
|
||
for (const item of res.results) map.set(item.id, item);
|
||
setCheckResults(map);
|
||
const validCount = res.results.filter((item) => item.valid).length;
|
||
message.success(`检测完成: ${validCount}/${res.results.length} 条有效`);
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
} finally {
|
||
setCheckingIds((prev) => {
|
||
const next = new Set(prev);
|
||
for (const id of ids) next.delete(id);
|
||
return next;
|
||
});
|
||
}
|
||
};
|
||
|
||
const handleCheckSelected = () => {
|
||
const ids = selectedRowKeys.map((k) => Number(k));
|
||
if (ids.length === 0) {
|
||
message.warning('请先选择要检测的 Cookie');
|
||
return;
|
||
}
|
||
void handleCheck(ids);
|
||
};
|
||
|
||
const handleDuplicateCheck = async () => {
|
||
setDuplicateOpen(true);
|
||
setDuplicateLoading(true);
|
||
try {
|
||
const result = await cookieApi.duplicates();
|
||
setDuplicateResult(result);
|
||
if (result.duplicate_groups > 0) {
|
||
message.warning(`发现 ${result.duplicate_groups} 组「多个账号共用同一份 CK」,涉及 ${result.duplicate_rows} 个账号`);
|
||
} else {
|
||
message.success('未发现共用 CK 的账号');
|
||
}
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
} finally {
|
||
setDuplicateLoading(false);
|
||
}
|
||
};
|
||
|
||
const loadCookies = useCallback(async () => {
|
||
setLoading(true);
|
||
try {
|
||
const data = await cookieApi.listPaged({
|
||
page: currentPage,
|
||
page_size: pageSize,
|
||
search: searchText.trim() || undefined,
|
||
tag: tagFilter || undefined,
|
||
account_names: customAccountNames.length > 0 ? customAccountNames.join('\n') : undefined,
|
||
include_cookie: false,
|
||
});
|
||
setCookies(data.items);
|
||
setTotal(data.total);
|
||
// 合并已持久化的检测结果(刷新后仍保留)
|
||
setCheckResults((prev) => {
|
||
const next = new Map(prev);
|
||
for (const item of data.items) {
|
||
if (!item.ck_check_status) continue;
|
||
next.set(item.id, {
|
||
id: item.id,
|
||
valid: item.ck_check_status === 'valid',
|
||
message: item.ck_check_result?.message ?? '',
|
||
fish_ball: item.ck_check_result?.fish_ball ?? null,
|
||
nickname: item.ck_check_result?.nickname ?? null,
|
||
level: item.ck_check_result?.level ?? null,
|
||
checked_at: item.ck_checked_at ?? '',
|
||
});
|
||
}
|
||
return next;
|
||
});
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [currentPage, pageSize, searchText, tagFilter, customAccountNames]);
|
||
|
||
const loadSummary = useCallback(async () => {
|
||
try {
|
||
const data = await cookieApi.summary();
|
||
setSummary(data);
|
||
} catch {
|
||
// 统计加载失败不影响列表操作。
|
||
}
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
loadCookies();
|
||
}, [loadCookies]);
|
||
|
||
useEffect(() => {
|
||
loadSummary();
|
||
}, [loadSummary]);
|
||
|
||
useEffect(() => {
|
||
accountApi.listTags().then(setTags).catch(() => {
|
||
// 标签加载失败不影响 Cookie 管理。
|
||
});
|
||
}, []);
|
||
|
||
const handleExport = async (format: string = 'csv') => {
|
||
try {
|
||
const blob = await cookieApi.exportCsv(
|
||
format,
|
||
customAccountNames.length > 0 ? customAccountNames.join('\n') : undefined,
|
||
);
|
||
const url = URL.createObjectURL(blob instanceof Blob ? blob : new Blob([blob]));
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = format === 'custom' ? 'cookies_custom.txt' : 'cookies.csv';
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
message.success(customAccountNames.length > 0 ? '已导出匹配的 Cookie' : '已导出');
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
}
|
||
};
|
||
|
||
const handleApplyCustomFilter = () => {
|
||
const names = parseAccountNames(customNamesText);
|
||
if (names.length === 0) {
|
||
message.warning('请先粘贴斗鱼账户名,每行一个');
|
||
return;
|
||
}
|
||
setCustomAccountNames(names);
|
||
setSelectedRowKeys([]);
|
||
setCurrentPage(1);
|
||
message.success(`已载入 ${names.length} 个账户名,正在筛选 Cookie`);
|
||
};
|
||
|
||
const handleClearCustomFilter = () => {
|
||
setCustomNamesText('');
|
||
setCustomAccountNames([]);
|
||
setSelectedRowKeys([]);
|
||
setCurrentPage(1);
|
||
};
|
||
|
||
const handleCopyCustomCookies = async () => {
|
||
if (customAccountNames.length === 0) {
|
||
message.warning('请先筛选自定义账户名');
|
||
return;
|
||
}
|
||
try {
|
||
const blob = await cookieApi.exportCsv('custom', customAccountNames.join('\n'));
|
||
const text = blob instanceof Blob ? await blob.text() : String(blob);
|
||
if (!text.trim()) {
|
||
message.warning('没有找到对应的 Cookie');
|
||
return;
|
||
}
|
||
await copyToClipboard(text);
|
||
message.success(`已复制 ${total} 条匹配的自定义 CK`);
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e) || '复制失败');
|
||
}
|
||
};
|
||
|
||
const handleCopyCookie = async (record: CookieItem) => {
|
||
try {
|
||
const detail = await cookieApi.get(record.id);
|
||
if (!detail.cookie) {
|
||
message.warning('Cookie 为空');
|
||
return;
|
||
}
|
||
const text = `${detail.account_username}----${detail.account_password || ''}----${detail.cookie}`;
|
||
await copyToClipboard(text);
|
||
message.success(`已复制 ${detail.account_username} 的 Cookie`);
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e) || '复制失败');
|
||
}
|
||
};
|
||
|
||
const handleCopySelected = async () => {
|
||
if (selectedRowKeys.length === 0) {
|
||
message.warning('请先选择 Cookie');
|
||
return;
|
||
}
|
||
try {
|
||
const selected = await Promise.all(selectedRowKeys.map((key) => cookieApi.get(Number(key))));
|
||
const text = selected
|
||
.map((c) => `${c.account_username}----${c.account_password || ''}----${c.cookie || ''}`)
|
||
.join('\r\n');
|
||
await copyToClipboard(text);
|
||
message.success(`已复制 ${selected.length} 条 Cookie`);
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e) || '复制失败');
|
||
}
|
||
};
|
||
|
||
const handleDelete = async (id: number) => {
|
||
try {
|
||
await cookieApi.delete(id);
|
||
message.success('已清除该账号的 CK');
|
||
setSelectedRowKeys((prev) => prev.filter((k) => k !== id));
|
||
loadCookies();
|
||
loadSummary();
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
}
|
||
};
|
||
|
||
const handleDeleteSelected = async () => {
|
||
if (selectedRowKeys.length === 0) {
|
||
message.warning('请先选择要清除 CK 的账号');
|
||
return;
|
||
}
|
||
try {
|
||
const ids = selectedRowKeys.map((k) => Number(k));
|
||
const res = await cookieApi.deleteBatch(ids);
|
||
message.success(res.message);
|
||
setSelectedRowKeys([]);
|
||
loadCookies();
|
||
loadSummary();
|
||
} catch (e: unknown) {
|
||
message.error(getErrorMessage(e));
|
||
}
|
||
};
|
||
|
||
const columns = [
|
||
{ title: 'ID', dataIndex: 'id', width: 60, align: 'center' as const },
|
||
{
|
||
title: '账号',
|
||
dataIndex: 'account_username',
|
||
width: 140,
|
||
ellipsis: true,
|
||
},
|
||
{
|
||
title: '分配',
|
||
dataIndex: 'assigned_username',
|
||
width: 100,
|
||
align: 'center' as const,
|
||
render: (name: string | null) =>
|
||
name ? <Tag color="green">{name}</Tag> : <Text type="secondary" style={{ fontSize: 12 }}>未分配</Text>,
|
||
},
|
||
{
|
||
title: 'Cookie',
|
||
dataIndex: 'cookie_preview',
|
||
width: 300,
|
||
ellipsis: true,
|
||
render: (val: string) => {
|
||
if (!canView) return <Tag>***</Tag>;
|
||
return <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{val}</span>;
|
||
},
|
||
},
|
||
{
|
||
title: '有效性',
|
||
width: 90,
|
||
align: 'center' as const,
|
||
render: (_: unknown, record: CookieItem) => {
|
||
if (checkingIds.has(record.id)) {
|
||
return <Tag color="processing" icon={<LoadingOutlined />}>检测中...</Tag>;
|
||
}
|
||
const result = checkResults.get(record.id);
|
||
if (!result) return <Text type="secondary" style={{ fontSize: 12 }}>未检测</Text>;
|
||
const detail = [
|
||
result.fish_ball != null ? `鱼丸: ${result.fish_ball}` : '',
|
||
result.nickname ? `昵称: ${result.nickname}${result.level != null ? ` (Lv.${result.level})` : ''}` : '',
|
||
result.message && !result.valid ? result.message : '',
|
||
].filter(Boolean).join(' | ');
|
||
const tag = result.valid
|
||
? <Tag color="success">有效</Tag>
|
||
: <Tag color="error">无效</Tag>;
|
||
return detail
|
||
? <Tooltip title={detail}>{tag}</Tooltip>
|
||
: tag;
|
||
},
|
||
},
|
||
{
|
||
title: '检测时间',
|
||
width: 170,
|
||
align: 'center' as const,
|
||
render: (_: unknown, record: CookieItem) => {
|
||
const checkedAt = checkResults.get(record.id)?.checked_at || record.ck_checked_at;
|
||
return checkedAt
|
||
? <Text type="secondary" style={{ fontSize: 12 }}>{formatTime(checkedAt)}</Text>
|
||
: <Text type="secondary" style={{ fontSize: 12 }}>-</Text>;
|
||
},
|
||
},
|
||
{
|
||
title: '时间',
|
||
dataIndex: 'created_at',
|
||
width: 180,
|
||
align: 'center' as const,
|
||
render: (val: string) => formatTime(val),
|
||
},
|
||
{
|
||
title: '操作',
|
||
width: 190,
|
||
align: 'center' as const,
|
||
fixed: 'right' as const,
|
||
render: (_: unknown, record: CookieItem) => (
|
||
<Space size={4}>
|
||
<Button
|
||
size="small"
|
||
icon={<CopyOutlined />}
|
||
onClick={() => handleCopyCookie(record)}
|
||
>
|
||
复制
|
||
</Button>
|
||
{canView && (
|
||
<Button
|
||
size="small"
|
||
icon={checkingIds.has(record.id) ? <LoadingOutlined /> : undefined}
|
||
loading={checkingIds.has(record.id)}
|
||
disabled={checkingIds.has(record.id)}
|
||
onClick={() => handleCheck([record.id])}
|
||
>
|
||
检测
|
||
</Button>
|
||
)}
|
||
{canRelogin && (
|
||
<Popconfirm
|
||
title="用账号信息重新登录并替换失效 Cookie?"
|
||
onConfirm={() => handleRelogin([record.id])}
|
||
>
|
||
<Button
|
||
size="small"
|
||
icon={<ReloadOutlined />}
|
||
loading={reloginIds.has(record.id)}
|
||
disabled={reloginIds.has(record.id)}
|
||
>
|
||
重登
|
||
</Button>
|
||
</Popconfirm>
|
||
)}
|
||
{canExport && (
|
||
<Popconfirm title="确认清除该账号的 CK?不可逆" onConfirm={() => handleDelete(record.id)}>
|
||
<Button danger size="small" icon={<DeleteOutlined />} />
|
||
</Popconfirm>
|
||
)}
|
||
</Space>
|
||
),
|
||
},
|
||
];
|
||
|
||
const duplicateColumns = [
|
||
{
|
||
title: '账号',
|
||
dataIndex: 'account_names',
|
||
width: 180,
|
||
ellipsis: true,
|
||
render: (names: string[]) => names.join(' / '),
|
||
},
|
||
{
|
||
title: 'CK 条数',
|
||
dataIndex: 'cookie_count',
|
||
width: 90,
|
||
align: 'center' as const,
|
||
render: (count: number) => <Tag color="error">{count}</Tag>,
|
||
},
|
||
{
|
||
title: '共用 CK 的账号数',
|
||
dataIndex: 'account_count',
|
||
width: 110,
|
||
align: 'center' as const,
|
||
},
|
||
{
|
||
title: '账号 ID(共用同一份 CK)',
|
||
dataIndex: 'cookie_ids',
|
||
width: 220,
|
||
ellipsis: true,
|
||
render: (ids: number[]) => ids.join(', '),
|
||
},
|
||
{
|
||
title: '账号 ID',
|
||
dataIndex: 'account_ids',
|
||
width: 130,
|
||
ellipsis: true,
|
||
render: (ids: number[]) => ids.join(', '),
|
||
},
|
||
{
|
||
title: '最近拿到 CK',
|
||
width: 170,
|
||
align: 'center' as const,
|
||
render: (_: unknown, group: CookieDuplicateGroup) => formatTime(group.records[0]?.finished_at),
|
||
},
|
||
];
|
||
|
||
return (
|
||
<div>
|
||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||
<h2 style={{ margin: 0 }}>Cookie 管理</h2>
|
||
<Space>
|
||
{canView && (
|
||
<Button
|
||
icon={<ScanOutlined />}
|
||
loading={duplicateLoading}
|
||
onClick={handleDuplicateCheck}
|
||
>
|
||
检测重复
|
||
</Button>
|
||
)}
|
||
<Button
|
||
icon={<CopyOutlined />}
|
||
onClick={handleCopySelected}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
复制选中 {selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
|
||
</Button>
|
||
{canView && (
|
||
<Button
|
||
icon={<LoadingOutlined />}
|
||
onClick={handleCheckSelected}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
检测选中 {selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
|
||
</Button>
|
||
)}
|
||
{canRelogin && (
|
||
<Popconfirm
|
||
title={`确认重新登录选中的 ${selectedRowKeys.length} 条 Cookie?将用账号信息重新登录并替换`}
|
||
onConfirm={handleReloginSelected}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
<Button
|
||
icon={<ReloadOutlined />}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
重登选中 {selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
|
||
</Button>
|
||
</Popconfirm>
|
||
)}
|
||
{canExport && (
|
||
<Popconfirm
|
||
title={`确认清除选中的 ${selectedRowKeys.length} 个账号的 CK?不可逆`}
|
||
onConfirm={handleDeleteSelected}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
<Button
|
||
danger
|
||
icon={<DeleteOutlined />}
|
||
disabled={selectedRowKeys.length === 0}
|
||
>
|
||
清除选中 {selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
|
||
</Button>
|
||
</Popconfirm>
|
||
)}
|
||
{canExport && (
|
||
<Dropdown
|
||
menu={{
|
||
items: [
|
||
{ key: 'csv', label: 'CSV(账号, Cookie, 时间)', onClick: () => handleExport('csv') },
|
||
{ key: 'custom', label: '自定义(账号----密码----ck)', onClick: () => handleExport('custom') },
|
||
],
|
||
}}
|
||
>
|
||
<Button type="primary" icon={<DownloadOutlined />}>
|
||
导出
|
||
</Button>
|
||
</Dropdown>
|
||
)}
|
||
</Space>
|
||
</div>
|
||
<Row gutter={12} style={{ marginBottom: 16 }}>
|
||
<Col span={6}>
|
||
<Card size="small"><Statistic title="Cookie 总数" value={summary.total} /></Card>
|
||
</Col>
|
||
<Col span={6}>
|
||
<Card size="small">
|
||
<Statistic
|
||
title="已分配"
|
||
value={summary.assigned_count}
|
||
styles={{ content: { color: token.colorSuccess } }}
|
||
/>
|
||
</Card>
|
||
</Col>
|
||
<Col span={6}>
|
||
<Card size="small">
|
||
<Statistic
|
||
title="未分配"
|
||
value={summary.unassigned_count}
|
||
styles={{ content: { color: token.colorError } }}
|
||
/>
|
||
</Card>
|
||
</Col>
|
||
</Row>
|
||
<Card size="small" title="获取自定义 CK" style={{ marginBottom: 16 }}>
|
||
<Space direction="vertical" style={{ width: '100%' }} size={8}>
|
||
<Input.TextArea
|
||
value={customNamesText}
|
||
onChange={(e) => setCustomNamesText(e.target.value)}
|
||
placeholder="从 Excel 复制斗鱼账户名后粘贴到这里,每行一个"
|
||
autoSize={{ minRows: 3, maxRows: 7 }}
|
||
/>
|
||
<Space wrap>
|
||
<Button type="primary" icon={<FilterOutlined />} onClick={handleApplyCustomFilter}>
|
||
筛选自定义 CK
|
||
</Button>
|
||
<Button icon={<CopyOutlined />} onClick={handleCopyCustomCookies} disabled={customAccountNames.length === 0}>
|
||
复制匹配 CK
|
||
</Button>
|
||
<Button onClick={handleClearCustomFilter} disabled={!customNamesText && customAccountNames.length === 0}>
|
||
清空
|
||
</Button>
|
||
{customAccountNames.length > 0 && (
|
||
<Text type="secondary">已载入 {customAccountNames.length} 个账户名,匹配结果共 {total} 条</Text>
|
||
)}
|
||
</Space>
|
||
</Space>
|
||
</Card>
|
||
<Space wrap style={{ marginBottom: 12 }}>
|
||
<Select
|
||
allowClear
|
||
showSearch
|
||
placeholder="按标签筛选"
|
||
style={{ width: 160 }}
|
||
value={tagFilter || undefined}
|
||
onChange={(value) => {
|
||
setTagFilter(value || '');
|
||
setCurrentPage(1);
|
||
setSelectedRowKeys([]);
|
||
}}
|
||
options={tags.map((tag) => ({ value: tag, label: tag }))}
|
||
/>
|
||
<Input.Search
|
||
placeholder="搜索账号、标签或分配客服"
|
||
allowClear
|
||
value={searchText}
|
||
onChange={(e) => {
|
||
setSearchText(e.target.value);
|
||
setCurrentPage(1);
|
||
}}
|
||
style={{ width: 260 }}
|
||
size="small"
|
||
prefix={<SearchOutlined />}
|
||
/>
|
||
</Space>
|
||
<Table
|
||
rowSelection={{
|
||
selectedRowKeys,
|
||
onChange: (keys) => setSelectedRowKeys(keys),
|
||
preserveSelectedRowKeys: true,
|
||
}}
|
||
columns={columns}
|
||
dataSource={cookies}
|
||
rowKey="id"
|
||
loading={loading}
|
||
size="small"
|
||
pagination={{
|
||
current: currentPage,
|
||
pageSize,
|
||
total,
|
||
showSizeChanger: true,
|
||
showTotal: (t) => `共 ${t} 条`,
|
||
onChange: (page, size) => {
|
||
setCurrentPage(page);
|
||
if (size !== pageSize) {
|
||
setPageSize(size);
|
||
localStorage.setItem('cookie_page_size', String(size));
|
||
setCurrentPage(1); // 切换 pageSize 时重置到第1页
|
||
}
|
||
},
|
||
}}
|
||
scroll={{ x: 1210 }}
|
||
/>
|
||
<Modal
|
||
title="数据库重复 CK 检测"
|
||
open={duplicateOpen}
|
||
onCancel={() => setDuplicateOpen(false)}
|
||
footer={null}
|
||
width={960}
|
||
>
|
||
{duplicateLoading ? (
|
||
<div style={{ padding: '48px 0', textAlign: 'center' }}>
|
||
<LoadingOutlined spin />
|
||
<Text style={{ marginLeft: 8 }}>正在检测...</Text>
|
||
</div>
|
||
) : duplicateResult ? (
|
||
<>
|
||
<Alert
|
||
type={duplicateResult.duplicate_groups > 0 ? 'warning' : 'success'}
|
||
showIcon
|
||
message={duplicateResult.duplicate_groups > 0
|
||
? `发现 ${duplicateResult.duplicate_groups} 组「多个账号共用同一份 CK」,涉及 ${duplicateResult.duplicate_rows} 个账号`
|
||
: '未发现共用 CK 的账号'}
|
||
style={{ marginBottom: 16 }}
|
||
/>
|
||
{duplicateResult.groups.length > 0 ? (
|
||
<Table<CookieDuplicateGroup>
|
||
rowKey="account_key"
|
||
size="small"
|
||
pagination={{ pageSize: 10, showTotal: (count) => `共 ${count} 组` }}
|
||
columns={duplicateColumns}
|
||
dataSource={duplicateResult.groups}
|
||
scroll={{ x: 900 }}
|
||
/>
|
||
) : (
|
||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未发现共用 CK 的账号" />
|
||
)}
|
||
</>
|
||
) : null}
|
||
</Modal>
|
||
</div>
|
||
);
|
||
}
|