实现虎牙绑定小程序码展示
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
HUYA_DEFAULT_ROOM_PID = "1199650619883"
|
||||
HUYA_DEFAULT_SID = "2203"
|
||||
HUYA_DEFAULT_OUTER_ACT_ID = "9504"
|
||||
HUYA_DEFAULT_BIND_ACT_ID = "17096"
|
||||
HUYA_DEFAULT_BIND_ACT_ID = "9271"
|
||||
HUYA_DEFAULT_PAY_CHANNEL = "Zfb"
|
||||
|
||||
HUYA_CONFIG_DEFAULTS = {
|
||||
|
||||
@@ -141,6 +141,117 @@ class HuyaBatchRunner:
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
self._mark_task(worker_db, task, "success", f"积分: {points}", result)
|
||||
|
||||
def _execute_get_bind_qr(
|
||||
self,
|
||||
worker_db: Session,
|
||||
task: HuyaTask,
|
||||
account: HuyaAccount,
|
||||
account_info: dict,
|
||||
config_info: dict,
|
||||
):
|
||||
b_act_id = str(self.payload.get("bind_act_id") or config_info.get("bind_act_id") or "").strip()
|
||||
if not b_act_id:
|
||||
self._mark_task(worker_db, task, "failed", "请先配置虎牙绑定 bActId")
|
||||
return
|
||||
|
||||
b_act_id_int = self._to_int(b_act_id)
|
||||
if not b_act_id_int:
|
||||
self._mark_task(worker_db, task, "failed", f"虎牙绑定 bActId 无效: {b_act_id}")
|
||||
return
|
||||
|
||||
uid = self._resolve_uid(account_info)
|
||||
if not uid:
|
||||
self._mark_task(worker_db, task, "failed", "无法从账号或 Cookie 解析 yyuid")
|
||||
return
|
||||
|
||||
cookie = account_info.get("cookie") or ""
|
||||
if not cookie:
|
||||
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
|
||||
return
|
||||
|
||||
client = HuyaHttpClient(logger=lambda msg: self._push_log("info", f"[{uid}] {msg}"))
|
||||
bind_status = client.check_user_bind_game_account(
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
is_use_outer_act_id=1,
|
||||
)
|
||||
if bind_status is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙绑定状态接口无响应")
|
||||
return
|
||||
if bind_status.status != 200:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
bind_status.msg or f"虎牙绑定状态查询失败: {bind_status.status}",
|
||||
bind_status.to_dict(),
|
||||
)
|
||||
return
|
||||
|
||||
live_link = client.get_live_link_param(
|
||||
uid=uid,
|
||||
cookie=cookie,
|
||||
b_act_id=b_act_id_int,
|
||||
game_auth_scene=bind_status.gameAuthScene,
|
||||
)
|
||||
if live_link is None:
|
||||
self._mark_task(worker_db, task, "error", "虎牙绑定二维码参数接口无响应")
|
||||
return
|
||||
if live_link.status != 200:
|
||||
self._mark_task(
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
live_link.msg or f"虎牙绑定二维码参数获取失败: {live_link.status}",
|
||||
live_link.to_log_dict(),
|
||||
)
|
||||
return
|
||||
|
||||
profile_nick = account_info.get("nickname") or account_info.get("username") or ""
|
||||
profile_avatar = ""
|
||||
profile_resp = client.get_user_profile_batch(uid=uid, cookie=cookie, target_uids=[uid])
|
||||
if profile_resp is not None and profile_resp.profiles:
|
||||
profile = profile_resp.profiles[0]
|
||||
profile_nick = profile.nick or profile.passport or profile_nick
|
||||
profile_avatar = profile.avatar or ""
|
||||
|
||||
urls = client.build_bind_urls(
|
||||
live_link.livelinkParam,
|
||||
b_act_id_int,
|
||||
game_auth_scene=bind_status.gameAuthScene,
|
||||
nick_name=profile_nick,
|
||||
face_url=profile_avatar,
|
||||
)
|
||||
mini_qrcode = client.get_livelink_mini_qrcode(urls["qr_url"])
|
||||
if not mini_qrcode:
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"profile": {
|
||||
"nick": profile_nick,
|
||||
"avatar": profile_avatar,
|
||||
},
|
||||
}
|
||||
self._mark_task(worker_db, task, "failed", "绑定小程序码获取失败", result)
|
||||
return
|
||||
|
||||
result = {
|
||||
"bind_act_id": b_act_id_int,
|
||||
"mini_qrcode_image": mini_qrcode["mini_qrcode_image"],
|
||||
"qrcode_token": mini_qrcode["qrcode_token"],
|
||||
"bind_status": bind_status.to_dict(),
|
||||
"profile": {
|
||||
"nick": profile_nick,
|
||||
"avatar": profile_avatar,
|
||||
},
|
||||
}
|
||||
|
||||
account.status = "bind_qr_generated"
|
||||
account.game_name = bind_status.gameName or account.game_name
|
||||
account.nickname = profile_nick or account.nickname
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
self._mark_task(worker_db, task, "success", "已生成绑定小程序码", result)
|
||||
|
||||
def _execute_one(self, task_id: int, account_info: dict, config_info: dict, total: int):
|
||||
worker_db = SessionLocal()
|
||||
try:
|
||||
@@ -165,13 +276,16 @@ class HuyaBatchRunner:
|
||||
name = self._account_name(account_info)
|
||||
self._push_log("info", f"[{current}/{total}] 开始虎牙任务: {name}")
|
||||
|
||||
if self.task_type != "query_points":
|
||||
if self.task_type not in {"query_points", "get_bind_qr"}:
|
||||
self._mark_task(worker_db, task, "failed", "该虎牙任务执行器暂未实现")
|
||||
self._push_log("warning", f"[{current}] {name} 暂未实现: {self.task_type}")
|
||||
return
|
||||
|
||||
try:
|
||||
self._execute_query_points(worker_db, task, account, account_info, config_info)
|
||||
if self.task_type == "query_points":
|
||||
self._execute_query_points(worker_db, task, account, account_info, config_info)
|
||||
elif self.task_type == "get_bind_qr":
|
||||
self._execute_get_bind_qr(worker_db, task, account, account_info, config_info)
|
||||
worker_db.refresh(task)
|
||||
if task.status == "success":
|
||||
self._push_log("success", f"[{current}] {name} {task.message}")
|
||||
|
||||
@@ -32,6 +32,10 @@ def apply_huya_config_defaults(config: HuyaConfig) -> bool:
|
||||
"""补齐虎牙配置默认值,返回是否发生变更。"""
|
||||
changed = False
|
||||
for field in HUYA_CONFIG_FIELDS:
|
||||
if field == "bind_act_id" and str(getattr(config, field, "") or "").strip() == "17096":
|
||||
setattr(config, field, HUYA_CONFIG_DEFAULTS[field])
|
||||
changed = True
|
||||
continue
|
||||
normalized = huya_config_value(field, getattr(config, field, None))
|
||||
if getattr(config, field, None) != normalized:
|
||||
setattr(config, field, normalized)
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Button, Card, Col, Form, Input, InputNumber, message, Row, Select, Space, Table, Tag, Tooltip, Typography, theme,
|
||||
Button, Card, Col, Form, Input, InputNumber, message, Modal, Row, Select, Space, Table, Tag, Tooltip, Typography, theme,
|
||||
} from 'antd';
|
||||
import type { TableProps } from 'antd';
|
||||
import {
|
||||
AppstoreOutlined, CheckCircleOutlined, CreditCardOutlined, FieldTimeOutlined, GiftOutlined,
|
||||
LinkOutlined, PlayCircleOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined,
|
||||
LinkOutlined, PlayCircleOutlined, QrcodeOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
huyaApi,
|
||||
@@ -69,6 +69,22 @@ function accountLabel(account: HuyaAccountItem): string {
|
||||
return `${name}${tag}${phone}`;
|
||||
}
|
||||
|
||||
function resultText(result: Record<string, unknown> | null | undefined, key: string): string {
|
||||
const value = result?.[key];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function resultProfileNick(result: Record<string, unknown> | null | undefined): string {
|
||||
const profile = result?.profile;
|
||||
if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return '';
|
||||
const nick = (profile as Record<string, unknown>).nick;
|
||||
return typeof nick === 'string' ? nick : '';
|
||||
}
|
||||
|
||||
function hasMiniQrcode(task: HuyaTaskItem): boolean {
|
||||
return task.task_type === 'get_bind_qr' && Boolean(resultText(task.result, 'mini_qrcode_image'));
|
||||
}
|
||||
|
||||
export default function HuyaTasksPage() {
|
||||
const { token } = theme.useToken();
|
||||
const [form] = Form.useForm<HuyaConfig>();
|
||||
@@ -88,6 +104,9 @@ export default function HuyaTasksPage() {
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [savingConfig, setSavingConfig] = useState(false);
|
||||
const [batchId, setBatchId] = useState<string | null>(null);
|
||||
const [qrTask, setQrTask] = useState<HuyaTaskItem | null>(null);
|
||||
const autoOpenedQrTaskIds = useRef<Set<number>>(new Set());
|
||||
const autoOpenQrReady = useRef(false);
|
||||
const { logs, connected: wsConnected, connect: connectLogs } = useWebSocketLogs();
|
||||
const { can } = usePermissions();
|
||||
|
||||
@@ -98,6 +117,17 @@ export default function HuyaTasksPage() {
|
||||
localStorage.setItem('huya_task_concurrency', String(concurrency));
|
||||
}, [concurrency]);
|
||||
|
||||
const rememberExistingQrcodes = useCallback((items: HuyaTaskItem[]) => {
|
||||
if (autoOpenQrReady.current) return;
|
||||
items.filter(hasMiniQrcode).forEach((task) => autoOpenedQrTaskIds.current.add(task.id));
|
||||
autoOpenQrReady.current = true;
|
||||
}, []);
|
||||
|
||||
const openQrTask = useCallback((task: HuyaTaskItem) => {
|
||||
autoOpenedQrTaskIds.current.add(task.id);
|
||||
setQrTask(task);
|
||||
}, []);
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -110,7 +140,10 @@ export default function HuyaTasksPage() {
|
||||
]);
|
||||
|
||||
if (accountResult.status === 'fulfilled') setAccounts(accountResult.value);
|
||||
if (taskResult.status === 'fulfilled') setTasks(taskResult.value);
|
||||
if (taskResult.status === 'fulfilled') {
|
||||
rememberExistingQrcodes(taskResult.value);
|
||||
setTasks(taskResult.value);
|
||||
}
|
||||
if (goodsResult.status === 'fulfilled') setGoods(goodsResult.value);
|
||||
if (configResult.status === 'fulfilled' && configResult.value) form.setFieldsValue(configResult.value);
|
||||
if (taskTypeResult.status === 'fulfilled') setTaskTypes({ ...FALLBACK_TASK_TYPES, ...taskTypeResult.value });
|
||||
@@ -128,16 +161,17 @@ export default function HuyaTasksPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [canConfig, form]);
|
||||
}, [canConfig, form, rememberExistingQrcodes]);
|
||||
|
||||
const loadTasks = useCallback(async () => {
|
||||
try {
|
||||
const data = await huyaApi.listTasks();
|
||||
rememberExistingQrcodes(data);
|
||||
setTasks(data);
|
||||
} catch {
|
||||
// 轮询失败不打扰操作,下一轮继续刷新。
|
||||
}
|
||||
}, []);
|
||||
}, [rememberExistingQrcodes]);
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
@@ -148,6 +182,14 @@ export default function HuyaTasksPage() {
|
||||
return () => clearInterval(timer);
|
||||
}, [loadTasks]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoOpenQrReady.current || qrTask) return;
|
||||
const nextQrTask = tasks
|
||||
.filter((task) => hasMiniQrcode(task) && !autoOpenedQrTaskIds.current.has(task.id))
|
||||
.sort((a, b) => b.id - a.id)[0];
|
||||
if (nextQrTask) openQrTask(nextQrTask);
|
||||
}, [openQrTask, qrTask, tasks]);
|
||||
|
||||
const accountOptions = useMemo(() => {
|
||||
return accounts.map((account) => ({ value: account.id, label: accountLabel(account) }));
|
||||
}, [accounts]);
|
||||
@@ -221,6 +263,32 @@ export default function HuyaTasksPage() {
|
||||
const successCount = tasks.filter((task) => task.status === 'success').length;
|
||||
const plannedCount = tasks.filter((task) => task.status === 'planned').length;
|
||||
const failedCount = tasks.filter((task) => ['failed', 'error'].includes(task.status)).length;
|
||||
const qrResult = qrTask?.result || null;
|
||||
const qrImage = resultText(qrResult, 'mini_qrcode_image');
|
||||
const qrAccountName = qrTask
|
||||
? resultProfileNick(qrResult) || qrTask.account_nickname || qrTask.account_uid || `#${qrTask.account_id}`
|
||||
: '';
|
||||
|
||||
const renderTaskResult = (value: Record<string, unknown> | null, record: HuyaTaskItem) => {
|
||||
const bindQrImage = resultText(value, 'mini_qrcode_image');
|
||||
if (bindQrImage) {
|
||||
return (
|
||||
<Button size="small" icon={<QrcodeOutlined />} onClick={() => openQrTask(record)}>
|
||||
查看二维码
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
if (record.task_type === 'get_bind_qr') {
|
||||
return <Text type="secondary">-</Text>;
|
||||
}
|
||||
|
||||
const availableScore = value?.available_score;
|
||||
if (typeof availableScore === 'number') {
|
||||
return <Tag color="blue">可用积分 {availableScore}</Tag>;
|
||||
}
|
||||
|
||||
return value ? <Text code style={{ fontSize: 12 }}>{JSON.stringify(value)}</Text> : <Text type="secondary">-</Text>;
|
||||
};
|
||||
|
||||
const taskColumns: TableProps<HuyaTaskItem>['columns'] = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 70, align: 'center' },
|
||||
@@ -248,11 +316,9 @@ export default function HuyaTasksPage() {
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'result',
|
||||
width: 180,
|
||||
width: 210,
|
||||
ellipsis: true,
|
||||
render: (value: Record<string, unknown> | null) => (
|
||||
value ? <Text code style={{ fontSize: 12 }}>{JSON.stringify(value)}</Text> : <Text type="secondary">-</Text>
|
||||
),
|
||||
render: renderTaskResult,
|
||||
},
|
||||
{
|
||||
title: '时间',
|
||||
@@ -329,8 +395,8 @@ export default function HuyaTasksPage() {
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item label="绑定活动 ID" name="bind_act_id">
|
||||
<Input placeholder="默认 17096" />
|
||||
<Form.Item label="绑定 bActId" name="bind_act_id">
|
||||
<Input placeholder="默认 9271" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
@@ -447,7 +513,7 @@ export default function HuyaTasksPage() {
|
||||
))}
|
||||
</div>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
当前阶段只创建 planned 任务并打通日志通道,真实 WSS/HTTP 执行器后续接入。
|
||||
当前已接入查询积分和获取绑定二维码,其余任务会先保留计划记录。
|
||||
</Text>
|
||||
</div>
|
||||
</Card>
|
||||
@@ -480,6 +546,36 @@ export default function HuyaTasksPage() {
|
||||
spinWhenEmpty
|
||||
style={{ marginTop: 4 }}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title="绑定小程序码"
|
||||
open={!!qrTask}
|
||||
onCancel={() => setQrTask(null)}
|
||||
footer={null}
|
||||
width={360}
|
||||
>
|
||||
{qrTask && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, padding: '8px 0 12px' }}>
|
||||
<Text strong style={{ maxWidth: '100%', textAlign: 'center' }}>{qrAccountName}</Text>
|
||||
{qrImage ? (
|
||||
<img
|
||||
src={qrImage}
|
||||
alt="绑定小程序码"
|
||||
style={{
|
||||
width: 260,
|
||||
height: 260,
|
||||
objectFit: 'contain',
|
||||
display: 'block',
|
||||
borderRadius: 8,
|
||||
background: token.colorBgContainer,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Text type="secondary">暂无二维码</Text>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user