- pyrightconfig.json 钉死 Python 3.12 虚拟环境,消除由于查找系统 Python 3.9 带来的假性报错 - 修复 huya/login.py 引用不存在函数的问题并补充单元测试 - 修复 browser_harvest.py 对 set 下标访问的错误并提升报错信息质量 - 虎牙 6 个子路由显式导入依赖,消除 import * 带来的未定义变量报警 - 规范化 Pydantic Field(default=...) 默认值声明 - 完善 solver.py / app_login.py 等核心路径类型守卫与 @overload 重载 - 在 pyproject.toml 中显式锁定 ruff lint 规则集 (E4, E7, E9, F, B, I, BLE) - 门禁脚本同步增加 ruff check 检查并在 AGENTS.md 补齐实践经验总结
537 lines
17 KiB
Python
537 lines
17 KiB
Python
"""虎牙账号:列表、导入、分配、标签、浏览器兑换材料。"""
|
|
|
|
from fastapi import APIRouter
|
|
|
|
from ._common import (
|
|
DEFAULT_EXCHANGE_TARGET,
|
|
AccountAssign,
|
|
AccountBulkSelection,
|
|
AccountBulkTag,
|
|
AccountTag,
|
|
BatchAssign,
|
|
Depends,
|
|
HTTPException,
|
|
HuyaAccount,
|
|
HuyaBrowserExchangeRequest,
|
|
HuyaCookieImport,
|
|
HuyaPasswordAccountImport,
|
|
HuyaTask,
|
|
HuyaWorkbenchAccount,
|
|
Query,
|
|
Session,
|
|
User,
|
|
_account_out,
|
|
_account_out_light,
|
|
_can_view_huya_all,
|
|
_can_view_huya_assigned,
|
|
_can_view_huya_cookie,
|
|
_clear_huya_account_references,
|
|
_filter_huya_accounts_query,
|
|
_huya_cookie_state_map,
|
|
_huya_password_state_map,
|
|
_require_huya_perm,
|
|
_require_huya_tag_permission,
|
|
_selected_huya_account_ids,
|
|
_visible_huya_accounts_query,
|
|
browser_login_script,
|
|
cookie_pairs,
|
|
defer,
|
|
ensure_huya_config,
|
|
exchange_target_options,
|
|
exchange_target_url,
|
|
func,
|
|
get_current_user,
|
|
get_db,
|
|
huya_config_value,
|
|
import_huya_cookies,
|
|
import_huya_password_accounts,
|
|
normalize_huya_cookie,
|
|
or_,
|
|
record_audit,
|
|
)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/accounts/{account_id}/browser-exchange")
|
|
def create_browser_exchange_kit(
|
|
account_id: int,
|
|
req: HuyaBrowserExchangeRequest | None = None,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""生成指定账号的本机浏览器人工兑换材料。
|
|
|
|
登录态由前端引导用户在自己的 Chrome/Edge 中写入,服务端不托管浏览器会话;
|
|
`target` 选择要打开的目标页(直播间/精英宝典/电竞宝典),不传则用默认目标。
|
|
"""
|
|
_require_huya_perm(current, "huya:task")
|
|
account = (
|
|
_visible_huya_accounts_query(db, current)
|
|
.filter(HuyaAccount.id == account_id)
|
|
.first()
|
|
)
|
|
if account is None:
|
|
raise HTTPException(status_code=404, detail="虎牙账号不存在或无权操作")
|
|
if not account.cookie:
|
|
raise HTTPException(status_code=400, detail="该账号没有可用 Cookie,请先登录")
|
|
config = ensure_huya_config(db)
|
|
room_pid = huya_config_value("room_pid", config.room_pid)
|
|
target = req.target if req and req.target else DEFAULT_EXCHANGE_TARGET
|
|
targets = exchange_target_options(room_pid)
|
|
try:
|
|
target_url = exchange_target_url(target, room_pid)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
pairs = dict(cookie_pairs(normalize_huya_cookie(account.cookie)))
|
|
# 兑换材料等同账号凭证:逐次留痕,记录谁、何时、取走哪个账号、准备打开哪个页面
|
|
record_audit(
|
|
db,
|
|
current,
|
|
action="huya:exchange:kit",
|
|
target=f"huya_account:{account.id}",
|
|
detail={"account_id": account.id, "target": target},
|
|
)
|
|
db.commit()
|
|
return {
|
|
"account_id": account.id,
|
|
"username": account.username or account.yyuid or "",
|
|
"target": target,
|
|
"targets": targets,
|
|
"target_url": target_url,
|
|
"cookie_string": "; ".join(f"{key}={value}" for key, value in pairs.items()),
|
|
"cookie_script": browser_login_script(pairs, target_url),
|
|
}
|
|
|
|
|
|
@router.get("/accounts")
|
|
def list_accounts(
|
|
assigned_only: bool = Query(False),
|
|
tag: str | None = Query(None),
|
|
has_cookie: bool = Query(False),
|
|
search: str = Query(""),
|
|
page: int | None = Query(None, ge=1),
|
|
page_size: int = Query(20, ge=1, le=200),
|
|
include_cookie: bool | None = Query(None),
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""查看虎牙 CK 账号。"""
|
|
query = _filter_huya_accounts_query(
|
|
_visible_huya_accounts_query(db, current),
|
|
current,
|
|
assigned_only=assigned_only,
|
|
tag=tag,
|
|
has_cookie=has_cookie,
|
|
search=search,
|
|
)
|
|
|
|
total = None
|
|
if page is not None:
|
|
total = query.order_by(None).count()
|
|
should_include_cookie = (
|
|
_can_view_huya_cookie(current)
|
|
if include_cookie is None
|
|
else (include_cookie and _can_view_huya_cookie(current))
|
|
)
|
|
query = query.order_by(HuyaAccount.id.desc())
|
|
if page is not None:
|
|
query = query.offset((page - 1) * page_size).limit(page_size)
|
|
|
|
if not should_include_cookie:
|
|
query = query.options(
|
|
defer(HuyaAccount.cookie), defer(HuyaAccount.account_password)
|
|
)
|
|
accounts = query.all()
|
|
if should_include_cookie:
|
|
result = [_account_out(account, include_cookie=True) for account in accounts]
|
|
else:
|
|
password_map = _huya_password_state_map(
|
|
db, [account.id for account in accounts]
|
|
)
|
|
cookie_map = _huya_cookie_state_map(db, [account.id for account in accounts])
|
|
result = [
|
|
_account_out_light(
|
|
account,
|
|
has_password=password_map.get(account.id, False),
|
|
has_cookie=cookie_map.get(account.id, False),
|
|
)
|
|
for account in accounts
|
|
]
|
|
if page is not None:
|
|
return {
|
|
"items": result,
|
|
"total": total or 0,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
}
|
|
return result
|
|
|
|
|
|
@router.get("/accounts/summary")
|
|
def accounts_summary(
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""虎牙账号统计,避免前端为了卡片统计拉全量账号。"""
|
|
query = _visible_huya_accounts_query(db, current)
|
|
total = query.count()
|
|
assigned_count = query.filter(HuyaAccount.assigned_to.isnot(None)).count()
|
|
tag_count = (
|
|
query.filter(HuyaAccount.tag != "", HuyaAccount.tag.isnot(None))
|
|
.with_entities(HuyaAccount.tag)
|
|
.distinct()
|
|
.count()
|
|
)
|
|
password_ready_count = query.filter(HuyaAccount.account_password != "").count()
|
|
point_count = query.filter(HuyaAccount.points.isnot(None)).count()
|
|
bound_count = query.filter(
|
|
or_(
|
|
HuyaAccount.game_name != "",
|
|
HuyaAccount.game_channel != "",
|
|
HuyaAccount.game_phone != "",
|
|
)
|
|
).count()
|
|
return {
|
|
"total": total,
|
|
"assigned_count": assigned_count,
|
|
"unassigned_count": max(0, total - assigned_count),
|
|
"tag_count": tag_count,
|
|
"password_ready_count": password_ready_count,
|
|
"point_count": point_count,
|
|
"bound_count": bound_count,
|
|
}
|
|
|
|
|
|
@router.get("/accounts/ids")
|
|
def list_huya_account_ids(
|
|
search: str = "",
|
|
tag: str = "",
|
|
has_cookie: bool = False,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""返回当前用户可见的全部账号 ID(不受分页限制),供工作台导入与批量登录排队。"""
|
|
query = _filter_huya_accounts_query(
|
|
_visible_huya_accounts_query(db, current),
|
|
current,
|
|
tag=tag or None,
|
|
has_cookie=has_cookie,
|
|
search=search,
|
|
)
|
|
rows = query.with_entities(HuyaAccount.id).all()
|
|
return {"account_ids": [row[0] for row in rows], "total": len(rows)}
|
|
|
|
|
|
@router.post("/accounts/import-cookies")
|
|
def import_cookies(
|
|
req: HuyaCookieImport,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""粘贴并导入虎牙 Cookie。"""
|
|
_require_huya_perm(current, "huya:import")
|
|
count, skipped = import_huya_cookies(db, req.text, req.tag)
|
|
return {
|
|
"message": f"导入/更新 {count} 条,跳过 {skipped} 条",
|
|
"success": True,
|
|
"count": count,
|
|
"skipped": skipped,
|
|
}
|
|
|
|
|
|
@router.post("/accounts/import-passwords")
|
|
def import_password_accounts(
|
|
req: HuyaPasswordAccountImport,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""导入虎牙账号密码,只入库不立即登录(仅允许四段格式)。"""
|
|
_require_huya_perm(current, "huya:import")
|
|
count, skipped = import_huya_password_accounts(
|
|
db, req.text, req.tag, require_four_segments=True
|
|
)
|
|
if count == 0 and skipped > 0:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="导入失败:当前仅允许四段格式(账号----密码----手机号----接码链接)",
|
|
)
|
|
return {
|
|
"message": f"成功导入/更新 {count} 个虎牙账号,跳过 {skipped} 条",
|
|
"success": True,
|
|
"count": count,
|
|
"skipped": skipped,
|
|
}
|
|
|
|
|
|
@router.delete("/accounts/batch")
|
|
def delete_accounts_batch(
|
|
account_ids: str = Query(..., description="逗号分隔的虎牙账号ID"),
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""批量删除虎牙 CK 账号及任务记录。"""
|
|
_require_huya_perm(current, "huya:delete")
|
|
ids = [int(x) for x in account_ids.split(",") if x.strip().isdigit()]
|
|
if not ids:
|
|
raise HTTPException(status_code=400, detail="无效的账号ID")
|
|
ids = _selected_huya_account_ids(db, current, AccountBulkSelection(account_ids=ids))
|
|
if not ids:
|
|
raise HTTPException(status_code=400, detail="请选择虎牙账号")
|
|
db.query(HuyaTask).filter(HuyaTask.account_id.in_(ids)).delete(
|
|
synchronize_session=False
|
|
)
|
|
db.query(HuyaWorkbenchAccount).filter(
|
|
HuyaWorkbenchAccount.account_id.in_(ids)
|
|
).delete(synchronize_session=False)
|
|
_clear_huya_account_references(db, ids)
|
|
deleted = (
|
|
db.query(HuyaAccount)
|
|
.filter(HuyaAccount.id.in_(ids))
|
|
.delete(synchronize_session=False)
|
|
)
|
|
db.commit()
|
|
return {
|
|
"message": f"已删除 {deleted} 个虎牙账号",
|
|
"deleted": deleted,
|
|
"success": True,
|
|
}
|
|
|
|
|
|
@router.post("/accounts/batch-delete")
|
|
def delete_accounts_batch_selection(
|
|
req: AccountBulkSelection,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""按显式选择或当前筛选结果批量删除虎牙账号及任务记录。"""
|
|
_require_huya_perm(current, "huya:delete")
|
|
ids = _selected_huya_account_ids(db, current, req)
|
|
if not ids:
|
|
raise HTTPException(status_code=400, detail="请选择虎牙账号")
|
|
db.query(HuyaTask).filter(HuyaTask.account_id.in_(ids)).delete(
|
|
synchronize_session=False
|
|
)
|
|
db.query(HuyaWorkbenchAccount).filter(
|
|
HuyaWorkbenchAccount.account_id.in_(ids)
|
|
).delete(synchronize_session=False)
|
|
_clear_huya_account_references(db, ids)
|
|
deleted = (
|
|
db.query(HuyaAccount)
|
|
.filter(HuyaAccount.id.in_(ids))
|
|
.delete(synchronize_session=False)
|
|
)
|
|
db.commit()
|
|
scope = "当前筛选下" if req.all_matching else "选中的"
|
|
return {
|
|
"message": f"已删除{scope} {deleted} 个虎牙账号",
|
|
"deleted": deleted,
|
|
"success": True,
|
|
}
|
|
|
|
|
|
@router.delete("/accounts/{account_id}")
|
|
def delete_account(
|
|
account_id: int,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""删除单个虎牙 CK 账号。"""
|
|
_require_huya_perm(current, "huya:delete")
|
|
account = db.query(HuyaAccount).filter(HuyaAccount.id == account_id).first()
|
|
if not account:
|
|
raise HTTPException(status_code=404, detail="账号不存在")
|
|
db.query(HuyaTask).filter(HuyaTask.account_id == account_id).delete(
|
|
synchronize_session=False
|
|
)
|
|
db.query(HuyaWorkbenchAccount).filter(
|
|
HuyaWorkbenchAccount.account_id == account_id
|
|
).delete(synchronize_session=False)
|
|
_clear_huya_account_references(db, [account_id])
|
|
db.delete(account)
|
|
db.commit()
|
|
return {"message": "已删除", "success": True}
|
|
|
|
|
|
@router.put("/accounts/{account_id}/assign")
|
|
def assign_account(
|
|
account_id: int,
|
|
req: AccountAssign,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""分配单个虎牙账号给客服。"""
|
|
_require_huya_perm(current, "huya:assign")
|
|
account = db.query(HuyaAccount).filter(HuyaAccount.id == account_id).first()
|
|
if not account:
|
|
raise HTTPException(status_code=404, detail="账号不存在")
|
|
if req.assigned_to:
|
|
target = db.query(User).filter(User.id == req.assigned_to).first()
|
|
if not target:
|
|
raise HTTPException(status_code=404, detail="目标用户不存在")
|
|
if target.role != "support":
|
|
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
|
account.assigned_to = req.assigned_to
|
|
db.commit()
|
|
return {"message": "已分配", "success": True}
|
|
|
|
|
|
@router.post("/accounts/batch-assign")
|
|
def batch_assign_accounts(
|
|
req: BatchAssign,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""批量分配/取消分配虎牙账号给客服。"""
|
|
_require_huya_perm(current, "huya:assign")
|
|
if not req.account_ids:
|
|
raise HTTPException(status_code=400, detail="请选择账号")
|
|
if req.assigned_to is not None:
|
|
target = db.query(User).filter(User.id == req.assigned_to).first()
|
|
if not target:
|
|
raise HTTPException(status_code=404, detail="目标用户不存在")
|
|
if target.role != "support":
|
|
raise HTTPException(status_code=400, detail="只能分配给客服角色")
|
|
|
|
count = (
|
|
db.query(HuyaAccount)
|
|
.filter(HuyaAccount.id.in_(req.account_ids))
|
|
.update(
|
|
{HuyaAccount.assigned_to: req.assigned_to},
|
|
synchronize_session=False,
|
|
)
|
|
)
|
|
db.commit()
|
|
action = "分配" if req.assigned_to else "取消分配"
|
|
return {
|
|
"message": f"已批量{action} {count} 个虎牙账号",
|
|
"success": True,
|
|
"count": count,
|
|
}
|
|
|
|
|
|
@router.get("/accounts/assignments/summary")
|
|
def assignments_summary(
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""虎牙分配概览:每个客服分配了多少虎牙账号。"""
|
|
_require_huya_perm(current, "huya:assign")
|
|
results = (
|
|
db.query(User.id, User.username, func.count(HuyaAccount.id).label("count"))
|
|
.outerjoin(HuyaAccount, HuyaAccount.assigned_to == User.id)
|
|
.filter(User.role == "support")
|
|
.group_by(User.id, User.username)
|
|
.order_by(func.count(HuyaAccount.id).desc())
|
|
.all()
|
|
)
|
|
total_unassigned = (
|
|
db.query(func.count(HuyaAccount.id))
|
|
.filter(HuyaAccount.assigned_to.is_(None))
|
|
.scalar()
|
|
) or 0
|
|
return {
|
|
"support_users": [
|
|
{"id": uid, "username": uname, "assigned_count": cnt}
|
|
for uid, uname, cnt in results
|
|
],
|
|
"unassigned_count": total_unassigned,
|
|
}
|
|
|
|
|
|
@router.put("/accounts/{account_id}/tag")
|
|
def set_account_tag(
|
|
account_id: int,
|
|
req: AccountTag,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""设置单个虎牙账号标签。"""
|
|
_require_huya_tag_permission(current)
|
|
account = (
|
|
_visible_huya_accounts_query(db, current)
|
|
.filter(HuyaAccount.id == account_id)
|
|
.first()
|
|
)
|
|
if not account:
|
|
raise HTTPException(status_code=404, detail="账号不存在")
|
|
account.tag = (req.tag or "").strip()
|
|
db.commit()
|
|
return {"message": "标签已更新", "success": True}
|
|
|
|
|
|
@router.put("/accounts/batch-tag")
|
|
def batch_tag(
|
|
req: AccountTag,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""批量设置虎牙账号标签。"""
|
|
_require_huya_tag_permission(current)
|
|
if not req.account_ids:
|
|
raise HTTPException(status_code=400, detail="请选择账号")
|
|
tag = (req.tag or "").strip()
|
|
count = (
|
|
_visible_huya_accounts_query(db, current)
|
|
.filter(HuyaAccount.id.in_(req.account_ids))
|
|
.update(
|
|
{HuyaAccount.tag: tag},
|
|
synchronize_session=False,
|
|
)
|
|
)
|
|
db.commit()
|
|
return {
|
|
"message": f"已为 {count} 个虎牙账号设置标签",
|
|
"success": True,
|
|
"count": count,
|
|
}
|
|
|
|
|
|
@router.put("/accounts/batch-tag-selection")
|
|
def batch_tag_selection(
|
|
req: AccountBulkTag,
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""按显式选择或当前筛选结果批量设置虎牙账号标签。"""
|
|
_require_huya_tag_permission(current)
|
|
ids = _selected_huya_account_ids(db, current, req)
|
|
if not ids:
|
|
raise HTTPException(status_code=400, detail="请选择虎牙账号")
|
|
tag = (req.tag_value or "").strip()
|
|
count = (
|
|
_visible_huya_accounts_query(db, current)
|
|
.filter(HuyaAccount.id.in_(ids))
|
|
.update(
|
|
{HuyaAccount.tag: tag},
|
|
synchronize_session=False,
|
|
)
|
|
)
|
|
db.commit()
|
|
scope = "当前筛选下" if req.all_matching else "选中的"
|
|
return {
|
|
"message": f"已为{scope} {count} 个虎牙账号设置标签",
|
|
"success": True,
|
|
"count": count,
|
|
}
|
|
|
|
|
|
@router.get("/accounts/tags/list")
|
|
def list_tags(
|
|
db: Session = Depends(get_db),
|
|
current: User = Depends(get_current_user),
|
|
):
|
|
"""获取虎牙账号标签列表。"""
|
|
tag_query = db.query(HuyaAccount.tag)
|
|
if not _can_view_huya_all(current):
|
|
if _can_view_huya_assigned(current):
|
|
tag_query = tag_query.filter(HuyaAccount.assigned_to == current.id)
|
|
else:
|
|
raise HTTPException(status_code=403, detail="无权查看虎牙账号")
|
|
tags = (
|
|
tag_query.filter(HuyaAccount.tag != "", HuyaAccount.tag.isnot(None))
|
|
.distinct()
|
|
.all()
|
|
)
|
|
return [item[0] for item in tags if item[0]]
|