- 新增 account_onboarding 首次登录作业,默认关闭,batch=20 - 新增 login_automation 共享执行器:wgapi 主通道,email_code 失败自动切 iframe - 重登作业对 email_code 失败账号增加 iframe 回退 - 自动化中心展示首次登录作业 - 补充首次登录/回退/注册表回归测试 - 文档补充执行顺序与本轮实现
244 lines
7.8 KiB
Python
244 lines
7.8 KiB
Python
"""自动登录批次的共享执行器:首次登录 / 重登 / 邮箱双通道回退。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..database import WorkerSessionLocal
|
|
from ..models import LoginAttempt, ProxyConfig, User
|
|
from .login_service import LoginBatchRunner, get_relogin_limits
|
|
|
|
#: 默认登录接口;旧版 iframe 只在邮箱验证码失败时作为回退通道。
|
|
PRIMARY_LOGIN_API = "wgapi"
|
|
FALLBACK_LOGIN_API = "iframe"
|
|
#: 触发回退的失败分型。邮箱配额满不代表通道坏了,不切换。
|
|
EMAIL_FALLBACK_KINDS = frozenset({"email_code"})
|
|
DEFAULT_MAX_TOTAL_TIME = 240
|
|
DEFAULT_MAX_RETRIES = 5
|
|
|
|
|
|
@dataclass
|
|
class LoginBatchOutcome:
|
|
account_ids: list[int] = field(default_factory=list)
|
|
attempted_ids: list[int] = field(default_factory=list)
|
|
success_ids: list[int] = field(default_factory=list)
|
|
failed_ids: list[int] = field(default_factory=list)
|
|
skipped_ids: list[int] = field(default_factory=list)
|
|
failure_kinds: dict[int, str] = field(default_factory=dict)
|
|
batch_ids: list[str] = field(default_factory=list)
|
|
fallback_batch_ids: list[str] = field(default_factory=list)
|
|
fallback_used: bool = False
|
|
fallback_success_ids: list[int] = field(default_factory=list)
|
|
|
|
@property
|
|
def scanned(self) -> int:
|
|
return len(self.attempted_ids)
|
|
|
|
@property
|
|
def success(self) -> int:
|
|
return len(self.success_ids)
|
|
|
|
@property
|
|
def failed(self) -> int:
|
|
return len(self.failed_ids)
|
|
|
|
@property
|
|
def skipped(self) -> int:
|
|
return len(self.skipped_ids)
|
|
|
|
@property
|
|
def fallback_success(self) -> int:
|
|
return len(self.fallback_success_ids)
|
|
|
|
def detail(self) -> dict[str, Any]:
|
|
return {
|
|
"batchIds": self.batch_ids,
|
|
"fallbackBatchIds": self.fallback_batch_ids,
|
|
"fallbackUsed": self.fallback_used,
|
|
"fallbackSuccess": self.fallback_success,
|
|
"attempted": self.scanned,
|
|
"skipped": self.skipped,
|
|
"failureKinds": {
|
|
str(account_id): kind
|
|
for account_id, kind in sorted(self.failure_kinds.items())
|
|
},
|
|
}
|
|
|
|
|
|
def system_user_id(db: Session) -> int | None:
|
|
"""自动登录落 created_by 需要真实用户;与 ck_relogin 保持一致。"""
|
|
row = (
|
|
db.query(User.id)
|
|
.filter(User.role == "super_admin")
|
|
.order_by(User.id.asc())
|
|
.first()
|
|
)
|
|
if row:
|
|
return int(row[0])
|
|
row = db.query(User.id).order_by(User.id.asc()).first()
|
|
return int(row[0]) if row else None
|
|
|
|
|
|
def _max_total_time() -> int:
|
|
try:
|
|
_, configured = get_relogin_limits()
|
|
return max(30, min(int(configured or DEFAULT_MAX_TOTAL_TIME), DEFAULT_MAX_TOTAL_TIME))
|
|
except Exception: # noqa: BLE001 - 配置异常时用安全默认值
|
|
return DEFAULT_MAX_TOTAL_TIME
|
|
|
|
|
|
def run_login_batch(
|
|
db: Session,
|
|
*,
|
|
account_ids: list[int],
|
|
mode: str,
|
|
created_by: int,
|
|
api_strategy: str,
|
|
concurrency: int = 3,
|
|
max_total_time: int | None = None,
|
|
max_login_retries: int = DEFAULT_MAX_RETRIES,
|
|
) -> str:
|
|
"""同步跑一个登录批次,返回 batch_id;runner 使用独立会话。"""
|
|
proxy = db.query(ProxyConfig).first()
|
|
runner_db = WorkerSessionLocal()
|
|
try:
|
|
runner = LoginBatchRunner(
|
|
db=runner_db,
|
|
account_ids=list(dict.fromkeys(int(value) for value in account_ids)),
|
|
created_by=int(created_by),
|
|
creator_permissions=["login:view_all", "cookie:operate"],
|
|
max_login_retries=max(1, int(max_login_retries)),
|
|
max_total_time=(
|
|
_max_total_time()
|
|
if max_total_time is None
|
|
else max(30, int(max_total_time))
|
|
),
|
|
proxy_config=proxy,
|
|
log_queue=None,
|
|
loop=None,
|
|
concurrency=max(1, min(int(concurrency or 3), 8)),
|
|
api_strategy=api_strategy,
|
|
mode=mode,
|
|
trigger_source="automation",
|
|
)
|
|
batch_id = runner.batch_id
|
|
runner.run()
|
|
return batch_id
|
|
finally:
|
|
runner_db.close()
|
|
|
|
|
|
def collect_batch_results(batch_id: str) -> dict[int, tuple[str, str]]:
|
|
"""在新事务里读回批次结果:account_id -> (status, failure_kind)。"""
|
|
session = WorkerSessionLocal()
|
|
try:
|
|
rows = (
|
|
session.query(
|
|
LoginAttempt.account_id,
|
|
LoginAttempt.status,
|
|
LoginAttempt.failure_kind,
|
|
)
|
|
.filter(LoginAttempt.batch_id == batch_id)
|
|
.order_by(LoginAttempt.id.asc())
|
|
.all()
|
|
)
|
|
result: dict[int, tuple[str, str]] = {}
|
|
for account_id, status, kind in rows:
|
|
result[int(account_id)] = (str(status or ""), str(kind or ""))
|
|
return result
|
|
finally:
|
|
session.close()
|
|
|
|
|
|
def _is_success(status: str) -> bool:
|
|
return status == "success"
|
|
|
|
|
|
def _is_failed(status: str) -> bool:
|
|
return status in {"failed", "error", "stopped"}
|
|
|
|
|
|
def run_login_batch_with_fallback(
|
|
db: Session,
|
|
*,
|
|
account_ids: list[int],
|
|
mode: str,
|
|
created_by: int,
|
|
concurrency: int = 3,
|
|
max_total_time: int | None = None,
|
|
max_login_retries: int = DEFAULT_MAX_RETRIES,
|
|
) -> LoginBatchOutcome:
|
|
"""先走 wgapi;仅对 email_code 失败账号切 iframe 重试一次。
|
|
|
|
首次登录和重登共用。邮箱配额满、极验、凭证、网络失败都不切通道。
|
|
"""
|
|
ordered_ids = list(dict.fromkeys(int(value) for value in account_ids))
|
|
outcome = LoginBatchOutcome(account_ids=ordered_ids)
|
|
|
|
primary_batch = run_login_batch(
|
|
db,
|
|
account_ids=ordered_ids,
|
|
mode=mode,
|
|
created_by=created_by,
|
|
api_strategy=PRIMARY_LOGIN_API,
|
|
concurrency=concurrency,
|
|
max_total_time=max_total_time,
|
|
max_login_retries=max_login_retries,
|
|
)
|
|
outcome.batch_ids.append(primary_batch)
|
|
primary = collect_batch_results(primary_batch)
|
|
|
|
success_ids = {account_id for account_id, (status, _) in primary.items() if _is_success(status)}
|
|
email_failed_ids = [
|
|
account_id
|
|
for account_id, (status, kind) in primary.items()
|
|
if account_id not in success_ids
|
|
and _is_failed(status)
|
|
and kind in EMAIL_FALLBACK_KINDS
|
|
]
|
|
|
|
fallback: dict[int, tuple[str, str]] = {}
|
|
if email_failed_ids:
|
|
outcome.fallback_used = True
|
|
fallback_batch = run_login_batch(
|
|
db,
|
|
account_ids=email_failed_ids,
|
|
mode=mode,
|
|
created_by=created_by,
|
|
api_strategy=FALLBACK_LOGIN_API,
|
|
concurrency=concurrency,
|
|
max_total_time=max_total_time,
|
|
max_login_retries=max_login_retries,
|
|
)
|
|
outcome.fallback_batch_ids.append(fallback_batch)
|
|
fallback = collect_batch_results(fallback_batch)
|
|
for account_id, (status, _) in fallback.items():
|
|
if _is_success(status):
|
|
success_ids.add(account_id)
|
|
|
|
attempted = dict(primary)
|
|
attempted.update(fallback)
|
|
outcome.attempted_ids = sorted(attempted)
|
|
outcome.success_ids = sorted(success_ids)
|
|
outcome.failed_ids = [
|
|
account_id
|
|
for account_id in outcome.attempted_ids
|
|
if account_id not in success_ids
|
|
]
|
|
outcome.skipped_ids = [
|
|
account_id for account_id in ordered_ids if account_id not in attempted
|
|
]
|
|
for account_id in outcome.failed_ids:
|
|
status, kind = attempted.get(account_id, ("", ""))
|
|
if not _is_success(status):
|
|
outcome.failure_kinds[account_id] = kind
|
|
outcome.fallback_success_ids = sorted(
|
|
account_id
|
|
for account_id, (status, _) in fallback.items()
|
|
if _is_success(status)
|
|
)
|
|
return outcome
|