feat: 按账号调度自动学习并让首页实时跟上状态
This commit is contained in:
+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]:
|
||||
|
||||
Reference in New Issue
Block a user