Files
live-hub-py/web/backend/services/automation/jobs/account_onboarding.py
T

147 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""账号首次登录:把未登录账号自动变成持有有效 CK 的可用账号。"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.orm import Session
from ....models import Account, AutomationJob, LoginTask
from ...account_lifecycle import MANUAL_KINDS, MANUAL_STATES, STATUS_MANUAL
from ...account_protection_service import load_protection_snapshot
from ...account_query_filters import protected_relogin_eligible_filter
from ...login_automation import run_login_batch_with_fallback, system_user_id
JOB_KEY = "account_onboarding"
def _in_flight_login_exists():
return (
select(LoginTask.id)
.where(
LoginTask.account_id == Account.id,
func.coalesce(LoginTask.attempt_status, "").in_(("pending", "running")),
)
.exists()
)
def _onboarding_eligibility_filter(db: Session, *, now: datetime | None = None):
protection = load_protection_snapshot(db)
ordinary = and_(
Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
# 缺账号/密码的账号首登必失败,不能占样本名额。
Account.username != "",
Account.password != "",
# 已经判定为极验/凭证问题的普通账号不再自动首登。
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(),
)
relogin_ids = protection.relogin_ids
if not relogin_ids:
return ordinary, protection
protected = and_(
or_(Account.cookie.is_(None), Account.cookie == ""),
protected_relogin_eligible_filter(
protected_ids=relogin_ids,
max_attempts=2,
now=now,
cookie_operable=True,
due_only=True,
suppressed_ids=protection.suppressed_relogin_ids,
),
)
return or_(ordinary, protected), protection
def build_select_query(
db: Session,
job: AutomationJob,
*,
limit: int | None = None,
):
"""未登录、自动托管、没有在途登录尝试的账号(履约保护目标优先)。"""
eligibility, protection = _onboarding_eligibility_filter(db)
ordering = []
if protection.relogin_ids:
ordering.append(
case((Account.id.in_(protection.relogin_ids), 0), else_=1)
)
ordering.append(Account.id.asc())
query = db.query(Account).filter(eligibility).order_by(*ordering)
batch = max(1, int(limit if limit is not None else job.batch_size or 20))
return query.limit(batch)
def count_pending_onboarding(db: Session) -> int:
eligibility, _ = _onboarding_eligibility_filter(db)
return int(
db.query(func.count(Account.id)).filter(eligibility).scalar() or 0
)
def run_account_onboarding(db: Session, job: AutomationJob) -> dict[str, Any]:
now = datetime.now(UTC)
user_id = system_user_id(db)
if user_id is None:
return {
"scanned": 0,
"valid": 0,
"invalid": 0,
"skipped": 0,
"message": "库里没有可用用户,无法以系统身份发起首次登录",
}
accounts = build_select_query(db, job).all()
pending = count_pending_onboarding(db)
if not accounts:
return {
"scanned": 0,
"valid": 0,
"invalid": 0,
"skipped": 0,
"message": f"没有待首次登录账号(当前积压 {pending})",
}
account_ids = [int(account.id) for account in accounts]
outcome = run_login_batch_with_fallback(
db,
account_ids=account_ids,
mode="login",
created_by=user_id,
concurrency=max(1, int(job.concurrency or 3)),
)
parts = [
f"本轮首次登录 {outcome.scanned} 个",
f"成功 {outcome.success}",
f"失败 {outcome.failed}",
]
if outcome.skipped:
parts.append(f"预算/预检跳过 {outcome.skipped}")
if outcome.fallback_used:
parts.append(
f"邮箱回退 wgapi→iframe {outcome.fallback_success} 个成功"
)
if pending:
parts.append(f"待首次登录积压 {pending}")
return {
"scanned": outcome.scanned,
"valid": outcome.success,
"invalid": outcome.failed,
"skipped": outcome.skipped,
"message": ",".join(parts),
"detail": {
**outcome.detail(),
"pending": pending,
"selected": len(account_ids),
"startedAt": now.isoformat(),
},
}
__all__ = ["JOB_KEY", "build_select_query", "count_pending_onboarding", "run_account_onboarding"]