"""账号自动学习任务的立即开始与停止。""" from __future__ import annotations import copy import math import re import secrets import threading import time from datetime import datetime from types import SimpleNamespace from euniv.study_window import month_key, window_open _frame_lock = threading.Lock() _frames: dict[str, int] = {} _BOOT = secrets.token_hex(8) _SECRET_COLUMNS = frozenset({"password_cipher", "credential_cipher", "proxy_password_cipher"}) _SNAP_SECONDS = 30.0 _snap_lock = threading.Lock() _snaps: dict[str, tuple[float, SimpleNamespace]] = {} _snap_marks: dict[str, int] = {} _EMPTY = { "started": False, "paused": True, "hours_met": False, "schedule_enabled": True, "workers": [], "active": False, "message": "", } def remember(account, mark: int | None = None) -> SimpleNamespace: """把首页学习状态要用的账号字段抄到内存,不含任何密文。账号一有写入就会失效。 mark 是读库之前取的写入记号。读库期间这个账号又被写过,就不把这份旧值留在内存里。 """ from euniv.models import Account fields = { column.key: getattr(account, column.key, None) for column in Account.__table__.columns if column.key not in _SECRET_COLUMNS } snap = SimpleNamespace(**fields) key = str(fields.get("employee_id") or "").strip() if key: with _snap_lock: if mark is None or _snap_marks.get(key, 0) == mark: _snaps[key] = (time.monotonic() + _SNAP_SECONDS, snap) return snap def forget(employee_id: str) -> None: key = (employee_id or "").strip() with _snap_lock: _snaps.pop(key, None) _snap_marks[key] = _snap_marks.get(key, 0) + 1 def _write_mark(employee_id: str) -> int: with _snap_lock: return _snap_marks.get(employee_id, 0) def _remembered(employee_id: str) -> SimpleNamespace | None: with _snap_lock: held = _snaps.get(employee_id) if held is None: return None if held[0] < time.monotonic(): _snaps.pop(employee_id, None) return None return held[1] def stamp_frame(employee_id: str, payload: dict) -> dict: """seq 只在同一次启动内递增。boot 变了说明服务重启过,页面要从新的 seq 重新计数。""" key = (employee_id or "").strip() with _frame_lock: number = _frames.get(key, 0) + 1 _frames[key] = number stamped = dict(payload) stamped["seq"] = number stamped["boot"] = _BOOT return stamped def start_now(account, now: datetime | None = None) -> None: account.study_paused = False account.study_stop_month = month_key(now) account.study_ignore_window = True def stop_now(account, now: datetime | None = None) -> None: account.study_paused = True account.study_ignore_window = False account.study_stop_month = month_key(now) def schedule_enabled(account) -> bool: if not hasattr(account, "study_schedule_enabled"): return True value = getattr(account, "study_schedule_enabled", True) return False if value is False else True def is_paused(account, now: datetime | None = None) -> bool: if not bool(getattr(account, "study_paused", False)): return False recorded = str(getattr(account, "study_stop_month", "") or "") return (not recorded) or recorded == month_key(now) def ignores_window(account) -> bool: return bool(getattr(account, "study_ignore_window", False)) def month_minutes(value: object) -> int: match = re.search(r"(\d+)", str(value or "")) return int(match.group(1)) if match else 0 def stamp_hours(account, hours: str, now: datetime | None = None) -> None: account.month_hours = hours account.hours_month = month_key(now) def hours_met(account, now: datetime | None = None) -> bool: target = int(getattr(account, "monthly_target", 0) or 0) if target <= 0: return False recorded = str(getattr(account, "hours_month", "") or "") if recorded and recorded != month_key(now): return False return month_minutes(getattr(account, "month_hours", "")) >= target def expire_pause(account, now: datetime | None = None) -> bool: """本月的停止和立即开始都不带到下月。遗留的无月份暂停记到当月。""" key = month_key(now) recorded = str(getattr(account, "study_stop_month", "") or "") changed = False if ignores_window(account) and recorded and recorded != key: account.study_ignore_window = False changed = True if not bool(getattr(account, "study_paused", False)): if changed: account.study_stop_month = "" return changed if not recorded: account.study_stop_month = key return True if recorded != key: account.study_paused = False account.study_stop_month = "" account.study_ignore_window = False return True return changed def eligible(account, now: datetime | None = None) -> bool: if is_paused(account, now): return False if hours_met(account, now): return False if ignores_window(account): return True if not schedule_enabled(account): return False return window_open(account, now) def view_of(account, now: datetime | None = None) -> dict: paused = is_paused(account, now) ignore = ignores_window(account) opened = window_open(account, now) met = hours_met(account, now) scheduled = schedule_enabled(account) started = (not paused) and (not met) and (ignore or (scheduled and opened)) return { "paused": paused, "ignore_window": ignore, "window_open": opened, "hours_met": met, "schedule_enabled": scheduled, "started": started, } def _with_heartbeat_left(workers: list) -> list: """每一帧按服务器当前时间重算剩余秒数,页面收到新帧时不会从整段间隔重新倒数。""" clock = time.time() rows = [] for item in workers: if not isinstance(item, dict): continue row = dict(item) due = row.get("heartbeat_at") if isinstance(due, (int, float)) and not isinstance(due, bool) and due > 0: left = max(0, int(math.ceil(float(due) - clock))) interval = row.get("interval") if isinstance(interval, int) and not isinstance(interval, bool) and interval > 0: left = min(left, interval) row["heartbeat_in"] = left rows.append(row) return rows def assemble(account, live: dict | None = None, now: datetime | None = None) -> dict: payload = view_of(account, now) info = dict(live) if isinstance(live, dict) else {} recorded = str(info.get("month") or "") if recorded and recorded != month_key(now): info = {} payload["state"] = str(info.get("state") or "") payload["course"] = str(info.get("course") or "") payload["message"] = str(info.get("message") or "") workers = info.get("workers") or [] payload["workers"] = _with_heartbeat_left(workers if isinstance(workers, list) else []) from euniv.autostudy import work_running eid = str(getattr(account, "employee_id", "") or "") running = bool(eid) and work_running(eid) payload["active"] = running payload["started"] = running cached_hours = str(info.get("month_hours") or "") stored_hours = str(getattr(account, "month_hours", "") or "") recorded_month = str(getattr(account, "hours_month", "") or "") if recorded_month and recorded_month != month_key(now): stored_hours = "" payload["month_hours"] = cached_hours or stored_hours refresh_at = info.get("hours_refresh_at") left = 0 if running and isinstance(refresh_at, (int, float)) and not isinstance(refresh_at, bool): left = max(0, int(math.ceil(float(refresh_at) - time.time()))) payload["hours_refresh_in"] = left try: payload["monthly_target"] = int(getattr(account, "monthly_target", 0) or 0) except (TypeError, ValueError): payload["monthly_target"] = 0 return payload def _release_due(account, payload: dict) -> bool: return bool(payload["hours_met"]) and ignores_window(account) and not payload["active"] def settle(account, live: dict | None = None, now: datetime | None = None) -> bool: """跨月恢复定时;达标且当前没在学时,收回立即开始标记。""" changed = expire_pause(account, now) if _release_due(account, assemble(account, live, now)): account.study_ignore_window = False changed = True return changed def quick_state(employee_id: str) -> dict | None: """只用内存拼出首页学习状态,不读库。 内存里没有这个账号,或者有状态要写回库(跨月、达标后收回立即开始),返回 None, 调用方改用 load_state。 """ from euniv.autostudy import account_status key = (employee_id or "").strip() held = _remembered(key) if key else None if held is None: return None live = account_status(key) probe = copy.copy(held) changed = expire_pause(probe) payload = assemble(probe, live) if changed or _release_due(probe, payload): return None return payload def load_state(employee_id: str) -> dict: """读库拼出首页学习状态,把该写回的写回,并把账号字段记到内存供之后直接用。""" from euniv.autostudy import account_status from euniv.db import SessionLocal from euniv.models import Account key = (employee_id or "").strip() if not key: return dict(_EMPTY) with SessionLocal() as db: mark = _write_mark(key) account = db.get(Account, key) if account is None: forget(key) return dict(_EMPTY) live = account_status(key) if settle(account, live): db.commit() mark = _write_mark(key) return assemble(remember(account, mark), live) def state_for(employee_id: str) -> dict: payload = quick_state(employee_id) return payload if payload is not None else load_state(employee_id) def payload_for(employee_id: str) -> dict: key = (employee_id or "").strip() if not key: return dict(_EMPTY) return stamp_frame(key, state_for(key))