feat(fulfillment): 实时刷新斗鱼账号并支持租约时长设置
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""直播账号履约租约时长设置
|
||||
|
||||
默认账号租约无期限;运营可切换为按分钟或小时自动过期。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261117_0085"
|
||||
down_revision: str | None = "20261117_0084"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _table_exists(table: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"SELECT COUNT(*) FROM information_schema.tables "
|
||||
"WHERE table_schema = DATABASE() AND table_name = :table"
|
||||
),
|
||||
{"table": table},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.alter_column(
|
||||
"account_leases",
|
||||
"expires_at",
|
||||
existing_type=sa.DateTime(),
|
||||
nullable=True,
|
||||
)
|
||||
if not _table_exists("platform_fulfillment_settings"):
|
||||
op.create_table(
|
||||
"platform_fulfillment_settings",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("lease_duration_minutes", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_by", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["updated_by"],
|
||||
["users.id"],
|
||||
name="fk_platform_fulfillment_settings_updated_by",
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO platform_fulfillment_settings (
|
||||
id, lease_duration_minutes, updated_by, updated_at
|
||||
) VALUES (1, NULL, NULL, NOW())
|
||||
ON DUPLICATE KEY UPDATE id = id
|
||||
"""
|
||||
)
|
||||
)
|
||||
# 设置上线即默认无限期;正在使用的租约也立即转为无限期,避免几分钟后中断。
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE account_leases
|
||||
SET expires_at = NULL
|
||||
WHERE purpose = 'platform_fulfillment' AND status = 'active'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE account_leases
|
||||
SET expires_at = DATE_ADD(NOW(), INTERVAL 5 MINUTE)
|
||||
WHERE purpose = 'platform_fulfillment'
|
||||
AND status = 'active'
|
||||
AND expires_at IS NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
if _table_exists("platform_fulfillment_settings"):
|
||||
op.drop_table("platform_fulfillment_settings")
|
||||
op.alter_column(
|
||||
"account_leases",
|
||||
"expires_at",
|
||||
existing_type=sa.DateTime(),
|
||||
nullable=False,
|
||||
)
|
||||
+18
-2
@@ -1686,8 +1686,8 @@ class AccountLease(Base):
|
||||
String(16), nullable=False, default="active", server_default="active"
|
||||
)
|
||||
leased_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
# TTL 兜底:进程重启、页面关掉都能靠它把租约收回来。
|
||||
expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False)
|
||||
# 到期时间;NULL 表示按当前设置无限期占用。
|
||||
expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
released_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
release_reason: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
@@ -1713,6 +1713,22 @@ class AccountLease(Base):
|
||||
holder: Mapped[User] = relationship("User")
|
||||
|
||||
|
||||
class PlatformFulfillmentSetting(Base):
|
||||
"""直播账号履约工作台的持久化设置。"""
|
||||
|
||||
__tablename__ = "platform_fulfillment_settings"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
lease_duration_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
updated_by: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
class PlatformCommodityMapping(Base):
|
||||
"""order_site 内部 SKU 到斗鱼商品的显式映射。"""
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from ..schemas import (
|
||||
PlatformFulfillmentCompleteRequest,
|
||||
PlatformFulfillmentMappingUpsert,
|
||||
PlatformFulfillmentReasonRequest,
|
||||
PlatformFulfillmentSettingsUpdate,
|
||||
)
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.platform_fulfillment import service
|
||||
@@ -21,6 +22,37 @@ from ..services.platform_fulfillment import service
|
||||
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
def get_settings(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||
) -> dict[str, Any]:
|
||||
del current
|
||||
return service.get_settings(db)
|
||||
|
||||
|
||||
@router.put("/settings")
|
||||
def update_settings(
|
||||
req: PlatformFulfillmentSettingsUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:admin")),
|
||||
) -> dict[str, Any]:
|
||||
result = service.update_settings(
|
||||
db,
|
||||
lease_duration_minutes=req.lease_duration_minutes,
|
||||
current=current,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="platform_fulfillment:settings:update",
|
||||
target="platform_fulfillment_settings",
|
||||
detail=result,
|
||||
)
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
def list_tasks(
|
||||
status: str = Query("", max_length=32),
|
||||
@@ -174,9 +206,7 @@ def refresh_eligibility(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("platform_fulfillment:use")),
|
||||
) -> dict[str, Any]:
|
||||
result = service.refresh_exchange_eligibility(
|
||||
db, task_id=task_id, current=current
|
||||
)
|
||||
result = service.refresh_exchange_eligibility(db, task_id=task_id, current=current)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
|
||||
@@ -1576,6 +1576,10 @@ class PlatformFulfillmentCompleteRequest(BaseModel):
|
||||
note: str = Field(default="", max_length=1000)
|
||||
|
||||
|
||||
class PlatformFulfillmentSettingsUpdate(BaseModel):
|
||||
lease_duration_minutes: int | None = Field(..., ge=1, le=525600)
|
||||
|
||||
|
||||
class DouyuTaskBatchRequest(BaseModel):
|
||||
account_ids: list[int]
|
||||
task_type: str
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from ..models import Account
|
||||
|
||||
# ── 作用域 ──────────────────────────────────────────────
|
||||
@@ -239,3 +242,37 @@ def derive_from_bind_info(info: dict | None) -> str | None:
|
||||
return BIND_UNBOUND
|
||||
# 接口没给结论:保持 unknown,别把"没查到"写成"没绑定"
|
||||
return None
|
||||
|
||||
|
||||
def is_role_change_cooling(info: dict | None) -> bool:
|
||||
"""是否处于真实换绑冷却:已有绑定角色且当前不可换绑。"""
|
||||
if not isinstance(info, dict):
|
||||
return False
|
||||
role_name = str(info.get("role_name") or info.get("role") or "").strip()
|
||||
if not role_name or not _truthy_flag(info.get("is_bound_act")):
|
||||
return False
|
||||
if str(info.get("api_version") or "") == "esports":
|
||||
can_change_time = _to_int(info.get("can_change_time"))
|
||||
if can_change_time is not None:
|
||||
return can_change_time > int(datetime.now(UTC).timestamp())
|
||||
wait_time = _to_int(info.get("change_role_wait_time"))
|
||||
if wait_time is not None and wait_time > 0:
|
||||
return True
|
||||
if info.get("can_change_role") is not None:
|
||||
return not _truthy_flag(info.get("can_change_role"))
|
||||
return False
|
||||
|
||||
|
||||
def _truthy_flag(value: Any) -> bool:
|
||||
if value is True:
|
||||
return True
|
||||
if value is False or value is None:
|
||||
return False
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "y"}
|
||||
|
||||
|
||||
def _to_int(value: Any) -> int | None:
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@@ -23,24 +23,17 @@ from ...account_value import (
|
||||
high_value_recheck_seconds,
|
||||
value_tier_expr,
|
||||
)
|
||||
from ...cookie_check_service import check_douyu_cookie
|
||||
from ...cookie_check_service import (
|
||||
check_douyu_cookie,
|
||||
)
|
||||
from ...cookie_check_service import (
|
||||
classify_douyu_cookie_result as classify_result,
|
||||
)
|
||||
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
|
||||
|
||||
JOB_KEY = "ck_health"
|
||||
FLUSH_EVERY = 25
|
||||
|
||||
# 斗鱼明确表示「这个 CK 不能用」的说法。只有命中这些才算真的失效。
|
||||
AUTH_FAILURE_MARKERS = (
|
||||
"登陆异常",
|
||||
"登录异常",
|
||||
"未登录",
|
||||
"登陆失效",
|
||||
"登录失效",
|
||||
"重新登陆",
|
||||
"重新登录",
|
||||
"账户登陆",
|
||||
)
|
||||
|
||||
# 非鉴权类失败(网络超时、响应异常、被判风控)占比超过它就自动暂停作业。
|
||||
# 这类失败说明「我们查不到」,不是「这个 CK 失效了」;如果不加区分地写
|
||||
# invalid,斗鱼接口抖动一小时就能把上千个好账号标成失效,客服会误判成
|
||||
@@ -49,22 +42,6 @@ ERROR_PAUSE_RATIO = 0.3
|
||||
ERROR_PAUSE_MIN_SCANNED = 20
|
||||
|
||||
|
||||
def classify_result(result: dict[str, Any]) -> str:
|
||||
"""把检测结果分成三类:valid / invalid(真失效)/ error(查不到)。
|
||||
|
||||
- ``valid``:斗鱼两个接口都通过;
|
||||
- ``invalid``:斗鱼明确回复「未登录 / 登陆异常」之类的鉴权失败;
|
||||
- ``error``:其余失败(请求失败、超时、响应异常、未知结构)——
|
||||
**不能当成失效**,也不覆盖该行原来的结论。
|
||||
"""
|
||||
if result.get("valid"):
|
||||
return "valid"
|
||||
message = str(result.get("message") or "")
|
||||
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
|
||||
return "invalid"
|
||||
return "error"
|
||||
|
||||
|
||||
def _candidates_query(db: Session, job: AutomationJob, now: datetime):
|
||||
"""本轮「待检测账号」的完整候选集(**不带 LIMIT**,供计数复用)。
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ def run_platform_fulfillment_lease_reaper(
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
AccountLease.expires_at.isnot(None),
|
||||
AccountLease.expires_at <= moment,
|
||||
)
|
||||
.limit(max(1, int(job.batch_size or 500)))
|
||||
|
||||
@@ -11,6 +11,27 @@ CHECK_UA = (
|
||||
FISH_BALL_API = "https://www.douyu.com/wjapi/nc/exchange/fishBall"
|
||||
USER_LEVEL_API = "https://www.douyu.com/japi/interactnc/web/userLevel/userLevelDetail"
|
||||
|
||||
AUTH_FAILURE_MARKERS = (
|
||||
"登陆异常",
|
||||
"登录异常",
|
||||
"未登录",
|
||||
"登陆失效",
|
||||
"登录失效",
|
||||
"重新登陆",
|
||||
"重新登录",
|
||||
"账户登陆",
|
||||
)
|
||||
|
||||
|
||||
def classify_douyu_cookie_result(result: dict) -> str:
|
||||
"""把检测结果分成 valid / invalid / error,区分失效与暂时查不到。"""
|
||||
if result.get("valid"):
|
||||
return "valid"
|
||||
message = str(result.get("message") or "")
|
||||
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
|
||||
return "invalid"
|
||||
return "error"
|
||||
|
||||
|
||||
def check_douyu_cookie(cookie: str) -> dict:
|
||||
"""检测斗鱼 Cookie 有效性,鱼丸与等级接口均通过才算有效。"""
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""斗鱼账号实时状态刷新。
|
||||
|
||||
选号不能依赖账号上的缓存字段。只要账号持有 CK,本模块就实时检测 CK、
|
||||
查询精英宝典、积分、限兑商品和绑定冷却,并把结果写回账号生命周期与账号
|
||||
快照。业务调用方只消费返回的实时结论。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account
|
||||
from .account_binding import (
|
||||
SCOPE_ELITE,
|
||||
derive_from_bind_info,
|
||||
is_role_change_cooling,
|
||||
set_bind_status,
|
||||
)
|
||||
from .account_lifecycle import on_ck_verdict
|
||||
from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result
|
||||
from .douyu_activity_query import (
|
||||
activity_client,
|
||||
query_bind_info,
|
||||
query_exchange_eligibility,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DouyuLiveAccountState:
|
||||
account_id: int
|
||||
account_name: str
|
||||
checked_at: datetime
|
||||
ck_verdict: str
|
||||
ck_message: str
|
||||
elite_opened: bool | None
|
||||
points: int | None
|
||||
limited_ids: frozenset[str]
|
||||
role_change_available_at: datetime | None
|
||||
error: str = ""
|
||||
role_change_blocked: bool = False
|
||||
|
||||
def blocking_reasons(
|
||||
self,
|
||||
*,
|
||||
commodity_id: str,
|
||||
) -> list[str]:
|
||||
reasons: list[str] = []
|
||||
if self.ck_verdict != "valid":
|
||||
reasons.append(f"CK {self.ck_verdict}: {self.ck_message}")
|
||||
if self.error:
|
||||
reasons.append(self.error)
|
||||
if commodity_id in self.limited_ids:
|
||||
reasons.append("该商品已达限兑上限")
|
||||
if self.role_change_blocked:
|
||||
available_text = (
|
||||
self.role_change_available_at.isoformat()
|
||||
if self.role_change_available_at
|
||||
else "未知时间"
|
||||
)
|
||||
reasons.append(f"角色换绑冷却至 {available_text}")
|
||||
return reasons
|
||||
|
||||
def soft_requirement_reasons(self, *, required_points: int) -> list[str]:
|
||||
"""积分/开通不淘汰账号,只决定后续需要充值还是开通。"""
|
||||
reasons: list[str] = []
|
||||
if self.elite_opened is not True:
|
||||
reasons.append("精英宝典未开通")
|
||||
if self.points is None or self.points < required_points:
|
||||
reasons.append(f"积分不足({self.points or 0}/{required_points})")
|
||||
return reasons
|
||||
|
||||
def readiness_rank(self, *, required_points: int) -> int:
|
||||
"""数值越小越接近直接兑换,用于软条件排序。"""
|
||||
opened = self.elite_opened is True
|
||||
enough = self.points is not None and self.points >= required_points
|
||||
if opened and enough:
|
||||
return 0
|
||||
if opened:
|
||||
return 1
|
||||
if enough:
|
||||
return 2
|
||||
return 3
|
||||
|
||||
|
||||
def refresh_douyu_account_state(
|
||||
db: Session,
|
||||
account: Account,
|
||||
*,
|
||||
manual_id: str,
|
||||
rid: str,
|
||||
act_alias: str,
|
||||
client: DouyuActivityClient | None = None,
|
||||
cookie_checker: Callable[[str], dict[str, Any]] = check_douyu_cookie,
|
||||
commit: bool = True,
|
||||
) -> DouyuLiveAccountState:
|
||||
"""实时刷新单个账号,并把所有可落库状态写回账号。"""
|
||||
now = datetime.now(UTC)
|
||||
cookie = str(account.cookie or "").strip()
|
||||
account_name = account.nickname or account.username or f"#{account.id}"
|
||||
ck_result = cookie_checker(cookie)
|
||||
ck_verdict = classify_douyu_cookie_result(ck_result)
|
||||
ck_message = str(ck_result.get("message") or "")
|
||||
on_ck_verdict(
|
||||
db,
|
||||
account,
|
||||
ck_verdict,
|
||||
detail=ck_result,
|
||||
occurred_at=now,
|
||||
)
|
||||
|
||||
if ck_verdict != "valid":
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": ["CK 检测未通过,未继续查询活动状态"],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
)
|
||||
|
||||
active_client = client or activity_client(cookie)
|
||||
try:
|
||||
eligibility = query_exchange_eligibility(
|
||||
active_client,
|
||||
cookie=cookie,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
uid=str(account.uid or ""),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要保留单项诊断
|
||||
error = f"{type(exc).__name__}: {exc}"[:240]
|
||||
snapshot = {
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"errors": [error],
|
||||
}
|
||||
account.overview_snapshot = _json_safe(snapshot)
|
||||
account.overview_queried_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=account.elite_opened,
|
||||
points=account.points,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
error=error,
|
||||
)
|
||||
|
||||
errors: list[str] = []
|
||||
bind_info: dict[str, Any] = {}
|
||||
try:
|
||||
bind_info = query_bind_info(
|
||||
active_client,
|
||||
act_alias=act_alias,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 绑定查询失败不应丢弃资产查询结果
|
||||
errors.append(f"绑定状态查询失败: {type(exc).__name__}: {exc}"[:240])
|
||||
|
||||
elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
|
||||
elite_expire_time = _to_int(eligibility.elite_user_info.get("expire_time"))
|
||||
account.elite_opened = elite_opened
|
||||
account.elite_expire_time = elite_expire_time or None
|
||||
account.points = eligibility.points
|
||||
account.points_expire_at = _points_expire_at(
|
||||
eligibility.points_response,
|
||||
checked_at=now,
|
||||
)
|
||||
role_change_available_at = account.role_change_available_at
|
||||
if bind_info:
|
||||
role_change_available_at = _apply_bind_state(
|
||||
account,
|
||||
bind_info,
|
||||
checked_at=now,
|
||||
)
|
||||
account.overview_snapshot = _json_safe(
|
||||
{
|
||||
"queried_at": now.isoformat(),
|
||||
"ck": ck_result,
|
||||
"elite": eligibility.elite_user_info,
|
||||
"points": eligibility.points_response,
|
||||
"limited_goods": eligibility.limited_goods,
|
||||
"bind": bind_info,
|
||||
"errors": errors,
|
||||
}
|
||||
)
|
||||
account.overview_queried_at = now
|
||||
account.high_value_checked_at = now
|
||||
account.updated_at = now
|
||||
if commit:
|
||||
db.commit()
|
||||
|
||||
return DouyuLiveAccountState(
|
||||
account_id=int(account.id),
|
||||
account_name=account_name,
|
||||
checked_at=now,
|
||||
ck_verdict=ck_verdict,
|
||||
ck_message=ck_message,
|
||||
elite_opened=elite_opened,
|
||||
points=eligibility.points,
|
||||
limited_ids=eligibility.limited_ids,
|
||||
role_change_available_at=role_change_available_at,
|
||||
error=";".join(errors),
|
||||
role_change_blocked=is_role_change_cooling(bind_info),
|
||||
)
|
||||
|
||||
|
||||
def _apply_bind_state(
|
||||
account: Account,
|
||||
bind_info: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
derived = derive_from_bind_info(bind_info)
|
||||
if derived is not None:
|
||||
set_bind_status(account, SCOPE_ELITE, derived)
|
||||
|
||||
role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip()
|
||||
if role_name:
|
||||
account.game_name = role_name[:128]
|
||||
area_name = str(bind_info.get("area_name") or "").strip()
|
||||
plat_name = str(bind_info.get("plat_name") or "").strip()
|
||||
channel = " · ".join(item for item in (area_name, plat_name) if item)
|
||||
if channel:
|
||||
account.game_channel = channel[:128]
|
||||
|
||||
wait_seconds = _to_int(bind_info.get("change_role_wait_time"))
|
||||
can_change_time = _to_int(bind_info.get("can_change_time"))
|
||||
account.change_role_wait_time = wait_seconds
|
||||
if not is_role_change_cooling(bind_info):
|
||||
available_at = None
|
||||
elif can_change_time is not None and can_change_time > 0:
|
||||
available_at = datetime.fromtimestamp(can_change_time, tz=UTC)
|
||||
elif wait_seconds is not None and wait_seconds > 0:
|
||||
available_at = checked_at + timedelta(seconds=wait_seconds)
|
||||
else:
|
||||
available_at = account.role_change_available_at
|
||||
account.role_change_available_at = available_at
|
||||
return available_at
|
||||
|
||||
|
||||
def _points_expire_at(
|
||||
points_response: dict[str, Any],
|
||||
*,
|
||||
checked_at: datetime,
|
||||
) -> datetime | None:
|
||||
raw = (
|
||||
points_response.get("willExpireTime")
|
||||
or points_response.get("will_expire_time")
|
||||
or points_response.get("expire_time")
|
||||
)
|
||||
value = _to_int(raw)
|
||||
if value is None or value <= 0:
|
||||
return None
|
||||
if value > 10_000_000_000:
|
||||
value //= 1000
|
||||
if value < int(checked_at.timestamp()) - 60:
|
||||
return None
|
||||
return datetime.fromtimestamp(value, tz=UTC)
|
||||
|
||||
|
||||
def _to_int(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _json_safe(value: Any) -> Any:
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat()
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json_safe(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple, set, frozenset)):
|
||||
return [_json_safe(item) for item in value]
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DouyuLiveAccountState",
|
||||
"refresh_douyu_account_state",
|
||||
]
|
||||
@@ -206,6 +206,7 @@ def query_exchange_orders(
|
||||
class DouyuEligibilityResult:
|
||||
elite_user_info: dict[str, Any]
|
||||
points: int
|
||||
points_response: dict[str, Any]
|
||||
limited_goods: list[dict[str, Any]]
|
||||
limited_ids: frozenset[str]
|
||||
|
||||
@@ -232,6 +233,7 @@ def query_exchange_eligibility(
|
||||
return DouyuEligibilityResult(
|
||||
elite_user_info=elite,
|
||||
points=int(points_result.get("points") or 0),
|
||||
points_response=points_result,
|
||||
limited_goods=limited,
|
||||
limited_ids=frozenset(limited_ids),
|
||||
)
|
||||
|
||||
@@ -17,6 +17,7 @@ from .account_binding import (
|
||||
BIND_UNBOUND,
|
||||
SCOPE_ELITE,
|
||||
SCOPE_ESPORTS,
|
||||
is_role_change_cooling,
|
||||
set_bind_status,
|
||||
)
|
||||
from .business_events import record_bind
|
||||
@@ -148,12 +149,7 @@ class BindMixin:
|
||||
@classmethod
|
||||
def _is_change_cooling(cls, bind_info: dict | None) -> bool:
|
||||
"""是否处于换绑冷却:已有绑定角色且当前不可换绑。"""
|
||||
if not bind_info:
|
||||
return False
|
||||
role_name = str(bind_info.get("role_name") or "").strip()
|
||||
if not role_name or not cls._is_bound_act(bind_info):
|
||||
return False
|
||||
return not cls._can_change_role(bind_info)
|
||||
return is_role_change_cooling(bind_info)
|
||||
|
||||
@classmethod
|
||||
def _is_pending_role(
|
||||
|
||||
@@ -14,6 +14,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models import Account, AccountEvent, AccountLease, User
|
||||
from ..account_lifecycle import MANUAL_STATES
|
||||
|
||||
VALIDATION_LEASE_MINUTES = 5
|
||||
BINDING_LEASE_MINUTES = 120
|
||||
@@ -109,6 +110,62 @@ def eligible_accounts(
|
||||
]
|
||||
|
||||
|
||||
def live_candidate_accounts(
|
||||
db: Session,
|
||||
*,
|
||||
limit: int = 20,
|
||||
) -> list[Account]:
|
||||
"""选出值得实时检测的账号,不读取 CK/积分/开通等缓存结论。"""
|
||||
owner_ids = select(User.id).where(User.role.in_(POOL_OWNER_ROLES))
|
||||
active_lease = (
|
||||
select(AccountLease.id)
|
||||
.where(AccountLease.active_account_id == Account.id)
|
||||
.exists()
|
||||
)
|
||||
return (
|
||||
db.query(Account)
|
||||
.filter(
|
||||
Account.cookie.isnot(None),
|
||||
Account.cookie != "",
|
||||
Account.auto_managed.is_(True),
|
||||
Account.status.notin_(MANUAL_STATES),
|
||||
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
|
||||
~active_lease,
|
||||
)
|
||||
.order_by(
|
||||
Account.ck_checked_at.is_(None).desc(),
|
||||
Account.ck_checked_at.asc(),
|
||||
Account.points.is_(None).desc(),
|
||||
Account.points.asc(),
|
||||
Account.id.asc(),
|
||||
)
|
||||
.limit(max(1, min(int(limit), 100)))
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def has_recent_exchange(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
commodity_id: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
moment = _now(now)
|
||||
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
|
||||
return (
|
||||
db.query(AccountEvent.id)
|
||||
.filter(
|
||||
AccountEvent.account_id == account_id,
|
||||
AccountEvent.event_type == "exchange",
|
||||
AccountEvent.subject_key == commodity_id,
|
||||
AccountEvent.occurred_at >= since,
|
||||
)
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
|
||||
|
||||
def lease_account(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -116,7 +173,7 @@ def lease_account(
|
||||
holder_user_id: int,
|
||||
task_id: int,
|
||||
commodity_id: str,
|
||||
ttl_minutes: int = VALIDATION_LEASE_MINUTES,
|
||||
ttl_minutes: int | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease | None:
|
||||
"""尝试领取一个账号;撞唯一索引时返回 None。"""
|
||||
@@ -130,7 +187,11 @@ def lease_account(
|
||||
batch_id=f"pf:{task_id}",
|
||||
status="active",
|
||||
leased_at=moment,
|
||||
expires_at=moment + timedelta(minutes=max(1, int(ttl_minutes))),
|
||||
expires_at=(
|
||||
None
|
||||
if ttl_minutes is None
|
||||
else moment + timedelta(minutes=max(1, int(ttl_minutes)))
|
||||
),
|
||||
release_reason="",
|
||||
created_at=moment,
|
||||
)
|
||||
@@ -150,12 +211,16 @@ def renew_lease(
|
||||
db: Session,
|
||||
lease: AccountLease,
|
||||
*,
|
||||
ttl_minutes: int = BINDING_LEASE_MINUTES,
|
||||
ttl_minutes: int | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease:
|
||||
if lease.status != "active":
|
||||
raise ValueError("租约已结束,不能续期")
|
||||
lease.expires_at = _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
|
||||
lease.expires_at = (
|
||||
None
|
||||
if ttl_minutes is None
|
||||
else _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
|
||||
)
|
||||
db.commit()
|
||||
return lease
|
||||
|
||||
@@ -188,6 +253,7 @@ def expire_platform_fulfillment_leases(
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
AccountLease.expires_at.isnot(None),
|
||||
AccountLease.expires_at <= moment,
|
||||
)
|
||||
.order_by(AccountLease.id.asc())
|
||||
@@ -210,7 +276,9 @@ __all__ = [
|
||||
"AccountCandidate",
|
||||
"eligible_accounts",
|
||||
"expire_platform_fulfillment_leases",
|
||||
"has_recent_exchange",
|
||||
"lease_account",
|
||||
"live_candidate_accounts",
|
||||
"release_lease",
|
||||
"renew_lease",
|
||||
]
|
||||
|
||||
@@ -3,15 +3,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityError
|
||||
|
||||
from ...models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
@@ -19,9 +17,11 @@ from ...models import (
|
||||
DouyuTask,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentEvent,
|
||||
PlatformFulfillmentSetting,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
||||
from ..douyu_activity_query import activity_client, query_exchange_eligibility
|
||||
from ..douyu_batch_launcher import start_douyu_batch
|
||||
from ..douyu_service import douyu_config_value, ensure_douyu_config
|
||||
@@ -30,10 +30,10 @@ from ..external_order_source import (
|
||||
list_pending_manual_fulfillments,
|
||||
)
|
||||
from .account_selector import (
|
||||
BINDING_LEASE_MINUTES,
|
||||
VALIDATION_LEASE_MINUTES,
|
||||
eligible_accounts,
|
||||
AccountCandidate,
|
||||
has_recent_exchange,
|
||||
lease_account,
|
||||
live_candidate_accounts,
|
||||
release_lease,
|
||||
renew_lease,
|
||||
)
|
||||
@@ -81,6 +81,66 @@ def _mapping_for_sku(
|
||||
)
|
||||
|
||||
|
||||
def get_settings(db: Session) -> dict[str, Any]:
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1, lease_duration_minutes=None)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def update_settings(
|
||||
db: Session,
|
||||
*,
|
||||
lease_duration_minutes: int | None,
|
||||
current: User,
|
||||
) -> dict[str, Any]:
|
||||
row = (
|
||||
db.query(PlatformFulfillmentSetting)
|
||||
.filter(PlatformFulfillmentSetting.id == 1)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = PlatformFulfillmentSetting(id=1)
|
||||
db.add(row)
|
||||
now = _now()
|
||||
row.lease_duration_minutes = lease_duration_minutes
|
||||
row.updated_by = current.id
|
||||
row.updated_at = now
|
||||
active_leases = (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for lease in active_leases:
|
||||
lease.expires_at = (
|
||||
None
|
||||
if lease_duration_minutes is None
|
||||
else now + timedelta(minutes=lease_duration_minutes)
|
||||
)
|
||||
db.commit()
|
||||
return {
|
||||
"leaseDurationMinutes": row.lease_duration_minutes,
|
||||
"updatedAt": _jsonable(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _lease_duration_minutes(db: Session) -> int | None:
|
||||
return get_settings(db)["leaseDurationMinutes"]
|
||||
|
||||
|
||||
def _append_event(
|
||||
db: Session,
|
||||
task_id: int,
|
||||
@@ -485,37 +545,119 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
||||
if not task.commodity_id or not task.required_points:
|
||||
raise HTTPException(status_code=409, detail="请先完成商品映射")
|
||||
required_points = int(task.required_points)
|
||||
if task.account_id and task.lease_id:
|
||||
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
if lease and lease.status == "active":
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
candidates = eligible_accounts(
|
||||
db,
|
||||
commodity_id=task.commodity_id,
|
||||
required_points=task.required_points,
|
||||
limit=20,
|
||||
)
|
||||
selected = None
|
||||
config = ensure_douyu_config(db)
|
||||
lease_duration_minutes = _lease_duration_minutes(db)
|
||||
manual_id = str(douyu_config_value("manual_id", config.manual_id))
|
||||
rid = str(douyu_config_value("rid", config.rid))
|
||||
act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias))
|
||||
# 单次最多实时检测 5 个,避免一次选号请求被外部接口拖到超时。
|
||||
# 检测时间会写回 ck_checked_at,下一次点击自动轮到下一批。
|
||||
candidates = live_candidate_accounts(db, limit=5)
|
||||
diagnostics: list[dict[str, Any]] = []
|
||||
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
|
||||
selected: AccountCandidate | None = None
|
||||
selected_state: DouyuLiveAccountState | None = None
|
||||
lease = None
|
||||
for candidate in candidates:
|
||||
for account in candidates:
|
||||
live_state = refresh_douyu_account_state(
|
||||
db,
|
||||
account,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
act_alias=act_alias,
|
||||
)
|
||||
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
|
||||
if has_recent_exchange(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
commodity_id=task.commodity_id,
|
||||
):
|
||||
reasons.append("365 天内已有该商品兑换事件")
|
||||
if reasons:
|
||||
diagnostics.append(
|
||||
{
|
||||
"accountId": int(account.id),
|
||||
"accountName": live_state.account_name,
|
||||
"ck": live_state.ck_verdict,
|
||||
"eliteOpened": live_state.elite_opened,
|
||||
"points": live_state.points,
|
||||
"reasons": reasons,
|
||||
}
|
||||
)
|
||||
continue
|
||||
qualified.append((account, live_state))
|
||||
|
||||
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
|
||||
# 其次是只需充值、只需开通、两者都需要的账号。
|
||||
qualified.sort(
|
||||
key=lambda item: (
|
||||
item[1].readiness_rank(required_points=required_points),
|
||||
int(item[1].points or 0),
|
||||
int(item[0].id),
|
||||
)
|
||||
)
|
||||
for account, live_state in qualified:
|
||||
candidate = AccountCandidate(
|
||||
account_id=int(account.id),
|
||||
username=str(account.username or ""),
|
||||
nickname=str(account.nickname or ""),
|
||||
points=int(live_state.points or 0),
|
||||
gold_balance=account.gold_balance,
|
||||
points_expire_at=account.points_expire_at,
|
||||
role_change_available_at=live_state.role_change_available_at,
|
||||
)
|
||||
lease = lease_account(
|
||||
db,
|
||||
candidate=candidate,
|
||||
holder_user_id=current.id,
|
||||
task_id=task.id,
|
||||
commodity_id=task.commodity_id,
|
||||
ttl_minutes=VALIDATION_LEASE_MINUTES,
|
||||
ttl_minutes=lease_duration_minutes,
|
||||
)
|
||||
if lease is not None:
|
||||
selected = candidate
|
||||
selected_state = live_state
|
||||
break
|
||||
if selected is None or lease is None:
|
||||
diagnostics.append(
|
||||
{
|
||||
"accountId": int(account.id),
|
||||
"accountName": live_state.account_name,
|
||||
"ck": live_state.ck_verdict,
|
||||
"eliteOpened": live_state.elite_opened,
|
||||
"points": live_state.points,
|
||||
"reasons": ["账号刚被其他任务占用"],
|
||||
}
|
||||
)
|
||||
if selected is None or selected_state is None or lease is None:
|
||||
task.execution_status = "ready"
|
||||
task.issue_code = "no_eligible_account"
|
||||
task.last_error = "当前没有满足 CK、积分、限兑和换绑条件的斗鱼账号"
|
||||
if not candidates:
|
||||
task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号"
|
||||
else:
|
||||
summary = ";".join(
|
||||
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
|
||||
for item in diagnostics[:5]
|
||||
)
|
||||
task.last_error = (
|
||||
f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号"
|
||||
+ (f"。{summary}" if summary else "")
|
||||
)[:500]
|
||||
task.updated_at = _now()
|
||||
_append_event(db, task.id, "account_allocation_failed")
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"account_allocation_failed",
|
||||
detail={
|
||||
"candidateCount": len(candidates),
|
||||
"diagnostics": diagnostics,
|
||||
},
|
||||
)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
@@ -524,9 +666,25 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
task.operator_id = current.id
|
||||
task.execution_status = "allocated"
|
||||
task.binding_status = "not_started"
|
||||
task.exchange_status = "not_started"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
soft_reasons = selected_state.soft_requirement_reasons(
|
||||
required_points=required_points
|
||||
)
|
||||
if task.commodity_id in selected_state.limited_ids:
|
||||
task.exchange_status = "limited"
|
||||
task.issue_code = "commodity_limit_reached"
|
||||
task.last_error = "该账号已达到此商品兑换上限"
|
||||
elif selected_state.elite_opened is not True:
|
||||
task.exchange_status = "not_opened"
|
||||
task.issue_code = "elite_not_opened"
|
||||
task.last_error = "账号尚未开通精英宝典,可开通后继续"
|
||||
elif selected_state.points is None or selected_state.points < required_points:
|
||||
task.exchange_status = "points_short"
|
||||
task.issue_code = "points_short"
|
||||
task.last_error = "账号积分不足,可充值后继续"
|
||||
else:
|
||||
task.exchange_status = "eligible"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
@@ -538,6 +696,9 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
"accountId": selected.account_id,
|
||||
"accountName": selected.display_name,
|
||||
"points": selected.points,
|
||||
"eliteOpened": selected_state.elite_opened,
|
||||
"softReasons": soft_reasons,
|
||||
"exchangeStatus": task.exchange_status,
|
||||
},
|
||||
)
|
||||
db.commit()
|
||||
@@ -613,7 +774,7 @@ async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str
|
||||
renew_lease(
|
||||
db,
|
||||
lease,
|
||||
ttl_minutes=BINDING_LEASE_MINUTES,
|
||||
ttl_minutes=_lease_duration_minutes(db),
|
||||
)
|
||||
_append_event(
|
||||
db,
|
||||
@@ -696,7 +857,7 @@ async def confirm_binding(
|
||||
task.execution_status = "binding_confirming"
|
||||
task.operator_id = current.id
|
||||
task.updated_at = _now()
|
||||
renew_lease(db, lease, ttl_minutes=BINDING_LEASE_MINUTES)
|
||||
renew_lease(db, lease, ttl_minutes=_lease_duration_minutes(db))
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
@@ -737,7 +898,7 @@ def refresh_exchange_eligibility(
|
||||
)
|
||||
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
|
||||
account.points = eligibility.points
|
||||
except DouyuActivityError as exc:
|
||||
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
|
||||
task.execution_status = "manual_required"
|
||||
task.exchange_status = "check_failed"
|
||||
task.issue_code = "eligibility_check_failed"
|
||||
@@ -770,9 +931,9 @@ def refresh_exchange_eligibility(
|
||||
task.exchange_status = "eligible"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.execution_status = (
|
||||
"manual_required" if task.exchange_status != "eligible" else "bound"
|
||||
)
|
||||
# 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留,
|
||||
# 后续充值/开通/解除限兑后刷新资格即可。
|
||||
task.execution_status = "bound"
|
||||
task.updated_at = _now()
|
||||
account.updated_at = _now()
|
||||
_append_event(
|
||||
|
||||
Reference in New Issue
Block a user