fix(douyu): 升级工作台任务流并修正换绑冷却
This commit is contained in:
@@ -21,6 +21,7 @@ from fastapi import (
|
||||
from loguru import logger
|
||||
from sqlalchemy import case, func, or_, select
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from sqlalchemy.sql import Select
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from core.douyu import (
|
||||
@@ -64,7 +65,7 @@ from ..schemas import (
|
||||
DouyuWorkbenchAccountsUpdate,
|
||||
DouyuXpdGoodsOut,
|
||||
)
|
||||
from ..services.account_binding import bind_payload
|
||||
from ..services.account_binding import BIND_BOUND, bind_payload
|
||||
from ..services.account_observability import (
|
||||
account_platform_status,
|
||||
account_platform_trends,
|
||||
@@ -355,6 +356,7 @@ def _list_visible_tasks_for_support(
|
||||
*,
|
||||
batch_id: str | None,
|
||||
handbook_scope: str | None,
|
||||
account_scope_query: Select | None,
|
||||
limit: int,
|
||||
offset: int = 0,
|
||||
) -> list[DouyuTask]:
|
||||
@@ -369,6 +371,10 @@ def _list_visible_tasks_for_support(
|
||||
base_query = db.query(DouyuTask.id).filter(*owner_filter)
|
||||
if batch_id:
|
||||
base_query = base_query.filter(DouyuTask.batch_id == batch_id)
|
||||
if account_scope_query is not None:
|
||||
base_query = base_query.filter(
|
||||
DouyuTask.account_id.in_(account_scope_query)
|
||||
)
|
||||
for query in _split_task_scope_query(base_query, handbook_scope):
|
||||
rows = query.order_by(DouyuTask.id.desc()).limit(take).all()
|
||||
task_ids.extend(int(row[0]) for row in rows)
|
||||
@@ -401,6 +407,7 @@ def _list_visible_tasks_for_admin(
|
||||
*,
|
||||
batch_id: str | None,
|
||||
handbook_scope: str | None,
|
||||
account_scope_query: Select | None,
|
||||
limit: int,
|
||||
offset: int = 0,
|
||||
) -> list[DouyuTask]:
|
||||
@@ -410,6 +417,10 @@ def _list_visible_tasks_for_admin(
|
||||
base_query = db.query(DouyuTask.id)
|
||||
if batch_id:
|
||||
base_query = base_query.filter(DouyuTask.batch_id == batch_id)
|
||||
if account_scope_query is not None:
|
||||
base_query = base_query.filter(
|
||||
DouyuTask.account_id.in_(account_scope_query)
|
||||
)
|
||||
for query in _split_task_scope_query(base_query, handbook_scope):
|
||||
rows = query.order_by(DouyuTask.id.desc()).limit(take).all()
|
||||
task_ids.extend(int(row[0]) for row in rows)
|
||||
@@ -442,6 +453,7 @@ def _count_visible_tasks_for_admin(
|
||||
*,
|
||||
batch_id: str | None,
|
||||
handbook_scope: str | None,
|
||||
account_scope_query: Select | None,
|
||||
) -> int:
|
||||
"""按作用域分支统计管理员任务数,避免 OR 条件走低效排序。"""
|
||||
if handbook_scope:
|
||||
@@ -460,6 +472,8 @@ def _count_visible_tasks_for_admin(
|
||||
query = db.query(func.count(DouyuTask.id)).filter(*scope_filter)
|
||||
if batch_id:
|
||||
query = query.filter(DouyuTask.batch_id == batch_id)
|
||||
if account_scope_query is not None:
|
||||
query = query.filter(DouyuTask.account_id.in_(account_scope_query))
|
||||
total += int(query.scalar() or 0)
|
||||
return total
|
||||
|
||||
@@ -470,6 +484,7 @@ def _count_visible_tasks_for_support(
|
||||
*,
|
||||
batch_id: str | None,
|
||||
handbook_scope: str | None,
|
||||
account_scope_query: Select | None,
|
||||
) -> int:
|
||||
"""用索引分支精确计算归属/创建人并集的任务总数。"""
|
||||
if handbook_scope:
|
||||
@@ -489,6 +504,8 @@ def _count_visible_tasks_for_support(
|
||||
query = db.query(func.count(DouyuTask.id)).filter(*owner_filter, *scope_filter)
|
||||
if batch_id:
|
||||
query = query.filter(DouyuTask.batch_id == batch_id)
|
||||
if account_scope_query is not None:
|
||||
query = query.filter(DouyuTask.account_id.in_(account_scope_query))
|
||||
return int(query.scalar() or 0)
|
||||
|
||||
assigned_filter = (DouyuTask.account_assigned_to == current.id,)
|
||||
@@ -631,6 +648,8 @@ def _order_task_accounts(
|
||||
|
||||
|
||||
def _account_out(account: Account) -> DouyuTaskAccountOut:
|
||||
elite_cooldown = account.role_bind_status == BIND_BOUND
|
||||
esports_cooldown = account.esports_bind_status == BIND_BOUND
|
||||
return DouyuTaskAccountOut(
|
||||
id=account.id,
|
||||
username=account.username,
|
||||
@@ -645,14 +664,17 @@ def _account_out(account: Account) -> DouyuTaskAccountOut:
|
||||
gold_balance=account.gold_balance,
|
||||
exchange_balance=account.exchange_balance,
|
||||
**bind_payload(account),
|
||||
change_role_wait_time=account.change_role_wait_time,
|
||||
# 未确认绑定时接口倒计时是占位值;API 出口也做一次归一,兼容历史行。
|
||||
change_role_wait_time=account.change_role_wait_time if elite_cooldown else 0,
|
||||
elite_opened=account.elite_opened,
|
||||
elite_expire_time=account.elite_expire_time,
|
||||
esports_points=account.esports_points,
|
||||
esports_game_name=account.esports_game_name or "",
|
||||
esports_game_channel=account.esports_game_channel or "",
|
||||
esports_change_role_wait_time=account.esports_change_role_wait_time,
|
||||
esports_can_change_time=account.esports_can_change_time,
|
||||
esports_change_role_wait_time=(
|
||||
account.esports_change_role_wait_time if esports_cooldown else 0
|
||||
),
|
||||
esports_can_change_time=account.esports_can_change_time if esports_cooldown else None,
|
||||
xpd_game_name=account.xpd_game_name or "",
|
||||
xpd_openid=account.xpd_openid or "",
|
||||
xpd_role_id=account.xpd_role_id or "",
|
||||
@@ -1441,6 +1463,7 @@ async def create_task_batch(
|
||||
def list_tasks(
|
||||
batch_id: str | None = None,
|
||||
handbook_scope: str | None = Query(None, pattern="^(elite|esports|peace)$"),
|
||||
workbench_only: bool = False,
|
||||
include_detail: bool = Query(
|
||||
False, description="是否返回完整任务结果(默认否,轮询请保持 false)"
|
||||
),
|
||||
@@ -1452,12 +1475,24 @@ def list_tasks(
|
||||
"""查看斗鱼任务记录,默认只返回最近 100 条。"""
|
||||
total = None
|
||||
offset = (page - 1) * page_size if page is not None else 0
|
||||
account_scope_query: Select | None = None
|
||||
if workbench_only:
|
||||
if not handbook_scope:
|
||||
raise HTTPException(status_code=400, detail="工作台任务查询必须指定手册类型")
|
||||
account_scope_query = (
|
||||
select(DouyuWorkbenchAccount.account_id)
|
||||
.where(
|
||||
DouyuWorkbenchAccount.user_id == current.id,
|
||||
DouyuWorkbenchAccount.handbook_scope == handbook_scope,
|
||||
)
|
||||
)
|
||||
|
||||
if _can_view_all(current):
|
||||
tasks = _list_visible_tasks_for_admin(
|
||||
db,
|
||||
batch_id=batch_id,
|
||||
handbook_scope=handbook_scope,
|
||||
account_scope_query=account_scope_query,
|
||||
limit=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
@@ -1466,6 +1501,7 @@ def list_tasks(
|
||||
db,
|
||||
batch_id=batch_id,
|
||||
handbook_scope=handbook_scope,
|
||||
account_scope_query=account_scope_query,
|
||||
)
|
||||
else:
|
||||
if not user_has_permission(current, "account:view_assigned"):
|
||||
@@ -1475,6 +1511,7 @@ def list_tasks(
|
||||
current,
|
||||
batch_id=batch_id,
|
||||
handbook_scope=handbook_scope,
|
||||
account_scope_query=account_scope_query,
|
||||
limit=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
@@ -1484,6 +1521,7 @@ def list_tasks(
|
||||
current,
|
||||
batch_id=batch_id,
|
||||
handbook_scope=handbook_scope,
|
||||
account_scope_query=account_scope_query,
|
||||
)
|
||||
|
||||
result = [_task_out(task, include_detail=include_detail) for task in tasks]
|
||||
|
||||
@@ -532,12 +532,20 @@ def binding_snapshot(info: dict | None) -> dict[str, Any]:
|
||||
data = info if isinstance(info, dict) else {}
|
||||
role_name = _binding_role_name(data)
|
||||
bound_status = derive_from_bind_info(data)
|
||||
confirmed = bound_status == BIND_BOUND
|
||||
phase = {
|
||||
BIND_BOUND: "confirmed",
|
||||
BIND_PENDING: "role_ready",
|
||||
BIND_UNBOUND: "unbound",
|
||||
}.get(bound_status or "", "unknown")
|
||||
bound_act = _explicit_flag(data.get("is_bound_act")) is True
|
||||
# 腾讯接口在未完成 bindAct 时会返回 changeRoleWaitTime=2592000 的占位值。
|
||||
# 这不是冷却;未确认绑定必须归一为没有倒计时,原始值仍保留在 bind_info 供排查。
|
||||
change_role_wait_time = _to_int(data.get("change_role_wait_time"))
|
||||
can_change_time = _to_int(data.get("can_change_time"))
|
||||
if not confirmed:
|
||||
change_role_wait_time = 0
|
||||
can_change_time = None
|
||||
return {
|
||||
"role_name": role_name,
|
||||
"area_name": str(data.get("area_name") or "").strip(),
|
||||
@@ -552,8 +560,8 @@ def binding_snapshot(info: dict | None) -> dict[str, Any]:
|
||||
"is_bound_act": bound_act,
|
||||
"need_bind_act": _truthy_flag(data.get("need_bind_act")),
|
||||
"need_bind_role": _truthy_flag(data.get("need_bind_role")),
|
||||
"change_role_wait_time": _to_int(data.get("change_role_wait_time")),
|
||||
"can_change_time": _to_int(data.get("can_change_time")),
|
||||
"change_role_wait_time": change_role_wait_time,
|
||||
"can_change_time": can_change_time,
|
||||
"can_change_role": can_change_role(data),
|
||||
"is_change_cooling": is_role_change_cooling(data),
|
||||
"bind_status": bound_status,
|
||||
|
||||
@@ -2166,20 +2166,10 @@ class BindMixin:
|
||||
f"查询换绑时间候选 act={item.get('act_alias') or '-'} "
|
||||
f"{self._format_bind_summary(item)}",
|
||||
)
|
||||
# 换绑时间看“当前已绑定”活动态,不要优先 cjm(cjm 常无 changeRoleWaitTime)
|
||||
action_aliases = self._action_act_aliases(config)
|
||||
bind_info = next(
|
||||
(
|
||||
item
|
||||
for alias in action_aliases
|
||||
for item in raw_candidates
|
||||
if str(item.get("act_alias") or "") == alias
|
||||
and item.get("change_role_wait_time") is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
# 与其他绑定流程共用“当前已绑定优先”的候选选择。
|
||||
# cjm 常没有 changeRoleWaitTime,不能靠原始字段是否存在来决定业务口径。
|
||||
bind_info = (
|
||||
bind_info
|
||||
self._pick_change_wait_bind_info(raw_candidates, config)
|
||||
or (
|
||||
role.get("bind_info")
|
||||
if isinstance(role.get("bind_info"), dict)
|
||||
|
||||
@@ -71,9 +71,19 @@ export const douyuApi = {
|
||||
listPeaceGoods: () => api.get<DouyuXpdGoodsItem[], DouyuXpdGoodsItem[]>('/douyu/xpd-goods'),
|
||||
createTasks: (data: DouyuTaskBatchRequest) =>
|
||||
api.post<DouyuTaskBatchResult, DouyuTaskBatchResult>('/douyu/tasks/batch', data),
|
||||
listTasks: (handbookScope: 'elite' | 'esports' | 'peace', batchId?: string) =>
|
||||
listTasks: (
|
||||
handbookScope: 'elite' | 'esports' | 'peace',
|
||||
batchId?: string,
|
||||
workbenchOnly = false,
|
||||
pageSize = 100,
|
||||
) =>
|
||||
api.get<DouyuTaskItem[], DouyuTaskItem[]>('/douyu/tasks', {
|
||||
params: { handbook_scope: handbookScope, ...(batchId ? { batch_id: batchId } : {}) },
|
||||
params: {
|
||||
handbook_scope: handbookScope,
|
||||
...(batchId ? { batch_id: batchId } : {}),
|
||||
...(workbenchOnly ? { workbench_only: true } : {}),
|
||||
page_size: pageSize,
|
||||
},
|
||||
}),
|
||||
listWorkbenchAccounts: (handbookScope: 'elite' | 'esports' | 'peace') =>
|
||||
api.get<{ account_ids: number[]; configured: boolean }, { account_ids: number[]; configured: boolean }>('/douyu/workbench-accounts', {
|
||||
|
||||
@@ -373,6 +373,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
() => tasks.filter((task) => activeTaskTypes.has(task.task_type)),
|
||||
[activeTaskTypes, tasks],
|
||||
);
|
||||
const isLocallyStartedTask = useCallback(
|
||||
(task: DouyuTaskItem) => locallyStartedBatchIds.current.has(task.batch_id),
|
||||
[],
|
||||
);
|
||||
|
||||
// qrTask 由 activeQrTaskId 从最新 tasks 中派生,切换 Tab 即切换关注账号
|
||||
const qrTask = useMemo(
|
||||
@@ -475,63 +479,46 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
return map;
|
||||
}, [tasks]);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
const loadAccountsPage = useCallback(async () => {
|
||||
if (!workbenchReady) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [accResult, goodsResult, taskResult, cfgResult, typeResult, rechargeChannelResult] = await Promise.allSettled([
|
||||
workbenchIds.length > 0
|
||||
? douyuApi.listAccountsPaged({
|
||||
ids: workbenchIds.join(','),
|
||||
search: accountSearch.trim() || undefined,
|
||||
page: accountPage,
|
||||
page_size: accountPageSize,
|
||||
})
|
||||
: Promise.resolve({ items: [] as DouyuTaskAccountItem[], total: 0, page: accountPage, page_size: accountPageSize }),
|
||||
isPeaceHandbook
|
||||
? douyuApi.listPeaceGoods()
|
||||
: (isEsportsHandbook ? douyuApi.listEsportsGoods() : douyuApi.listGoods()),
|
||||
douyuApi.listTasks(handbook),
|
||||
canConfig ? douyuApi.getConfig() : Promise.resolve(null),
|
||||
douyuApi.taskTypes(),
|
||||
douyuApi.getRechargeChannel(),
|
||||
]);
|
||||
if (accResult.status === 'fulfilled') {
|
||||
setAccounts(accResult.value.items);
|
||||
setAccountTotal(accResult.value.total);
|
||||
if (accountPage > 1 && accResult.value.items.length === 0) {
|
||||
setAccountPage(Math.max(1, Math.ceil(accResult.value.total / accountPageSize)));
|
||||
}
|
||||
}
|
||||
if (goodsResult.status === 'fulfilled') setGoods(goodsResult.value);
|
||||
if (taskResult.status === 'fulfilled') {
|
||||
setTasks(taskResult.value);
|
||||
// 首次加载只压制历史的复制/失败提示。二维码只会因当前页面创建的批次自动打开。
|
||||
if (!autoOpenQrReady.current) {
|
||||
for (const task of taskResult.value) {
|
||||
// 历史兑换成功任务不触发自动复制,避免页面加载时打扰
|
||||
if (exchangeTaskSucceeded(task)) autoCopiedExchangeTaskIds.current.add(task.id);
|
||||
// 历史确认绑定失败任务不重复弹提示(只提示一次)
|
||||
if (
|
||||
task.task_type === 'confirm_bind'
|
||||
&& ['failed', 'error'].includes(task.status)
|
||||
&& (task.message || '').includes('待绑定游戏账号')
|
||||
) {
|
||||
autoNotifiedConfirmFailedTaskIds.current.add(task.id);
|
||||
}
|
||||
}
|
||||
autoOpenQrReady.current = true;
|
||||
autoOpenEsportsBindReady.current = true;
|
||||
}
|
||||
}
|
||||
if (cfgResult.status === 'fulfilled' && cfgResult.value) setConfig(cfgResult.value);
|
||||
if (typeResult.status === 'fulfilled') setTaskTypes(typeResult.value);
|
||||
if (rechargeChannelResult.status === 'fulfilled') {
|
||||
setGoldRechargeChannel(rechargeChannelResult.value.gold_recharge_channel);
|
||||
const result = workbenchIds.length > 0
|
||||
? await douyuApi.listAccountsPaged({
|
||||
ids: workbenchIds.join(','),
|
||||
search: accountSearch.trim() || undefined,
|
||||
page: accountPage,
|
||||
page_size: accountPageSize,
|
||||
})
|
||||
: { items: [] as DouyuTaskAccountItem[], total: 0, page: accountPage, page_size: accountPageSize };
|
||||
setAccounts(result.items);
|
||||
setAccountTotal(result.total);
|
||||
if (accountPage > 1 && result.items.length === 0) {
|
||||
setAccountPage(Math.max(1, Math.ceil(result.total / accountPageSize)));
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(`加载工作台账号失败: ${getErrorMessage(error)}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [accountPage, accountPageSize, accountSearch, canConfig, handbook, isEsportsHandbook, isPeaceHandbook, workbenchIds]);
|
||||
}, [accountPage, accountPageSize, accountSearch, workbenchIds, workbenchReady]);
|
||||
|
||||
const loadStaticData = useCallback(async () => {
|
||||
const [goodsResult, cfgResult, typeResult, rechargeChannelResult] = await Promise.allSettled([
|
||||
isPeaceHandbook
|
||||
? douyuApi.listPeaceGoods()
|
||||
: (isEsportsHandbook ? douyuApi.listEsportsGoods() : douyuApi.listGoods()),
|
||||
canConfig ? douyuApi.getConfig() : Promise.resolve(null),
|
||||
douyuApi.taskTypes(),
|
||||
douyuApi.getRechargeChannel(),
|
||||
]);
|
||||
if (goodsResult.status === 'fulfilled') setGoods(goodsResult.value);
|
||||
if (cfgResult.status === 'fulfilled' && cfgResult.value) setConfig(cfgResult.value);
|
||||
if (typeResult.status === 'fulfilled') setTaskTypes(typeResult.value);
|
||||
if (rechargeChannelResult.status === 'fulfilled') {
|
||||
setGoldRechargeChannel(rechargeChannelResult.value.gold_recharge_channel);
|
||||
}
|
||||
}, [canConfig, isEsportsHandbook, isPeaceHandbook]);
|
||||
|
||||
const setPaySessionsSafely = useCallback(
|
||||
(updater: (current: DouyuPaySession[]) => DouyuPaySession[]) => {
|
||||
@@ -581,11 +568,26 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
}, [loadPaySessionTasks, paySessionsStorageKey]);
|
||||
|
||||
const loadTasks = useCallback(async () => {
|
||||
if (tasksLoadingRef.current) return;
|
||||
if (!workbenchReady || tasksLoadingRef.current) return;
|
||||
tasksLoadingRef.current = true;
|
||||
try {
|
||||
const data = await douyuApi.listTasks(handbook);
|
||||
const data = await douyuApi.listTasks(handbook, undefined, true, 300);
|
||||
setTasks(data);
|
||||
// 首次快照只建立历史基线;只有本页创建的批次允许触发自动二维码/复制/弹窗。
|
||||
if (!autoOpenQrReady.current) {
|
||||
for (const task of data) {
|
||||
if (exchangeTaskSucceeded(task)) autoCopiedExchangeTaskIds.current.add(task.id);
|
||||
if (
|
||||
task.task_type === 'confirm_bind'
|
||||
&& ['failed', 'error'].includes(task.status)
|
||||
&& (task.message || '').includes('待绑定游戏账号')
|
||||
) {
|
||||
autoNotifiedConfirmFailedTaskIds.current.add(task.id);
|
||||
}
|
||||
}
|
||||
autoOpenQrReady.current = true;
|
||||
autoOpenEsportsBindReady.current = true;
|
||||
}
|
||||
if (!data.some((task) => ['pending', 'running', 'planned'].includes(task.status))) {
|
||||
// 批次已结束时清理 busy 标记,避免 onResult 丢失导致永久锁住
|
||||
setRunningBatchIds(new Set());
|
||||
@@ -598,9 +600,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
} finally {
|
||||
tasksLoadingRef.current = false;
|
||||
}
|
||||
}, [handbook, loadPaySessionTasks]);
|
||||
}, [handbook, loadPaySessionTasks, workbenchReady]);
|
||||
|
||||
useEffect(() => { loadData(); }, [loadData]);
|
||||
useEffect(() => { void loadAccountsPage(); }, [loadAccountsPage]);
|
||||
useEffect(() => { void loadStaticData(); }, [loadStaticData]);
|
||||
useEffect(() => {
|
||||
if (workbenchReady) void loadTasks();
|
||||
}, [loadTasks, workbenchIds, workbenchReady]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -658,10 +664,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
localStorage.setItem(DOUYU_GIFT_COUNT_STORAGE_KEY, String(giftCount));
|
||||
}, [giftCount]);
|
||||
|
||||
const hasActiveTasks = useMemo(
|
||||
() => visibleTasks.some((task) => ['pending', 'running', 'planned'].includes(task.status)),
|
||||
[visibleTasks],
|
||||
);
|
||||
const hasActivePayTasks = useMemo(
|
||||
() => paySessions.some((session) => (
|
||||
(paySessionTasks[session.batchId] || []).some(
|
||||
@@ -699,18 +701,30 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
|
||||
const selectedHasRunning = selectedIds.some((id) => runningAccountIds.has(id));
|
||||
|
||||
// 任务状态由 WS(level=task) 即时推送;轮询仅作兜底(多标签页/断线重连),
|
||||
// 有活跃任务或 WS 连接时 5 秒一次,空闲 30 秒轻量刷新
|
||||
// WS 是主更新通道;仅本页活跃批次在断线时高频兜底,空闲页面低频做一致性校验。
|
||||
useEffect(() => {
|
||||
const intervalMs = (
|
||||
hasActiveTasks
|
||||
|| hasActivePayTasks
|
||||
|| logs.connected
|
||||
|| runningBatchIds.size > 0
|
||||
) ? 5000 : 30000;
|
||||
const timer = setInterval(loadTasks, intervalMs);
|
||||
return () => clearInterval(timer);
|
||||
}, [hasActivePayTasks, hasActiveTasks, loadTasks, logs.connected, runningBatchIds]);
|
||||
if (!workbenchReady) return undefined;
|
||||
const active = activeBatchIds.size > 0 || hasActivePayTasks || runningBatchIds.size > 0;
|
||||
const intervalMs = active ? (logs.connected ? 30000 : 5000) : 90000;
|
||||
const refreshVisibleTasks = () => {
|
||||
if (document.visibilityState === 'visible') void loadTasks();
|
||||
};
|
||||
const timer = window.setInterval(refreshVisibleTasks, intervalMs);
|
||||
document.addEventListener('visibilitychange', refreshVisibleTasks);
|
||||
window.addEventListener('focus', refreshVisibleTasks);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
document.removeEventListener('visibilitychange', refreshVisibleTasks);
|
||||
window.removeEventListener('focus', refreshVisibleTasks);
|
||||
};
|
||||
}, [
|
||||
activeBatchIds,
|
||||
hasActivePayTasks,
|
||||
loadTasks,
|
||||
logs.connected,
|
||||
runningBatchIds,
|
||||
workbenchReady,
|
||||
]);
|
||||
|
||||
const openQrTask = useCallback(async (task: DouyuTaskItem, activate = true) => {
|
||||
let resolved = task;
|
||||
@@ -890,7 +904,11 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
useEffect(() => {
|
||||
if (!autoOpenQrReady.current) return;
|
||||
const pending = visibleTasks
|
||||
.filter((task) => exchangeTaskSucceeded(task) && !autoCopiedExchangeTaskIds.current.has(task.id))
|
||||
.filter((task) => (
|
||||
isLocallyStartedTask(task)
|
||||
&& exchangeTaskSucceeded(task)
|
||||
&& !autoCopiedExchangeTaskIds.current.has(task.id)
|
||||
))
|
||||
.sort((a, b) => a.id - b.id);
|
||||
if (pending.length === 0) return;
|
||||
for (const task of pending) autoCopiedExchangeTaskIds.current.add(task.id);
|
||||
@@ -908,14 +926,15 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
console.warn('复制兑换图片失败', error);
|
||||
},
|
||||
);
|
||||
}, [visibleTasks]);
|
||||
}, [isLocallyStartedTask, visibleTasks]);
|
||||
|
||||
// 确认绑定失败自动弹提示(页面中央弹窗,自动消失,一次性去重)
|
||||
useEffect(() => {
|
||||
if (!autoOpenQrReady.current) return;
|
||||
const failedTasks = visibleTasks
|
||||
.filter((task) => (
|
||||
task.task_type === 'confirm_bind'
|
||||
isLocallyStartedTask(task)
|
||||
&& task.task_type === 'confirm_bind'
|
||||
&& ['failed', 'error'].includes(task.status)
|
||||
&& (task.message || '').includes('待绑定游戏账号')
|
||||
&& !autoNotifiedConfirmFailedTaskIds.current.has(task.id)
|
||||
@@ -933,7 +952,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
setActiveQrTaskId((cur) => (cur != null && !next.includes(cur) ? (next[next.length - 1] ?? null) : cur));
|
||||
return next;
|
||||
});
|
||||
}, [visibleTasks]);
|
||||
}, [isLocallyStartedTask, visibleTasks]);
|
||||
|
||||
// 弹窗倒计时自动关闭
|
||||
useEffect(() => {
|
||||
@@ -1073,7 +1092,8 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
next.delete(result.batch_id);
|
||||
return next;
|
||||
});
|
||||
void loadData();
|
||||
void loadAccountsPage();
|
||||
void loadTasks();
|
||||
},
|
||||
onTask: (rawTask) => {
|
||||
const task = rawTask as unknown as DouyuTaskItem;
|
||||
@@ -1108,7 +1128,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
if (prev.some((t) => t.id === task.id)) {
|
||||
return prev.map((t) => (t.id === task.id ? task : t));
|
||||
}
|
||||
return [task, ...prev].slice(0, 100);
|
||||
return [task, ...prev].slice(0, 300);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1424,7 +1444,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
const skipped = result.skipped ? `,${result.skipped} 个因缺少登录凭据跳过` : '';
|
||||
message.success(`已开始重登 ${result.count} 个失效账号${skipped}`);
|
||||
setSelectedIds([]);
|
||||
window.setTimeout(() => void loadData(), 2000);
|
||||
window.setTimeout(() => {
|
||||
void loadAccountsPage();
|
||||
void loadTasks();
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
@@ -1840,9 +1863,15 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
title: '换绑时间', dataIndex: 'change_role_wait_time', width: 150,
|
||||
render: (_, record) => {
|
||||
const fromTask = latestChangeWaitByAccount.get(record.id);
|
||||
const canChangeTime = fromTask?.canChangeTime ?? (
|
||||
isEsportsHandbook ? record.esports_can_change_time : null
|
||||
);
|
||||
const scopeState = isEsportsHandbook
|
||||
? record.esports_bind_status
|
||||
: record.role_bind_status;
|
||||
const noCooldown = scopeState === 'unbound' || scopeState === 'pending';
|
||||
const canChangeTime = noCooldown
|
||||
? null
|
||||
: (fromTask?.canChangeTime ?? (
|
||||
isEsportsHandbook ? record.esports_can_change_time : null
|
||||
));
|
||||
const esportsStatus = isEsportsHandbook ? esportsRebindStatus(canChangeTime) : null;
|
||||
if (esportsStatus) {
|
||||
return esportsStatus.available
|
||||
@@ -1854,10 +1883,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
const wait = fromTask?.wait ?? (
|
||||
const wait = noCooldown ? 0 : (fromTask?.wait ?? (
|
||||
isEsportsHandbook ? record.esports_change_role_wait_time : record.change_role_wait_time
|
||||
);
|
||||
const text = fromTask?.text || formatWaitSeconds(wait);
|
||||
));
|
||||
const text = noCooldown ? '0' : (fromTask?.text || formatWaitSeconds(wait));
|
||||
if (wait == null && !text) {
|
||||
return <Text type="secondary">未查</Text>;
|
||||
}
|
||||
@@ -1877,14 +1906,24 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
return <Text type="secondary">{text || '-'}</Text>;
|
||||
},
|
||||
sorter: (a, b) => {
|
||||
const aState = isEsportsHandbook ? a.esports_bind_status : a.role_bind_status;
|
||||
const bState = isEsportsHandbook ? b.esports_bind_status : b.role_bind_status;
|
||||
const aNoCooldown = aState === 'unbound' || aState === 'pending';
|
||||
const bNoCooldown = bState === 'unbound' || bState === 'pending';
|
||||
const aw = isEsportsHandbook
|
||||
? latestChangeWaitByAccount.get(a.id)?.canChangeTime ?? a.esports_can_change_time ?? -1
|
||||
: latestChangeWaitByAccount.get(a.id)?.wait
|
||||
?? (isEsportsHandbook ? a.esports_change_role_wait_time : a.change_role_wait_time) ?? -1;
|
||||
? (aNoCooldown ? 0 : latestChangeWaitByAccount.get(a.id)?.canChangeTime ?? a.esports_can_change_time ?? -1)
|
||||
: (aNoCooldown ? 0 : (
|
||||
latestChangeWaitByAccount.get(a.id)?.wait
|
||||
?? (isEsportsHandbook ? a.esports_change_role_wait_time : a.change_role_wait_time)
|
||||
?? -1
|
||||
));
|
||||
const bw = isEsportsHandbook
|
||||
? latestChangeWaitByAccount.get(b.id)?.canChangeTime ?? b.esports_can_change_time ?? -1
|
||||
: latestChangeWaitByAccount.get(b.id)?.wait
|
||||
?? (isEsportsHandbook ? b.esports_change_role_wait_time : b.change_role_wait_time) ?? -1;
|
||||
? (bNoCooldown ? 0 : latestChangeWaitByAccount.get(b.id)?.canChangeTime ?? b.esports_can_change_time ?? -1)
|
||||
: (bNoCooldown ? 0 : (
|
||||
latestChangeWaitByAccount.get(b.id)?.wait
|
||||
?? (isEsportsHandbook ? b.esports_change_role_wait_time : b.change_role_wait_time)
|
||||
?? -1
|
||||
));
|
||||
return aw - bw;
|
||||
},
|
||||
},
|
||||
@@ -2791,7 +2830,17 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
||||
onClick={() => setLayoutMode((m) => (m === 'split' ? 'stack' : 'split'))}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Button icon={<ReloadOutlined />} onClick={loadData} loading={loading}>刷新</Button>
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
onClick={() => {
|
||||
void loadAccountsPage();
|
||||
void loadStaticData();
|
||||
void loadTasks();
|
||||
}}
|
||||
loading={loading}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
{canConfig && <Button icon={<SettingOutlined />} onClick={() => setConfigOpen(true)}>配置</Button>}
|
||||
{(activeBatchIds.size > 0 || runningBatchIds.size > 0) && (
|
||||
<Popconfirm
|
||||
|
||||
Reference in New Issue
Block a user