feat(huya): 多选登录改单线程队列并拆分路由与工作台

默认同时只登一个号,失败两次跳下一个,号间留间隔,结束后可一键重试失败账号。
顺带拆分虎牙路由与斗鱼工作台页面,并补齐 raw_cookie 重建入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
yml2213
2026-09-10 11:31:50 +08:00
co-authored by Cursor
parent 8dea9e3244
commit e81119117f
27 changed files with 6405 additions and 5409 deletions
+350 -64
View File
@@ -1,12 +1,14 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Alert,
Avatar,
Button,
Card,
Input,
InputNumber,
Modal,
Popconfirm,
Progress,
Select,
Space,
Table,
@@ -81,6 +83,40 @@ const STATUS_COLORS: Record<string, string> = {
exchange_record: 'purple',
};
const HUYA_LOGIN_INTERVAL_KEY = 'huya_login_interval_seconds';
const HUYA_LOGIN_DEFAULT_INTERVAL = 8;
const HUYA_LOGIN_MAX_ATTEMPTS = 2;
function readLoginIntervalSeconds(): number {
const stored = Number(localStorage.getItem(HUYA_LOGIN_INTERVAL_KEY));
if (!Number.isFinite(stored)) return HUYA_LOGIN_DEFAULT_INTERVAL;
return Math.min(30, Math.max(0, stored));
}
function sleepWithCountdown(
totalMs: number,
aborted: () => boolean,
onTick: (secondsLeft: number) => void,
): Promise<void> {
return new Promise((resolve) => {
const started = Date.now();
const tick = () => {
if (aborted()) {
resolve();
return;
}
const left = Math.max(0, totalMs - (Date.now() - started));
onTick(Math.ceil(left / 1000));
if (left <= 0) {
resolve();
return;
}
window.setTimeout(tick, Math.min(250, left));
};
tick();
});
}
function copyToClipboard(text: string): Promise<void> {
if (navigator.clipboard?.writeText) {
return navigator.clipboard.writeText(text);
@@ -123,6 +159,16 @@ export default function HuyaAccountsPage() {
const [appPasswordLogging, setAppPasswordLogging] = useState(false);
const [loginModalTitle, setLoginModalTitle] = useState('虎牙 App 协议登录结果 (推荐)');
const [passwordLoginResults, setPasswordLoginResults] = useState<HuyaPasswordLoginBatchItem[]>([]);
const [loginQueuePhase, setLoginQueuePhase] = useState<'idle' | 'login' | 'wait' | 'done' | 'stopped'>('idle');
const [loginQueueIndex, setLoginQueueIndex] = useState(0);
const [loginQueueTotal, setLoginQueueTotal] = useState(0);
const [loginQueueUsername, setLoginQueueUsername] = useState('');
const [loginWaitLeft, setLoginWaitLeft] = useState(0);
const [loginIntervalSeconds, setLoginIntervalSeconds] = useState(readLoginIntervalSeconds);
const loginAbortRef = useRef(false);
const loginRunningRef = useRef(false);
const loginChannelRef = useRef<'app' | 'web'>('app');
const loginIntervalRef = useRef(loginIntervalSeconds);
const [smsLoginOpen, setSmsLoginOpen] = useState(false);
const [smsPhone, setSmsPhone] = useState('');
const [smsCode, setSmsCode] = useState('');
@@ -239,6 +285,10 @@ export default function HuyaAccountsPage() {
setSelectedAllMatching(false);
};
useEffect(() => {
loginIntervalRef.current = loginIntervalSeconds;
}, [loginIntervalSeconds]);
useEffect(() => {
clearSelection();
}, [searchText, tagFilter]);
@@ -383,48 +433,216 @@ export default function HuyaAccountsPage() {
}
};
const resolveLoginAccountIds = async (): Promise<number[]> => {
if (selectedAllMatching) {
const data = await huyaApi.listAccountIds({
search: searchText.trim() || undefined,
tag: tagFilter || undefined,
});
return data.account_ids;
}
return selectedRowKeys.map((key) => Number(key));
};
const runLoginQueue = async (
ids: number[],
channel: 'app' | 'web',
options?: { append?: boolean },
) => {
if (ids.length === 0) {
message.warning('没有可登录的账号');
return;
}
if (loginRunningRef.current) {
message.warning('已有登录队列在执行');
return;
}
loginAbortRef.current = false;
loginRunningRef.current = true;
loginChannelRef.current = channel;
const channelLabel = channel === 'app' ? 'App 协议' : 'Web';
if (channel === 'app') {
setAppPasswordLogging(true);
} else {
setPasswordLogging(true);
}
setLoginQueueTotal(ids.length);
setLoginQueueIndex(0);
setLoginQueueUsername('');
setLoginWaitLeft(0);
setLoginQueuePhase('login');
setLoginModalTitle(`${channelLabel}登录中`);
if (!options?.append) {
setPasswordLoginResults([]);
}
setPasswordLoginResultOpen(true);
const usernameById = new Map(
accounts.map((account) => [
account.id,
account.username || account.nickname || String(account.id),
]),
);
let successCount = 0;
let failedCount = 0;
for (let index = 0; index < ids.length; index += 1) {
if (loginAbortRef.current) {
const remaining = ids.slice(index).map((accountId) => ({
line: accountId,
username: usernameById.get(accountId) || '',
success: false,
message: '队列已停止,未登录',
}));
setPasswordLoginResults((prev) => [...prev, ...remaining]);
failedCount += remaining.length;
setLoginQueuePhase('stopped');
break;
}
const accountId = ids[index];
setLoginQueueIndex(index + 1);
setLoginQueueUsername(usernameById.get(accountId) || `#${accountId}`);
setLoginQueuePhase('login');
try {
const payload = {
account_ids: [accountId],
all_matching: false,
search: '',
tag: '',
max_attempts: HUYA_LOGIN_MAX_ATTEMPTS,
interval_seconds: 0,
};
const result = channel === 'app'
? await huyaApi.appPasswordLoginSelected(payload)
: await huyaApi.passwordLoginSelected(payload);
const item = result.results?.[0] || {
line: accountId,
username: usernameById.get(accountId) || '',
success: false,
message: result.message || '登录失败',
};
if (item.success) successCount += 1;
else failedCount += 1;
setPasswordLoginResults((prev) => [...prev, item]);
} catch (e: unknown) {
failedCount += 1;
setPasswordLoginResults((prev) => [
...prev,
{
line: accountId,
username: usernameById.get(accountId) || '',
success: false,
message: getErrorMessage(e),
},
]);
}
const intervalSec = loginIntervalRef.current;
if (index < ids.length - 1 && !loginAbortRef.current && intervalSec > 0) {
setLoginQueuePhase('wait');
await sleepWithCountdown(
intervalSec * 1000,
() => loginAbortRef.current,
setLoginWaitLeft,
);
setLoginWaitLeft(0);
}
}
if (!loginAbortRef.current) {
setLoginQueuePhase('done');
}
loginRunningRef.current = false;
setAppPasswordLogging(false);
setPasswordLogging(false);
loadAccounts();
loadTags();
loadSummary();
if (loginAbortRef.current) {
message.warning(`${channelLabel}登录已停止:成功 ${successCount},失败/未执行 ${failedCount}`);
} else if (failedCount > 0) {
message.warning(`${channelLabel}登录完成:成功 ${successCount},失败 ${failedCount}`);
} else {
message.success(`${channelLabel}登录完成:成功 ${successCount} 条`);
}
};
const handleStopLoginQueue = () => {
if (!loginRunningRef.current) return;
loginAbortRef.current = true;
message.info('将在当前账号结束后停止队列');
};
const handleRetryFailedLogins = async () => {
const failedIds = passwordLoginResults
.filter((item) => !item.success)
.map((item) => Number(item.line))
.filter((id) => Number.isFinite(id) && id > 0);
if (failedIds.length === 0) {
message.warning('没有失败的账号可重试');
return;
}
setPasswordLoginResults((prev) => prev.filter((item) => item.success));
await runLoginQueue(failedIds, loginChannelRef.current, { append: true });
};
const handleAppLoginSelected = async () => {
if (selectedCount === 0) {
message.warning('请先选择虎牙账号');
return;
}
setAppPasswordLogging(true);
try {
const result = await huyaApi.appPasswordLoginSelected({
...selectionPayload,
});
setPasswordLoginResults(result.results || []);
setLoginModalTitle('虎牙 App 协议登录结果 (推荐)');
setPasswordLoginResultOpen(true);
if (result.failed > 0) {
message.warning(result.message);
} else {
message.success(result.message || 'App 登录成功,Cookie 已保存');
}
loadAccounts();
loadTags();
loadSummary();
const ids = await resolveLoginAccountIds();
await runLoginQueue(ids, 'app');
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setAppPasswordLogging(false);
}
};
// 行内单账号登录: 复用批量端点, 只传该行 id (需已导入密码)
const [rowLoginKey, setRowLoginKey] = useState('');
const handleRowLogin = async (record: HuyaAccountItem, channel: 'app' | 'web') => {
if (loginRunningRef.current) {
message.warning('已有登录队列在执行,请等待完成或先停止');
return;
}
setRowLoginKey(`${channel}-${record.id}`);
loginChannelRef.current = channel;
try {
const payload = { account_ids: [record.id], all_matching: false, search: '', tag: '' };
const result = channel === 'app'
? await huyaApi.appPasswordLoginSelected(payload)
: await huyaApi.passwordLoginSelected(payload);
? await huyaApi.appPasswordLoginSelected({
account_ids: [record.id],
all_matching: false,
search: '',
tag: '',
max_attempts: HUYA_LOGIN_MAX_ATTEMPTS,
interval_seconds: 0,
})
: await huyaApi.passwordLoginSelected({
account_ids: [record.id],
all_matching: false,
search: '',
tag: '',
max_attempts: HUYA_LOGIN_MAX_ATTEMPTS,
interval_seconds: 0,
});
setPasswordLoginResults(result.results || []);
setLoginQueuePhase('done');
setLoginQueueIndex(1);
setLoginQueueTotal(1);
setLoginQueueUsername(record.username || record.nickname || String(record.id));
setLoginModalTitle(channel === 'app' ? 'App 协议登录结果' : 'Web 旧版登录结果');
setPasswordLoginResultOpen(true);
const ok = (result.results || []).some((r) => r.success);
if (ok) { message.success('登录成功,Cookie 已保存'); } else { message.warning(result.message || '登录失败'); }
const ok = (result.results || []).some((item) => item.success);
if (ok) {
message.success('登录成功,Cookie 已保存');
} else {
message.warning(result.message || '登录失败');
}
loadAccounts();
loadSummary();
} catch (e: unknown) {
@@ -474,26 +692,11 @@ export default function HuyaAccountsPage() {
message.warning('请先选择虎牙账号');
return;
}
setPasswordLogging(true);
try {
const result = await huyaApi.passwordLoginSelected({
...selectionPayload,
});
setPasswordLoginResults(result.results || []);
setLoginModalTitle('虎牙 Web 密码登录结果 (旧版)');
setPasswordLoginResultOpen(true);
if (result.failed > 0) {
message.warning(result.message);
} else {
message.success(result.message || 'Web 登录成功,Cookie 已保存');
}
loadAccounts();
loadTags();
loadSummary();
const ids = await resolveLoginAccountIds();
await runLoginQueue(ids, 'web');
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setPasswordLogging(false);
}
};
@@ -579,6 +782,13 @@ export default function HuyaAccountsPage() {
<Tag color={success ? 'success' : 'error'}>{success ? '成功' : '失败'}</Tag>
),
},
{
title: '尝试',
dataIndex: 'attempts',
width: 70,
align: 'center',
render: (value?: number) => value || '-',
},
{
title: '保存账号',
width: 160,
@@ -897,6 +1107,7 @@ export default function HuyaAccountsPage() {
type="primary"
icon={<MobileOutlined />}
loading={rowLoginKey === `app-${record.id}`}
disabled={Boolean(rowLoginKey) || appPasswordLogging || passwordLogging}
onClick={() => handleRowLogin(record, 'app')}
/>
</Tooltip>
@@ -917,6 +1128,7 @@ export default function HuyaAccountsPage() {
size="small"
icon={<LoginOutlined />}
loading={rowLoginKey === `web-${record.id}`}
disabled={Boolean(rowLoginKey) || appPasswordLogging || passwordLogging}
onClick={() => handleRowLogin(record, 'web')}
/>
</Tooltip>
@@ -1421,25 +1633,31 @@ export default function HuyaAccountsPage() {
<Space wrap size={8}>
{canImport && (
<Button
type="primary"
size="small"
icon={<MobileOutlined />}
loading={appPasswordLogging}
onClick={handleAppLoginSelected}
>
App 协议登录 ({selectedCount})
</Button>
<Tooltip title="逐个登录,同时只登一个号;失败 2 次后跳下一个,号间默认间隔 8 秒">
<Button
type="primary"
size="small"
icon={<MobileOutlined />}
loading={appPasswordLogging}
disabled={passwordLogging}
onClick={handleAppLoginSelected}
>
App 协议登录 ({selectedCount})
</Button>
</Tooltip>
)}
{canImport && (
<Button
size="small"
icon={<LoginOutlined />}
loading={passwordLogging}
onClick={handleWebLoginSelected}
>
Web 登录
</Button>
<Tooltip title="逐个登录,同时只登一个号;失败 2 次后跳下一个,号间默认间隔 8 秒">
<Button
size="small"
icon={<LoginOutlined />}
loading={passwordLogging}
disabled={appPasswordLogging}
onClick={handleWebLoginSelected}
>
Web 登录
</Button>
</Tooltip>
)}
{canTag && (
<Button
@@ -1673,26 +1891,94 @@ export default function HuyaAccountsPage() {
<Modal
title={loginModalTitle}
open={passwordLoginResultOpen}
onCancel={() => setPasswordLoginResultOpen(false)}
onCancel={() => {
if (loginQueuePhase === 'login' || loginQueuePhase === 'wait') return;
setPasswordLoginResultOpen(false);
}}
footer={[
<Button key="ok" type="primary" onClick={() => setPasswordLoginResultOpen(false)}>
(loginQueuePhase === 'login' || loginQueuePhase === 'wait') ? (
<Button key="stop" danger onClick={handleStopLoginQueue}>
停止队列
</Button>
) : null,
(loginQueuePhase === 'done' || loginQueuePhase === 'stopped')
&& passwordLoginResults.some((item) => !item.success) ? (
<Button
key="retry"
icon={<ReloadOutlined />}
disabled={loginQueuePhase === 'login' || loginQueuePhase === 'wait'}
onClick={() => { void handleRetryFailedLogins(); }}
>
重试失败 ({passwordLoginResults.filter((item) => !item.success).length})
</Button>
) : null,
<Button
key="ok"
type="primary"
disabled={loginQueuePhase === 'login' || loginQueuePhase === 'wait'}
onClick={() => setPasswordLoginResultOpen(false)}
>
确定
</Button>,
]}
].filter(Boolean)}
maskClosable={loginQueuePhase !== 'login' && loginQueuePhase !== 'wait'}
closable={loginQueuePhase !== 'login' && loginQueuePhase !== 'wait'}
width={860}
>
<Alert
type="info"
type={loginQueuePhase === 'stopped' ? 'warning' : 'info'}
showIcon
style={{ marginBottom: 12 }}
message="登录说明"
description="使用 App 协议登录时,系统已自动识别并通过 safe_auth 乱序滑块;若个别新账号提示“要求扫码验证 (qr_auth)”,则需在手机虎牙 App 上正常登录一次以建立设备信任。"
message={
loginQueuePhase === 'login'
? `正在登录 ${loginQueueIndex}/${loginQueueTotal} · ${loginQueueUsername || '—'}`
: loginQueuePhase === 'wait'
? `等待 ${loginWaitLeft}s 后登录下一个(${loginQueueIndex}/${loginQueueTotal})`
: loginQueuePhase === 'stopped'
? '队列已停止'
: '登录说明'
}
description={
loginQueuePhase === 'login' || loginQueuePhase === 'wait'
? `默认单线程,同时只登录一个号;失败最多尝试 ${HUYA_LOGIN_MAX_ATTEMPTS} 次再跳下一个。号与号之间间隔 ${loginIntervalSeconds} 秒。`
: '使用 App 协议登录时,系统已自动识别并通过 safe_auth 乱序滑块;若个别新账号提示“要求扫码验证 (qr_auth)”,则需在手机虎牙 App 上正常登录一次以建立设备信任。失败的账号可一键重试。'
}
/>
<Space wrap style={{ marginBottom: 12 }} align="center">
<Text type="secondary">号间间隔(秒)</Text>
<InputNumber
size="small"
min={0}
max={30}
value={loginIntervalSeconds}
disabled={loginQueuePhase === 'login' || loginQueuePhase === 'wait'}
onChange={(value) => {
const next = Math.min(30, Math.max(0, Number(value ?? HUYA_LOGIN_DEFAULT_INTERVAL)));
setLoginIntervalSeconds(next);
localStorage.setItem(HUYA_LOGIN_INTERVAL_KEY, String(next));
}}
style={{ width: 88 }}
/>
<Text type="secondary">
成功 {passwordLoginResults.filter((item) => item.success).length} · 失败 {passwordLoginResults.filter((item) => !item.success).length}
</Text>
</Space>
{(loginQueuePhase === 'login' || loginQueuePhase === 'wait') && loginQueueTotal > 0 && (
<Progress
percent={Math.round(
((loginQueuePhase === 'login'
? Math.max(0, loginQueueIndex - 1)
: loginQueueIndex) / loginQueueTotal) * 100,
)}
status="active"
style={{ marginBottom: 12 }}
/>
)}
{passwordLoginResults.length > 0 && (
<Table
columns={passwordLoginResultColumns}
dataSource={passwordLoginResults}
rowKey={(record) => `${record.line}-${record.username || 'empty'}`}
rowKey={(record, index) => `${record.line}-${record.username || 'empty'}-${index}`}
size="small"
pagination={false}
scroll={{ x: 720, y: 260 }}