实现虎牙密码登录
This commit is contained in:
@@ -7,6 +7,8 @@ from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from core.huya import HuyaCredentialError, HuyaLoginError, login_huya_password
|
||||
|
||||
from ..database import SessionLocal, get_db
|
||||
from ..deps import authenticate_websocket, require_permission
|
||||
from ..models import HuyaAccount, HuyaConfig, HuyaGoodsSnapshot, HuyaRechargeGoodsSnapshot, HuyaTask, User
|
||||
@@ -16,6 +18,7 @@ from ..schemas import (
|
||||
HuyaConfigUpdate,
|
||||
HuyaCookieImport,
|
||||
HuyaGoodsOut,
|
||||
HuyaPasswordLoginRequest,
|
||||
HuyaRechargeGoodsOut,
|
||||
HuyaTaskBatchRequest,
|
||||
HuyaTaskOut,
|
||||
@@ -28,6 +31,7 @@ from ..services.huya_service import (
|
||||
ensure_huya_config,
|
||||
huya_config_value,
|
||||
import_huya_cookies,
|
||||
upsert_huya_cookie,
|
||||
)
|
||||
from ..services.huya_runner import HuyaBatchRunner, huya_batch_registry
|
||||
|
||||
@@ -130,6 +134,41 @@ def import_cookies(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/accounts/password-login")
|
||||
def password_login_account(
|
||||
req: HuyaPasswordLoginRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("huya:account")),
|
||||
):
|
||||
"""使用账号密码登录虎牙,成功后保存 Cookie。"""
|
||||
try:
|
||||
result = login_huya_password(
|
||||
username=req.username.strip(),
|
||||
password=req.password,
|
||||
cookie=req.cookie.strip() or None,
|
||||
)
|
||||
except HuyaCredentialError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except HuyaLoginError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=f"虎牙密码登录失败: {exc}") from exc
|
||||
|
||||
if not result.success or not result.cookie:
|
||||
raise HTTPException(status_code=502, detail=result.message or "虎牙密码登录失败")
|
||||
|
||||
try:
|
||||
account = upsert_huya_cookie(db, result.cookie, tag=req.tag, username_hint=req.username)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return {
|
||||
"message": "登录成功,Cookie 已保存",
|
||||
"success": True,
|
||||
"account": _account_out(account),
|
||||
"sdid": result.sdid,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/accounts/batch")
|
||||
def delete_accounts_batch(
|
||||
account_ids: str = Query(..., description="逗号分隔的虎牙账号ID"),
|
||||
|
||||
@@ -175,6 +175,14 @@ class HuyaCookieImport(BaseModel):
|
||||
tag: str = ""
|
||||
|
||||
|
||||
class HuyaPasswordLoginRequest(BaseModel):
|
||||
"""虎牙账号密码登录并保存 Cookie。"""
|
||||
username: str = Field(..., min_length=1, max_length=128)
|
||||
password: str = Field(..., min_length=1, max_length=128)
|
||||
tag: str = ""
|
||||
cookie: str = ""
|
||||
|
||||
|
||||
class HuyaAccountOut(BaseModel):
|
||||
id: int
|
||||
uid: str = ""
|
||||
|
||||
@@ -97,6 +97,50 @@ def parse_huya_cookie_line(line: str) -> dict | None:
|
||||
}
|
||||
|
||||
|
||||
def _upsert_huya_account(db: Session, parsed: dict, tag: str = "", status: str | None = None) -> HuyaAccount:
|
||||
"""按 uid/yyuid 新增或更新虎牙账号。"""
|
||||
account = None
|
||||
if parsed["uid"]:
|
||||
account = db.query(HuyaAccount).filter(HuyaAccount.uid == parsed["uid"]).first()
|
||||
if account is None and parsed["yyuid"]:
|
||||
account = db.query(HuyaAccount).filter(HuyaAccount.yyuid == parsed["yyuid"]).first()
|
||||
|
||||
if account is None:
|
||||
account = HuyaAccount(
|
||||
uid=parsed["uid"],
|
||||
yyuid=parsed["yyuid"],
|
||||
username=parsed["username"],
|
||||
cookie=parsed["cookie"],
|
||||
game_phone=parsed["game_phone"],
|
||||
tag=tag,
|
||||
status=status or "imported",
|
||||
)
|
||||
db.add(account)
|
||||
else:
|
||||
account.uid = parsed["uid"] or account.uid
|
||||
account.yyuid = parsed["yyuid"] or account.yyuid
|
||||
account.username = parsed["username"] or account.username
|
||||
account.cookie = parsed["cookie"]
|
||||
account.game_phone = parsed["game_phone"] or account.game_phone
|
||||
if tag:
|
||||
account.tag = tag
|
||||
account.status = status or "updated"
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
return account
|
||||
|
||||
|
||||
def upsert_huya_cookie(db: Session, cookie: str, tag: str = "", username_hint: str = "") -> HuyaAccount:
|
||||
"""保存单条登录得到的虎牙 Cookie。"""
|
||||
line = f"{username_hint}----{cookie}" if username_hint else cookie
|
||||
parsed = parse_huya_cookie_line(line)
|
||||
if not parsed:
|
||||
raise ValueError("登录成功但 Cookie 中没有识别到虎牙 uid")
|
||||
account = _upsert_huya_account(db, parsed, tag=(tag or "").strip(), status="login_success")
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def import_huya_cookies(db: Session, text: str, tag: str = "") -> tuple[int, int]:
|
||||
"""导入虎牙 Cookie,返回 (成功数, 跳过数)。"""
|
||||
created_or_updated = 0
|
||||
@@ -109,34 +153,7 @@ def import_huya_cookies(db: Session, text: str, tag: str = "") -> tuple[int, int
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
account = None
|
||||
if parsed["uid"]:
|
||||
account = db.query(HuyaAccount).filter(HuyaAccount.uid == parsed["uid"]).first()
|
||||
if account is None and parsed["yyuid"]:
|
||||
account = db.query(HuyaAccount).filter(HuyaAccount.yyuid == parsed["yyuid"]).first()
|
||||
|
||||
if account is None:
|
||||
account = HuyaAccount(
|
||||
uid=parsed["uid"],
|
||||
yyuid=parsed["yyuid"],
|
||||
username=parsed["username"],
|
||||
cookie=parsed["cookie"],
|
||||
game_phone=parsed["game_phone"],
|
||||
tag=tag,
|
||||
status="imported",
|
||||
)
|
||||
db.add(account)
|
||||
else:
|
||||
account.uid = parsed["uid"] or account.uid
|
||||
account.yyuid = parsed["yyuid"] or account.yyuid
|
||||
account.username = parsed["username"] or account.username
|
||||
account.cookie = parsed["cookie"]
|
||||
account.game_phone = parsed["game_phone"] or account.game_phone
|
||||
if tag:
|
||||
account.tag = tag
|
||||
account.status = "updated"
|
||||
account.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
_upsert_huya_account(db, parsed, tag=tag)
|
||||
created_or_updated += 1
|
||||
|
||||
if created_or_updated:
|
||||
|
||||
Reference in New Issue
Block a user