feat(weibo): 拆分账号管理与个人工作台

This commit is contained in:
yml2213
2026-11-08 16:26:53 +08:00
parent 5d6325d74c
commit d566518478
13 changed files with 1307 additions and 93 deletions
@@ -0,0 +1,64 @@
"""增加微博个人工作台账号映射。"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "20261108_0072"
down_revision: str | None = "20261108_0071"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
inspector = sa.inspect(op.get_bind())
if not inspector.has_table("weibo_workbench_accounts"):
op.create_table(
"weibo_workbench_accounts",
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("account_id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(
["account_id"],
["weibo_accounts.id"],
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
ondelete="CASCADE",
),
sa.UniqueConstraint(
"user_id",
"account_id",
name="uq_weibo_workbench_account",
),
)
inspector = sa.inspect(op.get_bind())
existing_indexes = {
index["name"] for index in inspector.get_indexes("weibo_workbench_accounts")
}
if "ix_weibo_workbench_accounts_user_id" not in existing_indexes:
op.create_index(
"ix_weibo_workbench_accounts_user_id",
"weibo_workbench_accounts",
["user_id"],
)
if "ix_weibo_workbench_accounts_account_id" not in existing_indexes:
op.create_index(
"ix_weibo_workbench_accounts_account_id",
"weibo_workbench_accounts",
["account_id"],
)
def downgrade() -> None:
inspector = sa.inspect(op.get_bind())
if not inspector.has_table("weibo_workbench_accounts"):
return
op.drop_table("weibo_workbench_accounts")
+25
View File
@@ -961,6 +961,31 @@ class WeiboAccount(Base):
)
class WeiboWorkbenchAccount(Base):
"""用户个人微博工作台中的账号选择。"""
__tablename__ = "weibo_workbench_accounts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
)
account_id: Mapped[int] = mapped_column(
ForeignKey("weibo_accounts.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
__table_args__ = (
UniqueConstraint(
"user_id",
"account_id",
name="uq_weibo_workbench_account",
),
)
class WeiboCollabShop(Base):
"""微博外部单协作的店铺字典。"""
+3
View File
@@ -43,6 +43,7 @@ PERMISSIONS = {
"yyb:history": "查看应用宝充值历史",
# 微博微豆
"weibo:view": "查看微博账号",
"weibo:workbench": "使用个人微博工作台",
"weibo:import": "导入/刷新微博 CK",
"weibo:manage": "编辑、停用和启用微博账号",
"weibo:account:ck_export": "复制微博外部 CK 账号的 CK(写剪贴板)",
@@ -114,6 +115,7 @@ ROLE_PERMISSIONS = {
"yyb:manage",
"yyb:history",
"weibo:view",
"weibo:workbench",
"weibo:import",
"weibo:manage",
"weibo:account:ck_export",
@@ -160,6 +162,7 @@ ROLE_PERMISSIONS = {
"yyb:session",
"yyb:history",
"weibo:view",
"weibo:workbench",
"weibo:import",
"weibo:manage",
"weibo:account:ck_export",
+227 -39
View File
@@ -13,9 +13,10 @@ from core.weibo import WeiboAuthError, WeiboError, WeiboExchangeUncertainError
from ..database import get_db
from ..deps import get_current_user
from ..models import User, WeiboAccount
from ..models import User, WeiboAccount, WeiboWorkbenchAccount
from ..permissions import user_has_permission
from ..schemas import (
WeiboAccountBatchTagRequest,
WeiboAccountCkOut,
WeiboAccountDisableRequest,
WeiboAccountOut,
@@ -37,6 +38,7 @@ from ..schemas import (
WeiboPointRecordItem,
WeiboRechargeOrderOut,
WeiboRechargeRequest,
WeiboWorkbenchAccountsRequest,
)
from ..services.audit_service import record_audit
from ..services.weibo_service import (
@@ -88,6 +90,57 @@ def _account_out(account: WeiboAccount) -> WeiboAccountOut:
return WeiboAccountOut.model_validate(account)
def _apply_account_filters(
query,
*,
search: str,
bind_status: str,
enabled: bool | None,
):
search_text = _query_str(search)
if search_text:
pattern = f"%{search_text}%"
query = query.filter(
or_(
WeiboAccount.uid.ilike(pattern),
WeiboAccount.nickname.ilike(pattern),
WeiboAccount.game_role_name.ilike(pattern),
WeiboAccount.tag.ilike(pattern),
WeiboAccount.remark.ilike(pattern),
)
)
if isinstance(enabled, bool):
query = query.filter(WeiboAccount.is_enabled.is_(enabled))
bind_value = _query_str(bind_status)
if bind_value == "unbound":
query = query.filter(WeiboAccount.is_bound.is_(False))
elif bind_value == "bound":
query = query.filter(WeiboAccount.is_bound.is_(True))
elif bind_value == "rebindable":
query = query.filter(
WeiboAccount.is_bound.is_(True),
WeiboAccount.can_rebind.is_(True),
)
return query
def _paginated_accounts(query, *, page: int, page_size: int) -> dict:
total = query.order_by(None).count()
rows = (
query.options(defer(WeiboAccount.cookie))
.order_by(WeiboAccount.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"items": [_account_out(account) for account in rows],
"total": total,
"page": page,
"page_size": page_size,
}
def _ensure_enabled(account: WeiboAccount) -> None:
if not account.is_enabled:
raise HTTPException(status_code=409, detail="微博账号已停用,请先启用")
@@ -149,46 +202,181 @@ def list_accounts(
"""查看已导入的微博账号。"""
_require_weibo_perm(current, "weibo:view")
query = db.query(WeiboAccount)
search_text = _query_str(search)
if search_text:
pattern = f"%{search_text}%"
query = query.filter(
or_(
WeiboAccount.uid.ilike(pattern),
WeiboAccount.nickname.ilike(pattern),
WeiboAccount.game_role_name.ilike(pattern),
WeiboAccount.tag.ilike(pattern),
WeiboAccount.remark.ilike(pattern),
)
)
if isinstance(enabled, bool):
query = query.filter(WeiboAccount.is_enabled.is_(enabled))
bind_value = _query_str(bind_status)
if bind_value == "unbound":
query = query.filter(WeiboAccount.is_bound.is_(False))
elif bind_value == "bound":
query = query.filter(WeiboAccount.is_bound.is_(True))
elif bind_value == "rebindable":
query = query.filter(
WeiboAccount.is_bound.is_(True),
WeiboAccount.can_rebind.is_(True),
)
total = query.count()
rows = (
query.options(defer(WeiboAccount.cookie))
.order_by(WeiboAccount.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
query = _apply_account_filters(
db.query(WeiboAccount),
search=search,
bind_status=bind_status,
enabled=enabled,
)
return {
"items": [_account_out(account) for account in rows],
"total": total,
"page": page,
"page_size": page_size,
return _paginated_accounts(query, page=page, page_size=page_size)
@router.get("/workbench/accounts")
def list_workbench_accounts(
search: str = Query(""),
bind_status: str = Query(""),
enabled: bool | None = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""查看当前用户个人工作台中的微博账号。"""
_require_weibo_perm(current, "weibo:workbench")
query = (
db.query(WeiboAccount)
.join(
WeiboWorkbenchAccount,
WeiboWorkbenchAccount.account_id == WeiboAccount.id,
)
.filter(WeiboWorkbenchAccount.user_id == current.id)
)
query = _apply_account_filters(
query,
search=search,
bind_status=bind_status,
enabled=enabled,
)
return _paginated_accounts(query, page=page, page_size=page_size)
@router.get("/workbench/pool")
def list_workbench_pool(
search: str = Query(""),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""查看可加入当前用户工作台、且尚未加入的账号池账号。"""
_require_weibo_perm(current, "weibo:workbench")
selected = db.query(WeiboWorkbenchAccount.account_id).filter(
WeiboWorkbenchAccount.user_id == current.id
)
query = _apply_account_filters(
db.query(WeiboAccount).filter(WeiboAccount.id.not_in(selected)),
search=search,
bind_status="",
enabled=True,
)
return _paginated_accounts(query, page=page, page_size=page_size)
@router.post("/workbench/accounts")
def add_workbench_accounts(
req: WeiboWorkbenchAccountsRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""把账号池账号加入当前用户的工作台。"""
_require_weibo_perm(current, "weibo:workbench")
account_ids = sorted(
{account_id for account_id in req.account_ids if account_id > 0}
)
if not account_ids:
raise HTTPException(status_code=400, detail="请先选择账号")
existing_ids = {
account_id
for (account_id,) in db.query(WeiboAccount.id)
.filter(WeiboAccount.id.in_(account_ids))
.all()
}
missing = sorted(set(account_ids) - existing_ids)
if missing:
raise HTTPException(status_code=404, detail=f"账号不存在: {missing}")
selected_ids = {
account_id
for (account_id,) in db.query(WeiboWorkbenchAccount.account_id)
.filter(
WeiboWorkbenchAccount.user_id == current.id,
WeiboWorkbenchAccount.account_id.in_(account_ids),
)
.all()
}
db.add_all(
[
WeiboWorkbenchAccount(user_id=current.id, account_id=account_id)
for account_id in account_ids
if account_id not in selected_ids
]
)
db.commit()
_record_audit_safely(
db,
current,
action="weibo:workbench:add",
target=f"weibo_user:{current.id}",
detail={"account_ids": account_ids},
)
return {"account_ids": account_ids, "success": True}
@router.post("/workbench/accounts/remove")
def remove_workbench_accounts(
req: WeiboWorkbenchAccountsRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""从当前用户工作台移出账号,不影响账号池和其他用户。"""
_require_weibo_perm(current, "weibo:workbench")
account_ids = sorted(
{account_id for account_id in req.account_ids if account_id > 0}
)
if not account_ids:
raise HTTPException(status_code=400, detail="请先选择账号")
db.query(WeiboWorkbenchAccount).filter(
WeiboWorkbenchAccount.user_id == current.id,
WeiboWorkbenchAccount.account_id.in_(account_ids),
).delete(synchronize_session=False)
db.commit()
_record_audit_safely(
db,
current,
action="weibo:workbench:remove",
target=f"weibo_user:{current.id}",
detail={"account_ids": account_ids},
)
return {"account_ids": account_ids, "success": True}
@router.post("/accounts/batch-tag")
def batch_tag_accounts(
req: WeiboAccountBatchTagRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""批量设置微博账号标签。"""
_require_weibo_perm(current, "weibo:manage")
account_ids = sorted(set(req.ids))
if not account_ids:
raise HTTPException(status_code=400, detail="请先选择账号")
accounts = db.query(WeiboAccount).filter(WeiboAccount.id.in_(account_ids)).all()
actual_ids = {account.id for account in accounts}
missing = sorted(set(account_ids) - actual_ids)
if missing:
raise HTTPException(status_code=404, detail=f"账号不存在: {missing}")
tag = req.tag.strip()
previous = {account.id: account.tag or "" for account in accounts}
for account in accounts:
account.tag = tag
db.commit()
_record_audit_safely(
db,
current,
action="weibo:account:batch_tag",
target=f"weibo_accounts:{len(account_ids)}",
detail={
"account_ids": account_ids,
"tag": tag,
"previous_tags": previous,
},
)
return {"updated": len(accounts), "tag": tag, "success": True}
@router.get("/accounts/{account_id}", response_model=WeiboAccountOut)
+9
View File
@@ -505,6 +505,15 @@ class WeiboAccountUpdate(BaseModel):
remark: str | None = Field(None, max_length=256)
class WeiboAccountBatchTagRequest(BaseModel):
ids: list[int] = Field(min_length=1)
tag: str = Field("", max_length=64)
class WeiboWorkbenchAccountsRequest(BaseModel):
account_ids: list[int] = Field(default_factory=list)
class WeiboAccountDisableRequest(BaseModel):
reason: str = Field("", max_length=256)