feat: 按账号调度自动学习并让首页实时跟上状态
This commit is contained in:
+65
-18
@@ -2,11 +2,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request, Response
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -54,6 +55,7 @@ class StudyStartBody(_BaseModel):
|
||||
hour: int
|
||||
minute: int
|
||||
second: int
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
class CourseWorkersBody(_BaseModel):
|
||||
@@ -69,6 +71,9 @@ async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
ensure_admin_seed()
|
||||
load_admin_identity()
|
||||
from euniv.study_push import attach_loop
|
||||
|
||||
attach_loop(asyncio.get_running_loop())
|
||||
stop_refresh = None
|
||||
study_worker = None
|
||||
stop_pool = None
|
||||
@@ -269,6 +274,9 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session =
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
account.monthly_target = body.monthly_target
|
||||
db.commit()
|
||||
from euniv.autostudy import sync_work
|
||||
|
||||
sync_work(employee_id)
|
||||
return {"monthly_target": account.monthly_target}
|
||||
|
||||
|
||||
@@ -293,7 +301,12 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend
|
||||
apply(account, body.day, body.hour, body.minute, body.second)
|
||||
except StudyWindowError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if body.enabled is not None:
|
||||
account.study_schedule_enabled = bool(body.enabled)
|
||||
db.commit()
|
||||
from euniv.autostudy import sync_work
|
||||
|
||||
sync_work(account.employee_id)
|
||||
return view_of(account)
|
||||
|
||||
|
||||
@@ -369,29 +382,26 @@ def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
@app.get("/api/settings/study-control")
|
||||
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.autostudy import autostudy_status
|
||||
from euniv.study_control import view_of
|
||||
from euniv.study_control import assemble, settle
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
payload = view_of(account)
|
||||
live = (autostudy_status().get("users") or {}).get(employee_id) or {}
|
||||
payload["state"] = str(live.get("state") or "")
|
||||
payload["course"] = str(live.get("course") or "")
|
||||
payload["message"] = str(live.get("message") or "")
|
||||
workers = live.get("workers") or []
|
||||
payload["workers"] = workers if isinstance(workers, list) else []
|
||||
payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
|
||||
if payload["active"]:
|
||||
payload["started"] = True
|
||||
return payload
|
||||
status = autostudy_status()
|
||||
live = dict((status.get("users") or {}).get(employee_id) or {})
|
||||
if not live.get("message"):
|
||||
live["message"] = str(status.get("message") or "")
|
||||
if settle(account, live):
|
||||
db.commit()
|
||||
return assemble(account, live)
|
||||
|
||||
|
||||
@app.post("/api/settings/study-control")
|
||||
def post_study_control(body: StudyControlBody, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
from euniv.autostudy import request_stop, request_wake
|
||||
from euniv.study_control import start_now, stop_now
|
||||
from euniv.autostudy import request_stop, sync_work
|
||||
from euniv.study_control import hours_met, start_now, stop_now
|
||||
from euniv.study_push import notify
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
@@ -399,18 +409,55 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
action = (body.action or "").strip().lower()
|
||||
if action == "start":
|
||||
start_now(account)
|
||||
db.commit()
|
||||
request_wake()
|
||||
if hours_met(account):
|
||||
from euniv.autostudy import halt_work
|
||||
|
||||
halt_work(employee_id)
|
||||
else:
|
||||
start_now(account)
|
||||
db.commit()
|
||||
sync_work(employee_id)
|
||||
elif action == "stop":
|
||||
stop_now(account)
|
||||
db.commit()
|
||||
request_stop(employee_id)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="请选择开始或停止")
|
||||
notify(employee_id, urgent=True)
|
||||
return get_study_control(request, db)
|
||||
|
||||
|
||||
@app.websocket("/api/settings/study-control/ws")
|
||||
async def study_control_ws(websocket: WebSocket):
|
||||
from euniv.study_control import payload_for
|
||||
from euniv.study_push import register, unregister
|
||||
|
||||
await websocket.accept()
|
||||
if admin_session_active(websocket.cookies):
|
||||
await websocket.close(code=4403)
|
||||
return
|
||||
employee_id = read_employee_id(websocket.cookies)
|
||||
if not employee_id:
|
||||
await websocket.close(code=4401)
|
||||
return
|
||||
from euniv.db import SessionLocal
|
||||
|
||||
with SessionLocal() as db:
|
||||
if db.get(Account, employee_id) is None:
|
||||
await websocket.close(code=4403)
|
||||
return
|
||||
register(employee_id, websocket)
|
||||
try:
|
||||
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
|
||||
while True:
|
||||
await websocket.receive_text()
|
||||
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
unregister(employee_id, websocket)
|
||||
|
||||
|
||||
@app.get("/api/home/history")
|
||||
def home_history(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
|
||||
+534
-204
File diff suppressed because it is too large
Load Diff
+162
-85
@@ -57,6 +57,96 @@ def make_kid(prefix: str = "t") -> str:
|
||||
return prefix + "".join(random.choice("1234567890") for _ in range(4))
|
||||
|
||||
|
||||
def compact_id(value: str) -> str:
|
||||
return (value or "").replace("-", "").lower()
|
||||
|
||||
|
||||
def as_uuid(value: str) -> str:
|
||||
raw = compact_id(value)
|
||||
if len(raw) != 32 or any(char not in "0123456789abcdef" for char in raw):
|
||||
return (value or "").strip()
|
||||
return f"{raw[0:8]}-{raw[8:12]}-{raw[12:16]}-{raw[16:20]}-{raw[20:32]}"
|
||||
|
||||
|
||||
def play_page_vars(html: str) -> dict[str, str]:
|
||||
text = html or ""
|
||||
|
||||
def read(name: str, default: str = "") -> str:
|
||||
quoted = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*["\']([^"\']*)["\']', text)
|
||||
if quoted:
|
||||
return quoted.group(1).strip()
|
||||
numeric = re.search(rf'(?:var\s+)?{re.escape(name)}\s*=\s*(-?\d+)', text)
|
||||
if numeric:
|
||||
return numeric.group(1).strip()
|
||||
return default
|
||||
|
||||
return {
|
||||
"knowledgeType": read("knowledgeType"),
|
||||
"submitIsOpen": read("submitIsOpen", "0"),
|
||||
"submitProTimes": read("submitProTimes", "30"),
|
||||
"validtimeSpan": read("validtimeSpan", "120"),
|
||||
"standardStudyHours": read("standardStudyHours", "0"),
|
||||
"pageSize": read("pageSize", "1"),
|
||||
"fileType": read("fileType"),
|
||||
"kngId": read("kngId"),
|
||||
"packageID": read("packageID"),
|
||||
"orgID": read("orgID"),
|
||||
"userID": read("userID"),
|
||||
}
|
||||
|
||||
|
||||
def play_page_params(html: str) -> dict:
|
||||
raw = play_page_vars(html)
|
||||
|
||||
def as_int(name: str, default: int) -> int:
|
||||
try:
|
||||
return int(raw.get(name) or default)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
return {
|
||||
**raw,
|
||||
"submitProTimes": as_int("submitProTimes", 30),
|
||||
"validtimeSpan": as_int("validtimeSpan", 120),
|
||||
"standardStudyHours": as_int("standardStudyHours", 0),
|
||||
"pageSize": max(1, as_int("pageSize", 1)),
|
||||
}
|
||||
|
||||
|
||||
def study_progress_fields(
|
||||
knowledge_id: str,
|
||||
package_id: str = "",
|
||||
*,
|
||||
page_size: int = 1,
|
||||
study_time: int = 30,
|
||||
kind: int = 0,
|
||||
view_schedule: int | float = 0,
|
||||
end: bool = False,
|
||||
chapter_id: str = "",
|
||||
for_encrypt: bool = False,
|
||||
) -> dict:
|
||||
"""抓包里 knowledgeId/packageId 带连字符;Scorm 加密体的 studyChapterIds 末尾有分号。"""
|
||||
chapter = as_uuid(chapter_id) if chapter_id else ""
|
||||
if for_encrypt and kind == 2 and chapter:
|
||||
chapter = chapter + ";"
|
||||
return {
|
||||
"knowledgeId": as_uuid(knowledge_id),
|
||||
"masterId": "",
|
||||
"masterType": "",
|
||||
"packageId": as_uuid(package_id) if package_id else "",
|
||||
"pageSize": int(page_size),
|
||||
"studySize": int(page_size),
|
||||
"studyTime": int(study_time),
|
||||
"type": int(kind),
|
||||
"offLine": False,
|
||||
"end": bool(end),
|
||||
"care": True,
|
||||
"deviceId": "",
|
||||
"studyChapterIds": chapter,
|
||||
"viewSchedule": int(view_schedule or 0),
|
||||
}
|
||||
|
||||
|
||||
def encrypt_password(public_key_b64: str, password: str) -> str:
|
||||
key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
|
||||
cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15())
|
||||
@@ -292,7 +382,7 @@ def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, b
|
||||
side = history_month_side(str(item.get("studied_at") or ""), year, month)
|
||||
if side == "in":
|
||||
minutes = item.get("minutes")
|
||||
if isinstance(minutes, int):
|
||||
if isinstance(minutes, int) and not isinstance(minutes, bool):
|
||||
total += minutes
|
||||
elif side == "before":
|
||||
reached_before = True
|
||||
@@ -300,6 +390,41 @@ def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, b
|
||||
return total, reached_before
|
||||
|
||||
|
||||
def history_hour_totals(items: list[dict], now: datetime | None = None) -> dict[str, int]:
|
||||
"""按北京时间把学时历史加成累计、本年、本月、本日分钟。"""
|
||||
from euniv.study_window import CN_TZ
|
||||
|
||||
current = now or datetime.now(CN_TZ)
|
||||
if current.tzinfo is None:
|
||||
current = current.replace(tzinfo=CN_TZ)
|
||||
else:
|
||||
current = current.astimezone(CN_TZ)
|
||||
year, month, day = current.year, current.month, current.day
|
||||
total = year_total = month_total = today_total = 0
|
||||
for item in items:
|
||||
minutes = item.get("minutes")
|
||||
if not isinstance(minutes, int) or isinstance(minutes, bool):
|
||||
continue
|
||||
stamp = history_stamp(str(item.get("studied_at") or ""))
|
||||
if stamp is None:
|
||||
continue
|
||||
total += minutes
|
||||
if stamp.year != year:
|
||||
continue
|
||||
year_total += minutes
|
||||
if stamp.month != month:
|
||||
continue
|
||||
month_total += minutes
|
||||
if stamp.day == day:
|
||||
today_total += minutes
|
||||
return {
|
||||
"year": year_total,
|
||||
"month": month_total,
|
||||
"today": today_total,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
|
||||
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int:
|
||||
"""倒序分页累加本月分钟,遇到上个月即停。"""
|
||||
offset = 0
|
||||
@@ -606,15 +731,15 @@ class QrWaiting(Exception):
|
||||
|
||||
class EunivClient:
|
||||
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
||||
from euniv.proxy import parse_proxy
|
||||
from euniv.proxy import parse_proxy, sync_httpx_client
|
||||
|
||||
self.login_name = login_name.strip()
|
||||
self.password = password
|
||||
self.proxy = parse_proxy(proxy)
|
||||
self.client = httpx.Client(
|
||||
self.client = sync_httpx_client(
|
||||
self.proxy,
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
proxy=self.proxy,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
)
|
||||
self._profile: dict = {}
|
||||
@@ -1254,29 +1379,14 @@ class EunivClient:
|
||||
html = self._site_page(path)
|
||||
from euniv.encrypt import note_play_html
|
||||
note_play_html(html, EUNIV)
|
||||
def _var(name: str, default: str = "") -> str:
|
||||
m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html)
|
||||
return m.group(1).strip() if m else default
|
||||
return {
|
||||
"knowledgeType": _var("knowledgeType"),
|
||||
"submitIsOpen": _var("submitIsOpen", "0"),
|
||||
"submitProTimes": int(_var("submitProTimes", "30") or 30),
|
||||
"validtimeSpan": int(_var("validtimeSpan", "120") or 120),
|
||||
"standardStudyHours": int(_var("standardStudyHours", "0") or 0),
|
||||
"pageSize": int(_var("pageSize", "1") or 1),
|
||||
"fileType": _var("fileType"),
|
||||
"kngId": _var("kngId"),
|
||||
"packageID": _var("packageID"),
|
||||
"orgID": _var("orgID"),
|
||||
"userID": _var("userID"),
|
||||
}
|
||||
return play_page_params(html)
|
||||
|
||||
def update_progress(self, knowledge_id: str, package_id: str = "",
|
||||
master_id: str = "", master_type: str = "") -> dict:
|
||||
"""POST /v1/study/updateprogress。返回 studyschedule, actualstudyhours, standardstudyhours, viewSchedule, status。"""
|
||||
body = {
|
||||
"knowledgeId": knowledge_id,
|
||||
"packageId": package_id,
|
||||
"knowledgeId": as_uuid(knowledge_id),
|
||||
"packageId": as_uuid(package_id) if package_id else "",
|
||||
"masterId": master_id,
|
||||
"masterType": master_type,
|
||||
}
|
||||
@@ -1286,7 +1396,7 @@ class EunivClient:
|
||||
def sync_package(self, knowledge_id: str) -> dict:
|
||||
"""GET /v1/uk/syncpackage。返回整包和各章信息。"""
|
||||
resp = self._request("GET", f"{STUDY_API}/v1/uk/syncpackage",
|
||||
params={"knowledgeId": knowledge_id, "sourceType": "SingleStudy", "masterId": ""})
|
||||
params={"knowledgeId": as_uuid(knowledge_id), "sourceType": "SingleStudy", "masterId": ""})
|
||||
return resp.json()
|
||||
|
||||
def get_encrypt_request(self, body_json: str) -> str:
|
||||
@@ -1298,24 +1408,12 @@ class EunivClient:
|
||||
study_time: int, view_schedule: int,
|
||||
master_id: str = "", master_type: str = "") -> dict:
|
||||
"""视频心跳 POST /v1/study/submitpro。"""
|
||||
param = {
|
||||
"knowledgeId": knowledge_id,
|
||||
"masterId": master_id,
|
||||
"masterType": master_type,
|
||||
"packageId": package_id,
|
||||
"pageSize": 1,
|
||||
"studySize": 1,
|
||||
"studyTime": study_time,
|
||||
"type": 0,
|
||||
"offLine": False,
|
||||
"end": False,
|
||||
"care": True,
|
||||
"deviceId": "",
|
||||
"studyChapterIds": "",
|
||||
"viewSchedule": view_schedule,
|
||||
}
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = self.get_encrypt_request(encrypt_body)
|
||||
del master_id, master_type
|
||||
param = study_progress_fields(
|
||||
knowledge_id, package_id, page_size=1, study_time=study_time,
|
||||
kind=0, view_schedule=view_schedule,
|
||||
)
|
||||
encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":")))
|
||||
param["encryption"] = encryption
|
||||
param["multiple"] = 1
|
||||
param["realHour"] = study_time
|
||||
@@ -1331,24 +1429,12 @@ class EunivClient:
|
||||
view_schedule: int,
|
||||
master_id: str = "", master_type: str = "") -> dict:
|
||||
"""文档心跳 POST /v1/study/submit。"""
|
||||
param = {
|
||||
"knowledgeId": knowledge_id,
|
||||
"masterId": master_id,
|
||||
"masterType": master_type,
|
||||
"packageId": package_id,
|
||||
"pageSize": page_size,
|
||||
"studySize": page_size,
|
||||
"studyTime": study_time,
|
||||
"type": 1,
|
||||
"offLine": False,
|
||||
"end": False,
|
||||
"care": True,
|
||||
"deviceId": "",
|
||||
"studyChapterIds": "",
|
||||
"viewSchedule": view_schedule,
|
||||
}
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = self.get_encrypt_request(encrypt_body)
|
||||
del master_id, master_type
|
||||
param = study_progress_fields(
|
||||
knowledge_id, package_id, page_size=page_size, study_time=study_time,
|
||||
kind=1, view_schedule=view_schedule,
|
||||
)
|
||||
encryption = self.get_encrypt_request(json.dumps(param, separators=(",", ":")))
|
||||
param["multiple"] = 1
|
||||
param["realHour"] = study_time
|
||||
resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||||
@@ -1360,26 +1446,16 @@ class EunivClient:
|
||||
end: bool = False,
|
||||
master_id: str = "", master_type: str = "") -> dict:
|
||||
"""Scorm 心跳 POST /v1/study/submit,type=2。"""
|
||||
param = {
|
||||
"knowledgeId": knowledge_id,
|
||||
"masterId": master_id,
|
||||
"masterType": master_type,
|
||||
"packageId": package_id,
|
||||
"pageSize": -1 if end else 1,
|
||||
"studySize": -1 if end else 1,
|
||||
"studyTime": study_time,
|
||||
"type": 2,
|
||||
"offLine": False,
|
||||
"end": end,
|
||||
"care": True,
|
||||
"deviceId": "",
|
||||
"studyChapterIds": sco_id,
|
||||
"viewSchedule": 0,
|
||||
}
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = self.get_encrypt_request(encrypt_body)
|
||||
param["multiple"] = 1
|
||||
param["realHour"] = study_time
|
||||
del master_id, master_type
|
||||
encrypt_param = study_progress_fields(
|
||||
knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time,
|
||||
kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True,
|
||||
)
|
||||
encryption = self.get_encrypt_request(json.dumps(encrypt_param, separators=(",", ":")))
|
||||
param = study_progress_fields(
|
||||
knowledge_id, package_id, page_size=-1 if end else 1, study_time=study_time,
|
||||
kind=2, view_schedule=0, end=end, chapter_id=sco_id,
|
||||
)
|
||||
resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||||
content=json.dumps(param, separators=(",", ":")))
|
||||
return {}
|
||||
@@ -1387,7 +1463,7 @@ class EunivClient:
|
||||
def scorm_count(self, knowledge_id: str) -> int:
|
||||
"""GET /v1/kng/scorm/count/。"""
|
||||
resp = self._request("GET", f"{STUDY_API}/v1/kng/scorm/count/",
|
||||
params={"knowledgeId": knowledge_id})
|
||||
params={"knowledgeId": as_uuid(knowledge_id)})
|
||||
data = resp.json()
|
||||
return int(data.get("scocnt") or 1)
|
||||
|
||||
@@ -1408,11 +1484,11 @@ class EunivClient:
|
||||
"sessionId": session_id,
|
||||
"orgId": org_id,
|
||||
"userId": user_id,
|
||||
"scormId": scorm_id,
|
||||
"scormIdOri": scorm_id_ori,
|
||||
"scormId": as_uuid(scorm_id),
|
||||
"scormIdOri": as_uuid(scorm_id_ori),
|
||||
"masterId": master_id,
|
||||
"masterType": master_type,
|
||||
"packageId": package_id,
|
||||
"packageId": as_uuid(package_id) if package_id else "",
|
||||
"scocnt": sco_cnt,
|
||||
"data": data,
|
||||
}
|
||||
@@ -1421,7 +1497,8 @@ class EunivClient:
|
||||
|
||||
def scorm_page_files(self, knowledge_id: str) -> list[str]:
|
||||
"""下载 Scorm 课件的页索引,返回各页 .oss.js 的 URL 列表。"""
|
||||
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/index-scorm.js"
|
||||
compact = compact_id(knowledge_id)
|
||||
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js"
|
||||
resp = self.client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
|
||||
urls = []
|
||||
for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text):
|
||||
@@ -1433,7 +1510,7 @@ class EunivClient:
|
||||
elif raw.startswith("/"):
|
||||
urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}")
|
||||
else:
|
||||
urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/{raw}")
|
||||
urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}")
|
||||
return urls
|
||||
|
||||
def scorm_extract_answers(self, knowledge_id: str) -> list[dict]:
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false
|
||||
from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false, true as sql_true
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ class Account(Base):
|
||||
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
|
||||
month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
|
||||
hours_month: Mapped[str] = mapped_column(String(7), nullable=False, default="", server_default="")
|
||||
monthly_target: Mapped[int] = mapped_column(nullable=False, default=600, server_default="600")
|
||||
proxy_scheme: Mapped[str] = mapped_column(String(16), nullable=False, default="", server_default="")
|
||||
proxy_host: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="")
|
||||
@@ -59,7 +60,9 @@ class Account(Base):
|
||||
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
|
||||
use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
study_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
study_stop_month: Mapped[str] = mapped_column(String(7), nullable=False, default="", server_default="")
|
||||
study_ignore_window: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
|
||||
study_schedule_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=sql_true())
|
||||
|
||||
|
||||
class ProxyNode(Base):
|
||||
|
||||
+29
-1
@@ -7,6 +7,7 @@ from urllib.parse import quote, urlparse
|
||||
import httpx
|
||||
|
||||
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
||||
SOCKS_SCHEMES = ("socks4", "socks5", "socks5h")
|
||||
OFF_SCHEMES = ("", "off", "none", "direct", "close")
|
||||
POOL_SCHEMES = ("pool", "auto")
|
||||
|
||||
@@ -16,7 +17,7 @@ class ProxyError(ValueError):
|
||||
|
||||
|
||||
def parse_proxy(value: str | None) -> str | None:
|
||||
"""把代理地址规范成 httpx 可用的 URL。空值表示直连。"""
|
||||
"""把代理地址规范成内部使用的 URL。空值表示直连。"""
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
@@ -182,6 +183,33 @@ def bind_url(account) -> str | None:
|
||||
return url_of(account)
|
||||
|
||||
|
||||
def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict:
|
||||
"""httpx 不认 socks4;SOCKS 走 httpx-socks 传输,HTTP/HTTPS 仍用 proxy=。"""
|
||||
url = parse_proxy(proxy)
|
||||
if not url:
|
||||
return {}
|
||||
scheme = urlparse(url).scheme.lower()
|
||||
if scheme in SOCKS_SCHEMES:
|
||||
if asynchronous:
|
||||
from httpx_socks import AsyncProxyTransport
|
||||
|
||||
return {"transport": AsyncProxyTransport.from_url(url)}
|
||||
from httpx_socks import SyncProxyTransport
|
||||
|
||||
return {"transport": SyncProxyTransport.from_url(url)}
|
||||
return {"proxy": url}
|
||||
|
||||
|
||||
def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client:
|
||||
kwargs.update(client_proxy_args(proxy))
|
||||
return httpx.Client(**kwargs)
|
||||
|
||||
|
||||
def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient:
|
||||
kwargs.update(client_proxy_args(proxy, asynchronous=True))
|
||||
return httpx.AsyncClient(**kwargs)
|
||||
|
||||
|
||||
def is_proxy_failure(exc: BaseException) -> bool:
|
||||
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)):
|
||||
return True
|
||||
|
||||
@@ -17,7 +17,7 @@ from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
|
||||
from euniv.collectors import collect_all, is_china, source_title
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import ProxyNode, ProxyPoolSync
|
||||
from euniv.proxy import build_proxy_url
|
||||
from euniv.proxy import build_proxy_url, sync_httpx_client
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -170,8 +170,8 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
samples: list[int] = []
|
||||
reasons: list[str] = []
|
||||
try:
|
||||
with httpx.Client(
|
||||
proxy=url,
|
||||
with sync_httpx_client(
|
||||
url,
|
||||
timeout=LATENCY_LIMIT,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
@@ -202,9 +202,11 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
|
||||
|
||||
def _short_reason(exc: BaseException) -> str:
|
||||
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException)):
|
||||
from python_socks import ProxyConnectionError, ProxyTimeoutError
|
||||
|
||||
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)):
|
||||
return "超时"
|
||||
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError)):
|
||||
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)):
|
||||
return "无法连接"
|
||||
text = str(exc).strip() or type(exc).__name__
|
||||
return text[:200]
|
||||
|
||||
@@ -18,6 +18,7 @@ from euniv.client import (
|
||||
ManualJigsaw,
|
||||
QrWaiting,
|
||||
SessionExpired,
|
||||
history_hour_totals,
|
||||
is_qr_password,
|
||||
)
|
||||
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||
@@ -248,11 +249,11 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d
|
||||
|
||||
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
"""向 e 学现查首页信息。个人信息只出现在返回值里,不写入数据库。凭证变化时更新密文。"""
|
||||
return _live(db, employee_id, client_factory, lambda client: client.home_snapshot())
|
||||
return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_snapshot()))
|
||||
|
||||
|
||||
def fetch_home_summary(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
return _live(db, employee_id, client_factory, lambda client: client.home_summary())
|
||||
return _live(db, employee_id, client_factory, lambda client: _apply_hours_source(client, client.home_summary()))
|
||||
|
||||
|
||||
def fetch_home_exams(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
@@ -272,10 +273,57 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto
|
||||
|
||||
|
||||
def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||
items = _live(db, employee_id, client_factory, lambda client: client.study_history())
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
return {"items": items, "total": len(items)}
|
||||
def read(client):
|
||||
items = client.study_history()
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
hours = _hour_fields(_apply_hours_source(client, _api_hour_fields(client), items))
|
||||
return {"items": items, "total": len(items), **hours}
|
||||
|
||||
return _live(db, employee_id, client_factory, read)
|
||||
|
||||
|
||||
def _apply_hours_source(client, summary: dict, items: list | None = None) -> dict:
|
||||
from admin.settings import hours_source_of
|
||||
|
||||
data = dict(summary)
|
||||
source = hours_source_of()
|
||||
data["hours_source"] = source
|
||||
if source != "history":
|
||||
return data
|
||||
if items is None:
|
||||
raw = client.study_history()
|
||||
items = raw if isinstance(raw, list) else []
|
||||
totals = history_hour_totals(items)
|
||||
data["year_hours"] = totals["year"]
|
||||
data["month_hours"] = totals["month"]
|
||||
data["today_hours"] = totals["today"]
|
||||
data["total_hours"] = totals["total"]
|
||||
return data
|
||||
|
||||
|
||||
def _api_hour_fields(client) -> dict:
|
||||
from admin.settings import hours_source_of
|
||||
|
||||
if hours_source_of() == "history":
|
||||
return {}
|
||||
summary = client.home_summary()
|
||||
return {
|
||||
"year_hours": summary.get("year_hours"),
|
||||
"month_hours": summary.get("month_hours"),
|
||||
"today_hours": summary.get("today_hours"),
|
||||
"total_hours": summary.get("total_hours"),
|
||||
}
|
||||
|
||||
|
||||
def _hour_fields(data: dict) -> dict:
|
||||
return {
|
||||
"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"),
|
||||
}
|
||||
|
||||
|
||||
def _auto_attempts(db: Session) -> int:
|
||||
@@ -415,7 +463,9 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
|
||||
pass
|
||||
record_outcome(account, valid)
|
||||
if hours:
|
||||
account.month_hours = hours
|
||||
from euniv.study_control import stamp_hours
|
||||
|
||||
stamp_hours(account, hours)
|
||||
db.commit()
|
||||
if checked_alive:
|
||||
_request_course_sync(employee_id)
|
||||
@@ -491,6 +541,17 @@ def start_credential_refresh() -> _RefreshGate:
|
||||
|
||||
|
||||
def _month_hours(client) -> str:
|
||||
from admin.settings import hours_source_of
|
||||
|
||||
if hours_source_of() == "history":
|
||||
reader = getattr(client, "month_history_minutes", None)
|
||||
if reader is None:
|
||||
return ""
|
||||
try:
|
||||
value = reader()
|
||||
except Exception:
|
||||
return ""
|
||||
return str(value) if isinstance(value, int) and not isinstance(value, bool) else ""
|
||||
reader = getattr(client, "month_hours", None)
|
||||
if reader is None:
|
||||
return ""
|
||||
|
||||
+133
-11
@@ -2,7 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from euniv.study_window import window_open
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from euniv.study_window import month_key, window_open
|
||||
|
||||
|
||||
class StudyControlError(ValueError):
|
||||
@@ -11,38 +14,157 @@ class StudyControlError(ValueError):
|
||||
|
||||
def start_now(account) -> None:
|
||||
account.study_paused = False
|
||||
account.study_stop_month = ""
|
||||
account.study_ignore_window = True
|
||||
|
||||
|
||||
def stop_now(account) -> None:
|
||||
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 is_paused(account) -> bool:
|
||||
return bool(getattr(account, "study_paused", False))
|
||||
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 eligible(account) -> bool:
|
||||
if is_paused(account):
|
||||
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:
|
||||
"""本月停止不影响下月定时。遗留的无月份暂停记到当月。"""
|
||||
if not bool(getattr(account, "study_paused", False)):
|
||||
return False
|
||||
key = month_key(now)
|
||||
recorded = str(getattr(account, "study_stop_month", "") or "")
|
||||
if not recorded:
|
||||
account.study_stop_month = key
|
||||
return True
|
||||
if recorded != key:
|
||||
account.study_paused = False
|
||||
account.study_stop_month = ""
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
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
|
||||
return window_open(account)
|
||||
if not schedule_enabled(account):
|
||||
return False
|
||||
return window_open(account, now)
|
||||
|
||||
|
||||
def view_of(account) -> dict:
|
||||
paused = is_paused(account)
|
||||
def view_of(account, now: datetime | None = None) -> dict:
|
||||
paused = is_paused(account, now)
|
||||
ignore = ignores_window(account)
|
||||
opened = window_open(account)
|
||||
started = (not paused) and (ignore or opened)
|
||||
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 assemble(account, live: dict | None = None, now: datetime | None = None) -> dict:
|
||||
payload = view_of(account, now)
|
||||
info = live if isinstance(live, dict) else {}
|
||||
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"] = 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 "")
|
||||
payload["month_hours"] = cached_hours or str(getattr(account, "month_hours", "") or "")
|
||||
try:
|
||||
payload["monthly_target"] = int(getattr(account, "monthly_target", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
payload["monthly_target"] = 0
|
||||
return payload
|
||||
|
||||
|
||||
def settle(account, live: dict | None = None, now: datetime | None = None) -> bool:
|
||||
"""跨月恢复定时;达标且当前没在学时,收回立即开始标记。"""
|
||||
changed = expire_pause(account, now)
|
||||
payload = assemble(account, live, now)
|
||||
if payload["hours_met"] and ignores_window(account) and not payload["active"]:
|
||||
account.study_ignore_window = False
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
|
||||
def payload_for(employee_id: str) -> dict:
|
||||
from euniv.autostudy import autostudy_status
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import Account
|
||||
|
||||
key = (employee_id or "").strip()
|
||||
empty = {
|
||||
"started": False,
|
||||
"paused": True,
|
||||
"hours_met": False,
|
||||
"schedule_enabled": True,
|
||||
"workers": [],
|
||||
"active": False,
|
||||
"message": "",
|
||||
}
|
||||
if not key:
|
||||
return empty
|
||||
with SessionLocal() as db:
|
||||
account = db.get(Account, key)
|
||||
if account is None:
|
||||
return empty
|
||||
status = autostudy_status()
|
||||
live = dict((status.get("users") or {}).get(key) or {})
|
||||
if not live.get("message"):
|
||||
live["message"] = str(status.get("message") or "")
|
||||
if settle(account, live):
|
||||
db.commit()
|
||||
return assemble(account, live)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""把自动学习状态推到首页 WebSocket。https 页面自动走 wss。
|
||||
|
||||
心跳等高频更新最多每 3 秒发一帧,只发当前最新快照。
|
||||
开始/停止等控制变化立刻推。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
|
||||
from fastapi import WebSocket
|
||||
from starlette.websockets import WebSocketState
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_PUSH_SECONDS = 3.0
|
||||
|
||||
_loop: asyncio.AbstractEventLoop | None = None
|
||||
_clients: dict[str, set[WebSocket]] = defaultdict(set)
|
||||
_pending: dict[str, asyncio.TimerHandle] = {}
|
||||
_inflight: set[str] = set()
|
||||
_dirty: set[str] = set()
|
||||
_urgent: set[str] = set()
|
||||
_last_flush: dict[str, float] = {}
|
||||
_latest: dict[str, dict] = {}
|
||||
|
||||
|
||||
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
|
||||
global _loop
|
||||
_loop = loop
|
||||
|
||||
|
||||
def register(employee_id: str, ws: WebSocket) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return
|
||||
_clients[key].add(ws)
|
||||
|
||||
|
||||
def unregister(employee_id: str, ws: WebSocket) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
group = _clients.get(key)
|
||||
if not group:
|
||||
return
|
||||
group.discard(ws)
|
||||
if not group:
|
||||
_clients.pop(key, None)
|
||||
|
||||
|
||||
def notify(employee_id: str | None = None, urgent: bool = False) -> None:
|
||||
loop = _loop
|
||||
if loop is None or not loop.is_running():
|
||||
return
|
||||
keys = [(employee_id or "").strip()] if employee_id else list(_clients)
|
||||
for key in keys:
|
||||
if key:
|
||||
loop.call_soon_threadsafe(_mark, key, urgent)
|
||||
|
||||
|
||||
def latest_of(employee_id: str) -> dict | None:
|
||||
key = (employee_id or "").strip()
|
||||
payload = _latest.get(key)
|
||||
return dict(payload) if payload else None
|
||||
|
||||
|
||||
def _mark(employee_id: str, urgent: bool) -> None:
|
||||
_dirty.add(employee_id)
|
||||
if urgent:
|
||||
_urgent.add(employee_id)
|
||||
_arm(employee_id, 0.0)
|
||||
return
|
||||
if employee_id in _pending or employee_id in _inflight:
|
||||
return
|
||||
loop = asyncio.get_running_loop()
|
||||
wait = max(0.0, _PUSH_SECONDS - (loop.time() - _last_flush.get(employee_id, 0.0)))
|
||||
_arm(employee_id, wait)
|
||||
|
||||
|
||||
def _arm(employee_id: str, delay: float) -> None:
|
||||
old = _pending.pop(employee_id, None)
|
||||
if old is not None:
|
||||
old.cancel()
|
||||
loop = asyncio.get_running_loop()
|
||||
if delay <= 0:
|
||||
if employee_id in _inflight:
|
||||
return
|
||||
loop.create_task(_flush(employee_id))
|
||||
return
|
||||
_pending[employee_id] = loop.call_later(delay, lambda: asyncio.create_task(_flush(employee_id)))
|
||||
|
||||
|
||||
async def _flush(employee_id: str) -> None:
|
||||
_pending.pop(employee_id, None)
|
||||
sockets = list(_clients.get(employee_id) or ())
|
||||
if not sockets:
|
||||
_dirty.discard(employee_id)
|
||||
_urgent.discard(employee_id)
|
||||
return
|
||||
_inflight.add(employee_id)
|
||||
try:
|
||||
_dirty.discard(employee_id)
|
||||
_urgent.discard(employee_id)
|
||||
from euniv.study_control import payload_for
|
||||
|
||||
payload = await asyncio.to_thread(payload_for, employee_id)
|
||||
_latest[employee_id] = payload
|
||||
_last_flush[employee_id] = asyncio.get_running_loop().time()
|
||||
dead: list[WebSocket] = []
|
||||
for ws in sockets:
|
||||
try:
|
||||
if ws.client_state != WebSocketState.CONNECTED:
|
||||
dead.append(ws)
|
||||
continue
|
||||
await ws.send_json(payload)
|
||||
except Exception:
|
||||
dead.append(ws)
|
||||
for ws in dead:
|
||||
unregister(employee_id, ws)
|
||||
except Exception:
|
||||
log.debug("学习状态快照失败", exc_info=True)
|
||||
finally:
|
||||
_inflight.discard(employee_id)
|
||||
if employee_id in _dirty:
|
||||
delay = 0.0 if employee_id in _urgent else _PUSH_SECONDS
|
||||
_arm(employee_id, delay)
|
||||
@@ -45,22 +45,32 @@ def view_of(account) -> dict:
|
||||
hour = int(getattr(account, "study_start_hour", 0) or 0)
|
||||
minute = int(getattr(account, "study_start_minute", 0) or 0)
|
||||
second = int(getattr(account, "study_start_second", 0) or 0)
|
||||
enabled = getattr(account, "study_schedule_enabled", True)
|
||||
return {
|
||||
"day": day,
|
||||
"hour": hour,
|
||||
"minute": minute,
|
||||
"second": second,
|
||||
"enabled": False if enabled is False else True,
|
||||
"label": label_of(account),
|
||||
}
|
||||
|
||||
|
||||
def window_open(account, now: datetime | None = None) -> bool:
|
||||
"""当前是否已过该账号本月开始时刻。2 月 31 日等按当月最后一天。"""
|
||||
def as_cn(now: datetime | None = None) -> datetime:
|
||||
current = now or datetime.now(CN_TZ)
|
||||
if current.tzinfo is None:
|
||||
current = current.replace(tzinfo=CN_TZ)
|
||||
else:
|
||||
current = current.astimezone(CN_TZ)
|
||||
return current.replace(tzinfo=CN_TZ)
|
||||
return current.astimezone(CN_TZ)
|
||||
|
||||
|
||||
def month_key(now: datetime | None = None) -> str:
|
||||
current = as_cn(now)
|
||||
return f"{current.year:04d}-{current.month:02d}"
|
||||
|
||||
|
||||
def start_at(account, now: datetime | None = None) -> datetime:
|
||||
"""该账号在 now 所在月的开始时刻。2 月 31 日等按当月最后一天。"""
|
||||
current = as_cn(now)
|
||||
day, hour, minute, second = validate_start(
|
||||
int(getattr(account, "study_start_day", 1) or 1),
|
||||
int(getattr(account, "study_start_hour", 0) or 0),
|
||||
@@ -68,7 +78,7 @@ def window_open(account, now: datetime | None = None) -> bool:
|
||||
int(getattr(account, "study_start_second", 0) or 0),
|
||||
)
|
||||
last = calendar.monthrange(current.year, current.month)[1]
|
||||
start = datetime(
|
||||
return datetime(
|
||||
current.year,
|
||||
current.month,
|
||||
min(day, last),
|
||||
@@ -77,4 +87,28 @@ def window_open(account, now: datetime | None = None) -> bool:
|
||||
second,
|
||||
tzinfo=CN_TZ,
|
||||
)
|
||||
return current >= start
|
||||
|
||||
|
||||
def window_open(account, now: datetime | None = None) -> bool:
|
||||
"""当前是否已过该账号本月开始时刻。"""
|
||||
current = as_cn(now)
|
||||
return current >= start_at(account, current)
|
||||
|
||||
|
||||
def next_month_start(now: datetime | None = None) -> datetime:
|
||||
current = as_cn(now)
|
||||
if current.month == 12:
|
||||
return datetime(current.year + 1, 1, 1, tzinfo=CN_TZ)
|
||||
return datetime(current.year, current.month + 1, 1, tzinfo=CN_TZ)
|
||||
|
||||
|
||||
def next_fire_at(account, now: datetime | None = None) -> datetime | None:
|
||||
"""下次定时触发。本月已到点则等到下月;关闭定时则没有下一次。"""
|
||||
enabled = getattr(account, "study_schedule_enabled", True)
|
||||
if enabled is False:
|
||||
return None
|
||||
current = as_cn(now)
|
||||
this = start_at(account, current)
|
||||
if current < this:
|
||||
return this
|
||||
return start_at(account, next_month_start(current))
|
||||
|
||||
Reference in New Issue
Block a user