fix: 补上清单里还没对上的登录拒绝、会话回退和代理清理

This commit is contained in:
2026-11-16 16:46:37 +08:00
parent a1e2b6e65c
commit 3cff9dc37a
19 changed files with 223 additions and 65 deletions
+6
View File
@@ -1628,6 +1628,12 @@ class AutoStudyWorker:
course_list = snapshot_courses(db.scalars(select(Course)).all())
if expired:
db.commit()
queried = {row.employee_id for row in users}
with _halt_lock:
stranded = [eid for eid in list(_wanted) if eid not in queried and eid not in _running]
for eid in stranded:
_set_user_status(eid, state="学习失败", message="登录凭证待校验")
drop_work(eid)
wait = max(1.0, min(3600.0, (soonest - as_cn()).total_seconds()))
label = soonest.strftime("%m-%d %H:%M:%S")
return jobs, course_list, wait, f"下一次定时 {label}"
+16 -8
View File
@@ -439,7 +439,7 @@ def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[
}
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int:
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> tuple[int, bool]:
"""倒序分页累加本月分钟,遇到上个月即停。重复页直接返回,不再累加。"""
offset = 0
total = 0
@@ -449,9 +449,9 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int =
if rows is None:
if offset == 0:
raise RuntimeError("学时历史没有获取到")
return total
return total, False
if not rows:
return total
return total, False
mark = (
len(rows),
rows[0].get("studied_at"),
@@ -460,14 +460,14 @@ def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int =
rows[-1].get("title"),
)
if mark in seen:
return total
return total, False
seen.add(mark)
add, done = fold_month_minutes(rows, year, month)
total += add
if done or len(rows) != page_size:
return total
return total, False
offset += page_size
return total
return total, True
def parse_training_cards(page: str, status: str) -> list[dict]:
@@ -744,6 +744,10 @@ class JigsawRejected(RuntimeError):
"""这次拼图位置不对,可以换一张再试。"""
class LoginRejected(RuntimeError):
"""平台明确拒绝了账号或密码,不能再自动重试。"""
class ManualJigsaw(Exception):
"""自动拼图已用完,把新拼图交给人来拖。"""
@@ -967,7 +971,9 @@ class EunivClient:
return profile
if any(word in message for word in ("验证码", "拼图", "滑块")):
raise JigsawRejected(message or "拼图未通过")
raise RuntimeError(f"登录失败:{message}")
if any(word in message for word in ("密码", "账号", "用户名", "工号")):
raise LoginRejected("账号或密码错误")
raise RuntimeError("登录没有完成")
def authorize(self, profile: dict) -> None:
account_id = str(profile.get("accountId") or profile.get("userName") or "")
@@ -1209,7 +1215,9 @@ class EunivClient:
return self._study_history_search(pageable=True, offset=offset, limit=limit)
try:
return accumulate_month_minutes(fetch_page, year, month)
total, limited = accumulate_month_minutes(fetch_page, year, month)
self.history_limited = limited
return total
except SessionExpired:
raise
except Exception as exc:
+1
View File
@@ -99,6 +99,7 @@ class ProxyNode(Base):
latency_ms: Mapped[int | None] = mapped_column(nullable=True)
last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
fail_reason: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default=text("''"))
assigns: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
+12
View File
@@ -393,6 +393,7 @@ def _refresh_body() -> dict:
new_ids: list[int] = []
alive_ids: list[int] = []
dead_ids: list[int] = []
seen_at = _now()
for item in candidates:
if not is_china(item.country):
continue
@@ -407,6 +408,7 @@ def _refresh_body() -> dict:
anonymity=item.anonymity,
source=item.source,
status=STATUS_NEW,
last_seen_at=seen_at,
)
db.add(node)
db.flush()
@@ -416,6 +418,7 @@ def _refresh_body() -> dict:
node.country = item.country or node.country
node.anonymity = item.anonymity or node.anonymity
node.source = item.source or node.source
node.last_seen_at = seen_at
if node.status == STATUS_DEAD:
dead_ids.append(node.id)
continue
@@ -423,6 +426,15 @@ def _refresh_body() -> dict:
new_ids.append(node.id)
elif node.status == STATUS_ALIVE:
alive_ids.append(node.id)
stale_before = seen_at - timedelta(days=7)
held = set(_holds.values())
for node in list(existing.values()):
if node.id in held or node.status != STATUS_DEAD:
continue
seen = _aware(node.last_seen_at)
if seen is not None and seen < stale_before:
db.delete(node)
existing.pop((node.scheme, node.host, int(node.port)), None)
for node in existing.values():
if node.id in alive_ids or node.id in new_ids or node.id in dead_ids:
continue
+34 -5
View File
@@ -17,6 +17,7 @@ from euniv.client import (
QR_PASSWORD_MARK,
EunivClient,
JigsawRejected,
LoginRejected,
ManualJigsaw,
QrWaiting,
SessionExpired,
@@ -420,6 +421,14 @@ def _apply_hours_source(client, summary: dict, items: list | None = None) -> dic
data["month_hours"] = totals["month"]
data["today_hours"] = totals["today"]
data["total_hours"] = totals["total"]
data["limited"] = False
walker = getattr(client, "month_history_minutes", None)
if callable(walker):
try:
data["month_hours"] = walker()
data["limited"] = bool(getattr(client, "history_limited", False))
except Exception:
data["limited"] = False
return data
@@ -439,13 +448,29 @@ def _api_hour_fields(client) -> dict:
def _hour_fields(data: dict) -> dict:
return {
fields = {
"hours_source": data.get("hours_source") or "api",
"year_hours": data.get("year_hours"),
"month_hours": data.get("month_hours"),
"today_hours": data.get("today_hours"),
"total_hours": data.get("total_hours"),
}
if data.get("limited") is True:
fields["limited"] = True
return fields
def _drop_rejected_password(db: Session, employee_id: str) -> None:
"""密码被平台拒绝后清掉登录凭证,停止自动重试。"""
with _credential_lock(employee_id):
db.rollback()
account = db.get(Account, employee_id)
if account is None:
return
account.credential_cipher = ""
account.credential_valid = False
account.last_refresh_at = datetime.now(timezone.utc)
db.commit()
def _auto_attempts(db: Session) -> int:
@@ -496,6 +521,9 @@ def _live(db: Session, employee_id: str, client_factory, read):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
return data
except LoginRejected:
_drop_rejected_password(db, employee_id)
raise RuntimeError("请先登录") from None
except RuntimeError:
raise
except Exception as exc:
@@ -599,15 +627,16 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
if isinstance(exc, InvalidToken):
logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id)
return
if isinstance(exc, LoginRejected):
logging.getLogger("euniv.service").warning("账号 %s 的密码已被拒绝,停止自动登录", employee_id)
_drop_rejected_password(db, employee_id)
return
logging.getLogger("euniv.service").exception("刷新账号 %s 的登录状态失败", employee_id)
db.rollback()
account = db.get(Account, employee_id)
if account is None:
return
rejected = isinstance(exc, RuntimeError) and any(
word in str(exc) for word in ("登录失败", "登录页校验失败", "密码错误")
)
valid = False if rejected else account.credential_valid
valid = account.credential_valid
finally:
if client is not None:
try: