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 { 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(); 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([]); const [loading, setLoading] = useState(false); const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [searchText, setSearchText] = useState(''); const [tagFilter, setTagFilter] = useState(''); const [tags, setTags] = useState([]); const [customNamesText, setCustomNamesText] = useState(''); const [customAccountNames, setCustomAccountNames] = useState([]); const [total, setTotal] = useState(0); const [summary, setSummary] = useState({ 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>(new Set()); const [checkResults, setCheckResults] = useState>(new Map()); const [reloginIds, setReloginIds] = useState>(new Set()); const [duplicateOpen, setDuplicateOpen] = useState(false); const [duplicateLoading, setDuplicateLoading] = useState(false); const [duplicateResult, setDuplicateResult] = useState(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 ? {name} : 未分配, }, { title: 'Cookie', dataIndex: 'cookie_preview', width: 300, ellipsis: true, render: (val: string) => { if (!canView) return ***; return {val}; }, }, { title: '有效性', width: 90, align: 'center' as const, render: (_: unknown, record: CookieItem) => { if (checkingIds.has(record.id)) { return }>检测中...; } const result = checkResults.get(record.id); if (!result) return 未检测; 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 ? 有效 : 无效; return detail ? {tag} : 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 ? {formatTime(checkedAt)} : -; }, }, { 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) => ( {canView && ( )} {canRelogin && ( handleRelogin([record.id])} > )} {canExport && ( handleDelete(record.id)}> )} {canView && ( )} {canRelogin && ( )} {canExport && ( )} {canExport && ( handleExport('csv') }, { key: 'custom', label: '自定义(账号----密码----ck)', onClick: () => handleExport('custom') }, ], }} > )} setCustomNamesText(e.target.value)} placeholder="从 Excel 复制斗鱼账户名后粘贴到这里,每行一个" autoSize={{ minRows: 3, maxRows: 7 }} /> {customAccountNames.length > 0 && ( 已载入 {customAccountNames.length} 个账户名,匹配结果共 {total} 条 )}