feat(weibo): 增加工作台批量充值与批量导入

This commit is contained in:
yml
2026-11-11 20:11:35 +08:00
parent c9814ab4d2
commit 50bb829101
9 changed files with 1353 additions and 60 deletions
+174
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import os
import re
from fastapi import APIRouter, Depends, HTTPException, Query
from loguru import logger
@@ -41,6 +42,9 @@ from ..schemas import (
WeiboRechargeOrderOut,
WeiboRechargeRequest,
WeiboWorkbenchAccountsRequest,
WeiboWorkbenchBatchImportItem,
WeiboWorkbenchBatchImportOut,
WeiboWorkbenchBatchImportRequest,
)
from ..services.audit_service import record_audit
from ..services.weibo_service import (
@@ -61,6 +65,7 @@ from ..services.weibo_service import (
router = APIRouter(prefix="/api/weibo", tags=["微博微豆"])
WEIBO_DEFAULT_ACTIVITY = os.getenv("WEIBO_DEFAULT_ACTIVITY", "").strip()
WEIBO_WORKBENCH_BATCH_IMPORT_MAX = 200
def _require_weibo_perm(user: User, permission: str) -> None:
@@ -319,6 +324,175 @@ def list_workbench_pool(
return _paginated_accounts(query, page=page, page_size=page_size)
@router.post(
"/workbench/accounts/batch-import",
response_model=WeiboWorkbenchBatchImportOut,
)
def import_workbench_accounts_by_text(
req: WeiboWorkbenchBatchImportRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""按 UID/用户名/角色批量解析账号并加入当前用户工作台。"""
_require_weibo_perm(current, "weibo:workbench")
identifiers: list[str] = []
for token in re.split(r"[\s,,;;]+", req.text.strip()):
value = token.strip()
if value and value not in identifiers:
identifiers.append(value)
if not identifiers:
raise HTTPException(status_code=400, detail="请先粘贴微博用户名或 UID")
if len(identifiers) > WEIBO_WORKBENCH_BATCH_IMPORT_MAX:
raise HTTPException(
status_code=400,
detail=f"一次最多导入 {WEIBO_WORKBENCH_BATCH_IMPORT_MAX} 个账号",
)
visible_query = _visible_weibo_accounts_query(db.query(WeiboAccount), current)
accounts = visible_query.filter(
or_(
WeiboAccount.uid.in_(identifiers),
WeiboAccount.nickname.in_(identifiers),
WeiboAccount.game_role_name.in_(identifiers),
)
).all()
def grouped(field: str) -> dict[str, list[WeiboAccount]]:
result: dict[str, list[WeiboAccount]] = {}
for account in accounts:
value = str(getattr(account, field) or "").strip()
if value:
result.setdefault(value, []).append(account)
return result
by_uid = grouped("uid")
by_nickname = grouped("nickname")
by_role = grouped("game_role_name")
account_ids = [account.id for account in accounts]
occupancy = {
account_id: user_id
for account_id, user_id in db.query(
WeiboWorkbenchAccount.account_id,
WeiboWorkbenchAccount.user_id,
)
.filter(WeiboWorkbenchAccount.account_id.in_(account_ids))
.all()
}
items: list[WeiboWorkbenchBatchImportItem] = []
to_add: list[WeiboAccount] = []
planned_ids: set[int] = set()
for identifier in identifiers:
candidates = by_uid.get(identifier) or by_nickname.get(identifier) or []
if not candidates:
candidates = by_role.get(identifier) or []
if not candidates:
items.append(
WeiboWorkbenchBatchImportItem(
identifier=identifier,
status="not_found",
message="当前可见账号池中没有匹配项",
)
)
continue
if len(candidates) > 1 and identifier not in by_uid:
items.append(
WeiboWorkbenchBatchImportItem(
identifier=identifier,
status="ambiguous",
message=f"匹配到 {len(candidates)} 个账号,请改用 UID",
)
)
continue
account = candidates[0]
base = {
"identifier": identifier,
"account_id": account.id,
"uid": account.uid,
"nickname": account.nickname,
}
occupant = occupancy.get(account.id)
if not account.is_enabled:
items.append(
WeiboWorkbenchBatchImportItem(
status="disabled",
message="账号已停用",
**base,
)
)
elif occupant is not None and occupant != current.id:
items.append(
WeiboWorkbenchBatchImportItem(
status="unavailable",
message="账号已在其他人的工作台中使用",
**base,
)
)
elif occupant == current.id:
items.append(
WeiboWorkbenchBatchImportItem(
status="already_added",
message="账号已在本工作台",
**base,
)
)
elif account.id in planned_ids:
items.append(
WeiboWorkbenchBatchImportItem(
status="duplicate",
message="同一账号在本次名单中重复",
**base,
)
)
else:
planned_ids.add(account.id)
to_add.append(account)
items.append(
WeiboWorkbenchBatchImportItem(
status="added",
message="已加入工作台",
**base,
)
)
try:
db.add_all(
[
WeiboWorkbenchAccount(user_id=current.id, account_id=account.id)
for account in to_add
]
)
db.commit()
except IntegrityError as exc:
db.rollback()
raise HTTPException(
status_code=409,
detail="部分账号刚被其他工作台占用,请刷新后重试",
) from exc
if to_add:
_record_audit_safely(
db,
current,
action="weibo:workbench:batch_import",
target=f"weibo_user:{current.id}",
detail={"account_ids": [account.id for account in to_add]},
)
added = sum(item.status == "added" for item in items)
already_added = sum(item.status == "already_added" for item in items)
failed = len(items) - added - already_added
return WeiboWorkbenchBatchImportOut(
requested=len(identifiers),
added=added,
already_added=already_added,
failed=failed,
account_ids=[account.id for account in to_add],
items=items,
)
@router.get("/workbench/tags")
def list_workbench_tags(
db: Session = Depends(get_db),
+22
View File
@@ -521,6 +521,28 @@ class WeiboWorkbenchAccountsRequest(BaseModel):
account_ids: list[int] = Field(default_factory=list)
class WeiboWorkbenchBatchImportRequest(BaseModel):
text: str = Field(..., min_length=1, max_length=100_000)
class WeiboWorkbenchBatchImportItem(BaseModel):
identifier: str
status: str
message: str = ""
account_id: int | None = None
uid: str = ""
nickname: str = ""
class WeiboWorkbenchBatchImportOut(BaseModel):
requested: int
added: int
already_added: int
failed: int
account_ids: list[int] = Field(default_factory=list)
items: list[WeiboWorkbenchBatchImportItem] = Field(default_factory=list)
class WeiboBatchAssignRequest(BaseModel):
account_ids: list[int] = Field(min_length=1)
assigned_to: int | None = None