// ==UserScript==
// @name 【效率版】木玛成人教育55zs学习助手
// @namespace https://card.wlxy.live/
// @version 1.0
// @author 柠檬真酸
// @icon https://huaweicloudobs.ahjxjy.cn/895789f9086469785b846d30c0ed95f9.png
// @description 木玛成人教育55zs学习助手:自动完成视频学时与作业,会员授权;免费体验5章节,Pro不限,几分钟完成当前学期所有课时、作业,考试功能后期开放!
// @antifeature payment 免费体验5章节,升级Pro不限课时/作业
// @antifeature membership 需云端授权
// @match https://*.55zs.com/*
// @match http://*.55zs.com/*
// @connect *.55zs.com
// @connect 55zs.com
// @connect oa52.ahzsksw.cn
// @connect oa888.ahzsksw.cn
// @connect *.ahzsksw.cn
// @connect ahzsksw.cn
// @connect card.wlxy.live
// @connect huaweicloudobs.ahjxjy.cn
// @grant GM_xmlhttpRequest
// @grant GM_info
// @grant GM_openInTab
// @run-at document-idle
// @license All Rights Reserved
// ==/UserScript==
(function () {
"use strict";
(function bindOa888GlobalImportantNotice() {
const GLOBAL_NOTICE_JSON =
"https://oa888.ahzsksw.cn/api/global/important-notice.json";
const HOST_ID = "oa888-global-bubble-host-zs55";
if (document.getElementById(HOST_ID)) return;
const host = document.createElement("div");
host.id = HOST_ID;
host.style.cssText =
"all:initial;position:fixed;right:16px;bottom:16px;z-index:2147483000;font-family:system-ui,sans-serif;";
document.documentElement.appendChild(host);
const shadow = host.attachShadow({ mode: "open" });
fetch(GLOBAL_NOTICE_JSON, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((j) => {
if (!j || !j.enabled || !j.text) return;
const box = document.createElement("div");
box.style.cssText =
"max-width:280px;padding:10px 12px;border-radius:10px;background:#fff7ed;border:1px solid #fdba74;color:#9a3412;font-size:12px;line-height:1.45;box-shadow:0 8px 24px rgba(0,0,0,.12);";
box.textContent = String(j.text);
shadow.appendChild(box);
})
.catch(() => {});
})();
const HOST = String(location.hostname || "").toLowerCase();
const CLOUD_BASE = "https://oa52.ahzsksw.cn";
const PRO_BUY_URL = "https://card.wlxy.live/details/5CD532F9";
const TOKEN_KEY = "zs55_pro_token";
const QUEUE_KEY = "zs55_queue";
const MODE_KEY = "zs55_mode";
const POS_KEY = "zs55_panel_pos_v1";
const COLLAPSED_KEY = "zs55_panel_collapsed_v1";
const LEARNING_UID_KEY = "zs55_learning_uid";
const MODE_EFF = "eff";
const MODE_RT = "rt";
const DONE_RATIO = 0.98;
const HW_DONE_SCORE = 95;
const SCRIPT_VERSION =
(typeof GM_info !== "undefined" && GM_info?.script?.version) || "1.0";
const PANEL_LOGO_URL =
"https://huaweicloudobs.ahjxjy.cn/895789f9086469785b846d30c0ed95f9.png";
const PANEL_NOTICE_FALLBACK =
"\u6728\u739b55zs\u6210\u4eba\u6559\u80b2\u5b66\u4e60\u52a9\u624b\uff1a\u514d\u8d39\u4f53\u9a8c 5 \u4e2a\u7ae0\u8282\uff1b\u4e13\u4e1a\u7248\u53ef\u5b66\u8bfe\u65f6\u3001\u4f5c\u4e1a\u3002\u6fc0\u6d3b\u540e 30 \u5929\u6709\u6548\u3002";
const state = {
busy: false,
examBusy: false,
stopFlag: false,
courses: [],
homeworks: [],
queue: [],
mode: localStorage.getItem(MODE_KEY) === MODE_RT ? MODE_RT : MODE_EFF,
logLines: [],
currentCourse: "",
currentTask: "\u70b9\u5f00\u59cb\u540e\u81ea\u52a8\u5b66\u4e60",
cloudTier: "free",
cloudLease: "",
cloudToken: localStorage.getItem(TOKEN_KEY) || "",
leaseExp: 0,
freeChapterLimit: 5,
freeUsedChapters: 0,
canHomework: false,
canExam: false,
proExpiresAt: 0,
proExpiresText: "",
proBuyUrl: PRO_BUY_URL,
panelNotice: PANEL_NOTICE_FALLBACK,
learningUserId: "",
chapterCache: Object.create(null),
previewChapters: [],
queueDone: 0,
queueTotal: 0,
};
try {
state.queue = JSON.parse(localStorage.getItem(QUEUE_KEY) || "[]");
if (!Array.isArray(state.queue)) state.queue = [];
} catch (_) {
state.queue = [];
}
function sleep(ms) {
return new Promise((r) => setTimeout(r, Math.max(0, ms | 0)));
}
function escapeHtml(s) {
return String(s || "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
}
function saveJson(key, val) {
localStorage.setItem(key, JSON.stringify(val));
}
function formatSec(sec) {
const n = Math.max(0, Math.floor(Number(sec) || 0));
const m = Math.floor(n / 60);
const s = n % 60;
return m + ":" + String(s).padStart(2, "0");
}
function log(msg, level) {
const text = String(msg || "");
state.logLines.unshift({
t: Date.now(),
text,
level: level === "warn" ? "warn" : "info",
});
if (state.logLines.length > 120) state.logLines.length = 120;
renderRunLog();
updatePanel();
}
function renderRunLog() {
const box = document.getElementById("zs55-run-log");
if (!box) return;
box.innerHTML = state.logLines
.slice(0, 60)
.map((row) => {
const cls = row.level === "warn" ? " zs55-log-warn" : "";
const ts = new Date(row.t).toLocaleTimeString();
return `
[${ts}] ${escapeHtml(row.text)}
`;
})
.join("");
}
function showProAlert(text) {
const tip = document.getElementById("zs55-start-hint");
if (tip) {
tip.textContent = String(text || "");
tip.style.display = text ? "block" : "none";
}
switchTab("settings");
}
function readCookie(name) {
const m = document.cookie.match(
new RegExp("(?:^|; )" + name.replace(/([.$?*|{}()[\]\\/+^])/g, "\\$1") + "=([^;]*)")
);
return m ? decodeURIComponent(m[1]) : "";
}
function cookieByPrefix(prefix) {
const hostKey = prefix + HOST;
const direct =
readCookie(hostKey) ||
readCookie(prefix) ||
localStorage.getItem(hostKey) ||
localStorage.getItem(prefix) ||
"";
if (direct) return direct;
try {
const parts = String(document.cookie || "").split(";");
for (const raw of parts) {
const i = raw.indexOf("=");
if (i < 0) continue;
const k = raw.slice(0, i).trim();
const v = decodeURIComponent(raw.slice(i + 1).trim());
if (k === hostKey || k === prefix || k.startsWith(prefix)) return v;
}
} catch (_) {}
return "";
}
function platformToken() {
return cookieByPrefix("USER_TOKEN") || localStorage.getItem("token") || "";
}
function tenantId() {
const fromCookie = cookieByPrefix("TENANT_ID");
if (fromCookie) return fromCookie;
try {
const tok = platformToken();
const mid = tok.split(".")[1];
if (!mid) return "";
const json = JSON.parse(
decodeURIComponent(
atob(mid.replace(/-/g, "+").replace(/_/g, "/"))
.split("")
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
.join("")
)
);
const userData = JSON.parse(json.userData || "{}");
return String(userData.userId || "").trim();
} catch (_) {
return "";
}
}
function semesterId() {
return cookieByPrefix("SEMESTER_ID");
}
function isLoggedIn() {
return !!platformToken() && !!semesterId();
}
function resolveLearningUserId() {
const tid = tenantId();
const next = tid ? "tenant-" + tid : "";
const prev = state.learningUserId || localStorage.getItem(LEARNING_UID_KEY) || "";
if (next && prev && next !== prev) {
state.cloudLease = "";
state.leaseExp = 0;
state.cloudTier = "free";
state.canHomework = false;
state.canExam = false;
state.learningUserId = next;
localStorage.setItem(LEARNING_UID_KEY, next);
return next;
}
if (next) {
state.learningUserId = next;
localStorage.setItem(LEARNING_UID_KEY, next);
return next;
}
if (state.learningUserId) return state.learningUserId;
let uid = localStorage.getItem(LEARNING_UID_KEY) || "";
if (!uid) {
uid = "local-" + Math.random().toString(36).slice(2) + Date.now().toString(36);
localStorage.setItem(LEARNING_UID_KEY, uid);
}
state.learningUserId = uid;
return uid;
}
function gmHttp(url, method, headers, body) {
return new Promise((resolve, reject) => {
const done = (status, text) => resolve({ status, text: text || "" });
if (typeof GM_xmlhttpRequest === "function") {
GM_xmlhttpRequest({
method: method || "GET",
url,
headers: headers || {},
data: body == null ? undefined : typeof body === "string" ? body : JSON.stringify(body),
withCredentials: true,
timeout: 60000,
onload: (r) => done(r.status, r.responseText || ""),
onerror: () => reject(new Error("\u7f51\u7edc\u9519\u8bef")),
ontimeout: () => reject(new Error("\u8bf7\u6c42\u8d85\u65f6")),
});
} else {
fetch(url, {
method: method || "GET",
headers: headers || {},
credentials: "include",
body: body == null ? undefined : JSON.stringify(body),
})
.then(async (r) => done(r.status, await r.text()))
.catch(() => reject(new Error("\u7f51\u7edc\u9519\u8bef")));
}
});
}
async function platformJson(method, path, body) {
const url = location.origin + (path.startsWith("/") ? path : "/" + path);
const headers = {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
};
const token = platformToken();
const tid = tenantId();
if (token) headers.token = token;
if (tid) headers["TENANT-ID"] = tid;
const res = await gmHttp(url, method, headers, body);
let j = null;
try {
j = JSON.parse(res.text || "{}");
} catch (_) {
throw new Error("\u5e73\u53f0\u54cd\u5e94\u5f02\u5e38");
}
if (res.status === 401 || j?.code === 401) throw new Error("\u767b\u5f55\u5df2\u5931\u6548");
if (res.status >= 400) throw new Error("\u5e73\u53f0\u8bf7\u6c42\u5931\u8d25");
return j;
}
async function cloudJson(path, method, payload) {
const url = CLOUD_BASE + (path.startsWith("/") ? path : "/" + path);
const headers = { Accept: "application/json", "Content-Type": "application/json" };
const luid = resolveLearningUserId();
if (luid) headers["x-learning-user-id"] = luid;
if (state.cloudToken) headers.Authorization = "Bearer " + state.cloudToken;
const res = await gmHttp(url, method || "GET", headers, payload);
let j = null;
try {
j = JSON.parse(res.text || "{}");
} catch (_) {
j = { ok: false, message: "\u4e91\u7aef\u54cd\u5e94\u5f02\u5e38" };
}
j._http = res.status;
return j;
}
function formatExpireText(ts, fallback) {
const n = Number(ts);
if (n > 0) {
try {
return new Date(n * 1000).toLocaleString("zh-CN", {
timeZone: "Asia/Shanghai",
hour12: false,
});
} catch (_) {}
}
return String(fallback || "");
}
function applyLeasePayload(data) {
if (!data || typeof data !== "object") return;
if (data.lease) state.cloudLease = String(data.lease);
if (data.exp) state.leaseExp = Number(data.exp) || 0;
if (data.tier) state.cloudTier = String(data.tier);
const lim = data.free_chapter_limit ?? data.freeChapterLimit ?? data.free_course_limit;
if (lim != null) state.freeChapterLimit = Number(lim) || 5;
const used = data.free_used_chapters ?? data.freeUsedChapters ?? data.free_used_courses;
if (used != null) state.freeUsedChapters = Number(used) || 0;
state.canHomework = !!data.can_homework || state.cloudTier === "pro";
state.canExam = !!data.can_exam;
if (data.proBuyUrl) state.proBuyUrl = String(data.proBuyUrl);
if (data.panelNotice) state.panelNotice = String(data.panelNotice);
if (data.pro_expires_at != null) state.proExpiresAt = Number(data.pro_expires_at) || 0;
if (state.cloudTier === "pro") {
state.proExpiresText = formatExpireText(
state.proExpiresAt,
data.pro_expires_at_text || ""
);
} else {
state.proExpiresAt = 0;
state.proExpiresText = "";
}
}
async function ensureCloudLease(force) {
resolveLearningUserId();
const now = Math.floor(Date.now() / 1000);
if (!force && state.cloudLease && state.leaseExp > now + 30) return state.cloudLease;
const data = await cloudJson("/api/zs55/lease", "POST", {
learning_user_id: resolveLearningUserId(),
});
const msg = String(data.message || data.detail || "");
if (
data._http === 403 ||
/token_bound_to_other_learning_user|learning_user_mismatch/i.test(msg)
) {
state.cloudLease = "";
state.leaseExp = 0;
state.cloudTier = "free";
state.canHomework = false;
state.canExam = false;
state.proExpiresAt = 0;
state.proExpiresText = "";
state.cloudToken = "";
localStorage.removeItem(TOKEN_KEY);
const tip = "\u5f53\u524d\u8d26\u53f7\u4e0e\u4e13\u4e1a\u7248\u7ed1\u5b9a\u4e0d\u7b26\uff0c\u5df2\u9000\u51fa Pro";
showProAlert(tip);
throw new Error(tip);
}
if (data._http >= 400 || data.ok === false) {
throw new Error(msg || "\u6388\u6743\u5931\u8d25");
}
applyLeasePayload(data);
if (!state.cloudLease) throw new Error("\u672a\u53d6\u5f97\u6388\u6743\u51ed\u8bc1");
return state.cloudLease;
}
function toPercent(v) {
const n = Number(v);
if (!Number.isFinite(n)) return 0;
if (n <= 1) return Math.round(n * 100);
return Math.round(n);
}
function toUnitProgress(v) {
const n = Number(v);
if (!Number.isFinite(n)) return 0;
return n > 1 ? n / 100 : n;
}
function parseDuration(str) {
if (typeof str === "number" && Number.isFinite(str)) return Math.max(0, Math.floor(str));
const t = String(str || "").trim();
if (!t) return 0;
if (/^\d+(\.\d+)?$/.test(t)) return Math.max(0, Math.floor(Number(t)));
const parts = t.split(":").map((x) => parseInt(x, 10) || 0);
if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
if (parts.length === 2) return parts[0] * 60 + parts[1];
return 0;
}
async function fetchAchievementPlanMap() {
const map = Object.create(null);
try {
const j = await platformJson(
"POST",
"/apis/adult/auth/adult/achievement/student/course/achievement",
{ clientType: 1, courseAbbreviation: "", semesterId: semesterId() }
);
for (const row of Array.isArray(j.data) ? j.data : []) {
const cid = String(row.courseId || "");
if (!cid) continue;
map[cid] = {
detailsId: String(row.detailsId || row.teachingPlanId || ""),
teachingPlanId: String(row.teachingPlanId || row.detailsId || ""),
studentSchoolStatusId: String(row.studentSchoolStatusId || ""),
};
}
} catch (_) {}
return map;
}
async function ensureCoursePlan(course) {
let detailsId = String(course.detailsId || course.teachingPlanId || "").trim();
if (!detailsId) {
const map = await fetchAchievementPlanMap();
const hit = map[String(course.courseId)] || null;
if (hit) {
detailsId = String(hit.detailsId || hit.teachingPlanId || "").trim();
if (hit.studentSchoolStatusId) course.studentSchoolStatusId = hit.studentSchoolStatusId;
if (hit.teachingPlanId) course.teachingPlanId = hit.teachingPlanId;
}
}
if (!detailsId) throw new Error("\u8bfe\u7a0b\u4fe1\u606f\u7f3a\u5931\uff0c\u8bf7\u5237\u65b0\u540e\u91cd\u8bd5");
course.detailsId = detailsId;
if (!course.teachingPlanId) course.teachingPlanId = detailsId;
if (!course.studentSchoolStatusId) course.studentSchoolStatusId = String(tenantId() || "").trim();
return detailsId;
}
async function fetchCourseList() {
const sid = semesterId();
if (!sid) throw new Error("\u8bf7\u5148\u8fdb\u5165\u5b66\u4e60\u4e2d\u5fc3");
const planMap = await fetchAchievementPlanMap();
const all = [];
let page = 1;
let totalPage = 1;
do {
const body = { clientType: 1, courseAbbreviation: "", semesterId: sid };
if (page > 1) {
body.pageSize = 50;
body.pageCurrent = page;
}
const j = await platformJson(
"POST",
"/apis/adult/auth/adult/myCourse/student/course/list",
body
);
const data = j.data || {};
const list = Array.isArray(data.list) ? data.list : [];
totalPage = Number(data.totalPage) || 1;
for (const row of list) {
const progress = toPercent(row.maxProgress);
const courseId = String(row.courseId || "");
const plan = planMap[courseId] || {};
const teachingPlanId = String(
row.teachingPlanId || row.detailsId || plan.teachingPlanId || plan.detailsId || ""
);
all.push({
id: String(row.id || row.courseId),
courseId,
teachingPlanId,
detailsId: String(
row.detailsId || row.teachingPlanId || plan.detailsId || plan.teachingPlanId || ""
),
studentSchoolStatusId: String(plan.studentSchoolStatusId || tenantId() || ""),
courseName: String(row.courseName || row.courseAbbreviation || "\u672a\u547d\u540d"),
periodNum: Number(row.periodNum) || 0,
progress,
studyDone: progress >= 99,
hasHomework: false,
hwScore: null,
hwLeft: 0,
examDone: false,
done: false,
});
}
page += 1;
} while (page <= totalPage && page <= 20);
for (const c of all) recomputeCourseFlags(c);
return all;
}
function normCourseName(s) {
return String(s || "")
.replace(/\s+/g, "")
.toLowerCase();
}
function recomputeCourseFlags(course) {
if (!course) return course;
course.studyDone = !!course.studyDone || Number(course.progress) >= 99;
if (course.studyDone && Number(course.progress) < 99) course.progress = 100;
const hwOk =
!course.hasHomework ||
(course.hwScore != null && Number(course.hwScore) >= HW_DONE_SCORE);
course.hwDone = !!hwOk;
const examOk = true;
course.done = !!(course.studyDone && course.hwDone && examOk);
return course;
}
function matchHomeworkForCourse(course, homeworks) {
const cid = String(course.courseId || "");
const cname = normCourseName(course.courseName);
const list = Array.isArray(homeworks) ? homeworks : [];
let matched = list.filter((h) => cid && h.courseId && h.courseId === cid);
if (!matched.length && cname) {
matched = list.filter((h) => {
const hn = normCourseName(h.courseName);
const tn = normCourseName(h.taskName);
return (
(hn && (hn === cname || hn.includes(cname) || cname.includes(hn))) ||
(tn && tn.includes(cname))
);
});
}
return matched;
}
function attachHomeworkToCourses(courses, homeworks) {
for (const c of courses || []) {
const matched = matchHomeworkForCourse(c, homeworks);
if (!matched.length) {
c.hasHomework = false;
c.hwScore = null;
c.hwLeft = 0;
} else {
c.hasHomework = true;
const pending = matched.find(
(h) =>
h.left > 0 &&
!(h.achievement != null && Number(h.achievement) >= HW_DONE_SCORE)
);
const best = matched.reduce((a, b) =>
Number(b.achievement || -1) > Number(a.achievement || -1) ? b : a
);
const use = pending || best;
c.hwScore = use.achievement == null ? null : Number(use.achievement);
c.hwLeft = Number(use.left) || 0;
}
recomputeCourseFlags(c);
}
}
async function refreshHomeworkStatus() {
try {
state.homeworks = await fetchHomeworkList();
attachHomeworkToCourses(state.courses, state.homeworks);
} catch (_) {}
}
async function fetchChapters(course) {
const periods = [];
let page = 1;
let totalPage = 1;
do {
const j = await platformJson("POST", "/apis/course/auth/course/chapter/page", {
courseId: course.courseId,
pageSize: 50,
pageCurrent: page,
});
const data = j.data || {};
const list = Array.isArray(data.list) ? data.list : [];
totalPage = Number(data.totalPage) || 1;
for (const ch of list) {
for (const p of Array.isArray(ch.periodList) ? ch.periodList : []) {
if (Number(p.isVideo) !== 1 && !p.videoVid) continue;
periods.push({
periodId: String(p.id || ""),
chapterName: String(ch.chapterName || ""),
periodName: String(p.periodName || p.videoName || "\u89c6\u9891"),
videoVid: String(p.videoVid || ""),
durationSec: parseDuration(p.videoLength),
lastWatchLength: 0,
maxProgress: 0,
done: false,
});
}
}
page += 1;
} while (page <= totalPage && page <= 30);
return periods;
}
async function fetchPeriodProgress(course) {
const j = await platformJson(
"POST",
"/apis/data/auth/course/user/period/progress/course/list",
{ courseId: course.courseId, detailsId: course.detailsId || course.teachingPlanId }
);
const map = Object.create(null);
for (const row of Array.isArray(j.data) ? j.data : []) {
const pid = String(row.periodId || "");
if (!pid) continue;
map[pid] = {
lastWatchLength: Number(row.lastWatchLength) || 0,
maxStudyLength: Number(row.maxStudyLength) || 0,
maxProgress: toUnitProgress(row.maxProgress),
};
}
return map;
}
function mergeProgress(periods, progMap) {
for (const p of periods) {
const g = progMap[p.periodId];
if (!g) continue;
p.lastWatchLength = Math.max(p.lastWatchLength, g.lastWatchLength, g.maxStudyLength);
p.maxProgress = Math.max(toUnitProgress(p.maxProgress), g.maxProgress);
const dur = Math.max(1, p.durationSec);
if (p.maxProgress >= DONE_RATIO || p.lastWatchLength >= dur * DONE_RATIO) p.done = true;
}
return periods;
}
async function runEngineLoop(startPath, stepPath, context, config) {
await ensureCloudLease(false);
const start = await cloudJson(startPath, "POST", {
lease: state.cloudLease,
context,
config: config || {},
});
if (start.free_used_chapters != null) state.freeUsedChapters = Number(start.free_used_chapters) || 0;
if (start.free_chapter_limit != null) state.freeChapterLimit = Number(start.free_chapter_limit) || 5;
if (start.proBuyUrl) state.proBuyUrl = String(start.proBuyUrl);
if (start.log) log(start.log);
let cmd = start.command || {};
const sid = start.session_id;
if (!sid) {
const msg = (cmd && cmd.message) || start.log || "\u65e0\u6cd5\u5f00\u59cb";
if (cmd.code === "free_quota_exceeded" || start._http === 402) showProAlert(msg);
throw new Error(msg);
}
if (cmd.type === "failed") {
const msg = cmd.message || start.log || "\u65e0\u6cd5\u5f00\u59cb";
if (cmd.code === "free_quota_exceeded") showProAlert(msg);
if (cmd.code === "pro_required") showProAlert(msg);
throw new Error(msg);
}
if (cmd.type === "done") return cmd;
let guard = 0;
while (!state.stopFlag && guard++ < 200) {
if (cmd.type === "wait") {
state.currentTask = start.log || "\u5904\u7406\u4e2d…";
updatePanel();
await sleep(Number(cmd.ms) || 1000);
const step = await cloudJson(stepPath, "POST", {
lease: state.cloudLease,
session_id: sid,
event: "submit_result",
last_result: { ok: true },
});
if (step.log) log(step.log);
if (step.free_used_chapters != null) state.freeUsedChapters = Number(step.free_used_chapters) || 0;
cmd = step.command || {};
} else if (cmd.type === "platform_request") {
state.currentTask = "\u540c\u6b65\u4e2d…";
updatePanel();
let platformRes = null;
let errMsg = "";
try {
platformRes = await platformJson(cmd.method || "POST", cmd.path, cmd.body || {});
} catch (e) {
errMsg = String(e.message || e);
platformRes = { code: 500, msg: errMsg };
}
const step = await cloudJson(stepPath, "POST", {
lease: state.cloudLease,
session_id: sid,
event: "submit_result",
last_result: { data: platformRes, ok: !errMsg, message: errMsg },
});
if (step.log) log(step.log);
if (step.free_used_chapters != null) state.freeUsedChapters = Number(step.free_used_chapters) || 0;
cmd = step.command || {};
} else if (cmd.type === "done") {
return cmd;
} else if (cmd.type === "failed") {
throw new Error(cmd.message || "\u4efb\u52a1\u5931\u8d25");
} else {
throw new Error("\u672a\u77e5\u6307\u4ee4");
}
}
if (state.stopFlag) {
try {
await cloudJson(stepPath, "POST", {
lease: state.cloudLease,
session_id: sid,
event: "stopped",
last_result: {},
});
} catch (_) {}
return { type: "done", stopped: true };
}
throw new Error("\u4efb\u52a1\u8d85\u65f6");
}
async function studyOnePeriod(period, course) {
const label = `${period.chapterName ? period.chapterName + " · " : ""}${period.periodName}`;
state.currentTask = label;
updatePanel();
const result = await runEngineLoop(
"/api/zs55/study/engine/start",
"/api/zs55/study/engine/step",
{
kind: "study_period",
periodId: period.periodId,
videoVid: period.videoVid,
detailsId: course.detailsId || course.teachingPlanId,
studentSchoolStatusId: course.studentSchoolStatusId || tenantId(),
durationSec: period.durationSec,
lastWatchLength: period.lastWatchLength || 0,
periodName: label,
studyMode: state.mode === MODE_RT ? "rt" : "eff",
done: !!period.done,
},
{
studyMode: state.mode === MODE_RT ? "rt" : "eff",
doneRatio: DONE_RATIO,
}
);
if (result && !result.stopped) {
period.done = true;
period.lastWatchLength = period.durationSec;
}
return result;
}
function paintCourseUi() {
renderCourseList();
void refreshChapterPreview();
}
function applyCourseProgress(course, periods) {
const total = Math.max(1, periods.length);
const left = periods.filter((x) => !x.done).length;
course.progress = Math.round(((total - left) / total) * 100);
if (left === 0) {
course.progress = 100;
course.studyDone = true;
}
recomputeCourseFlags(course);
if (course.done) {
state.queue = state.queue.filter((id) => id !== course.id);
saveJson(QUEUE_KEY, state.queue);
}
return left;
}
async function studyOneCourse(course) {
state.currentCourse = course.courseName;
state.currentTask = "\u51c6\u5907\u4e2d…";
updatePanel();
log(`\u5f00\u59cb\uff1a${course.courseName}`);
await ensureCoursePlan(course);
let periods = state.chapterCache[course.courseId];
if (!periods) {
periods = await fetchChapters(course);
try {
mergeProgress(periods, await fetchPeriodProgress(course));
} catch (_) {}
state.chapterCache[course.courseId] = periods;
}
if (!periods.length) {
log(`${course.courseName} \u6682\u65e0\u5185\u5bb9`, "warn");
return;
}
for (const p of periods) {
if (state.stopFlag) break;
if (p.done) continue;
try {
await studyOnePeriod(p, course);
} catch (e) {
const msg = String(e.message || e);
log(`\u672a\u5b8c\u6210\uff1a${p.periodName}`, "warn");
if (/\u514d\u8d39\u4f53\u9a8c\u5df2\u7528\u5b8c|\u989d\u5ea6|pro_required|free_quota/i.test(msg)) throw e;
}
applyCourseProgress(course, periods);
paintCourseUi();
await sleep(400);
updatePanel();
}
if (!state.stopFlag) {
const left = applyCourseProgress(course, periods);
paintCourseUi();
if (left === 0) log(`\u8bfe\u65f6\u5b8c\u6210\uff1a${course.courseName}`);
else log(`${course.courseName} \u5269\u4f59 ${left} \u8282`);
}
}
async function syncCoursesFromPlatform() {
try {
const fresh = await fetchCourseList();
const byId = Object.create(null);
for (const c of fresh) byId[c.id] = c;
for (const c of state.courses) {
const f = byId[c.id];
if (!f) continue;
c.progress = f.progress;
c.studyDone = f.studyDone;
c.periodNum = f.periodNum;
if (f.studyDone) delete state.chapterCache[c.courseId];
recomputeCourseFlags(c);
}
await refreshHomeworkStatus();
state.queue = state.queue.filter((id) => {
const c = state.courses.find((x) => x.id === id);
return c && !c.done;
});
saveJson(QUEUE_KEY, state.queue);
} catch (_) {}
renderCourseList();
void refreshChapterPreview({ force: true });
}
async function fetchHomeworkList() {
const j = await platformJson("POST", "/apis/adult/auth/adult/my/exam/student/newList", {
type: 0,
});
return (Array.isArray(j.data) ? j.data : []).map((row) => {
const answerNum = Number(row.answerNum) || 0;
const finishNum = Number(row.finishNum) || 0;
return {
onlineId: String(row.id || ""),
examId: String(row.examId || ""),
courseId: String(row.courseId || ""),
taskName: String(row.taskName || row.courseAbbreviation || "\u4f5c\u4e1a"),
courseName: String(row.courseName || row.courseAbbreviation || ""),
left: Math.max(0, answerNum - finishNum),
finishNum,
answerNum,
achievement: row.achievement == null ? null : Number(row.achievement),
};
});
}
async function runOneHomework(hw) {
const label = hw.taskName || hw.courseName;
state.currentCourse = label;
state.currentTask = "\u4f5c\u4e1a\u5904\u7406\u4e2d…";
updatePanel();
await runEngineLoop(
"/api/zs55/homework/engine/start",
"/api/zs55/homework/engine/step",
{
kind: "homework",
onlineId: hw.onlineId,
examId: hw.examId,
taskName: label,
},
{ targetScore: HW_DONE_SCORE }
);
}
async function doHomeworkQueue() {
if (state.cloudTier !== "pro" && !state.canHomework) {
showProAlert("\u4f5c\u4e1a\u9700\u4e13\u4e1a\u7248");
log("\u4f5c\u4e1a\u9700\u4e13\u4e1a\u7248", "warn");
return;
}
const list = await fetchHomeworkList();
state.homeworks = list;
const runnable = list.filter(
(h) =>
h.left > 0 &&
!(h.achievement != null && Number(h.achievement) >= HW_DONE_SCORE)
);
if (!runnable.length) {
log("\u6682\u65e0\u5f85\u505a\u4f5c\u4e1a");
await refreshHomeworkStatus();
paintCourseUi();
return;
}
log(`\u4f5c\u4e1a ${runnable.length} \u4efd`);
for (const hw of runnable) {
if (state.stopFlag) break;
try {
await runOneHomework(hw);
} catch (e) {
log(`\u4f5c\u4e1a\u672a\u5b8c\u6210\uff1a${hw.taskName}`, "warn");
}
await sleep(600);
}
log(state.stopFlag ? "\u5df2\u505c\u6b62" : "\u4f5c\u4e1a\u7ed3\u675f");
await refreshHomeworkStatus();
paintCourseUi();
}
async function runQueue() {
if (state.busy || state.examBusy) return;
state.busy = true;
state.stopFlag = false;
state.queueDone = 0;
updatePanel();
try {
if (!isLoggedIn()) {
log("\u8bf7\u5148\u767b\u5f55", "warn");
return;
}
try {
await ensureCloudLease(true);
} catch (e) {
log("\u6388\u6743\u5931\u8d25\uff1a" + (e.message || e), "warn");
return;
}
if (!state.courses.length) await refreshCourses();
else await refreshHomeworkStatus();
const selected = state.queue
.map((id) => state.courses.find((c) => c.id === id))
.filter(Boolean)
.filter((c) => !c.done);
const q = selected.filter((c) => !c.studyDone);
if (!selected.length) {
log("\u8bf7\u5148\u52fe\u9009\u8bfe\u7a0b");
return;
}
state.queueTotal = q.length || selected.length;
updatePanel();
for (const c of q) {
if (state.stopFlag) break;
try {
await studyOneCourse(c);
state.queueDone += 1;
} catch (e) {
const msg = String(e.message || e);
log(`\u4e2d\u65ad\uff1a${c.courseName}`, "warn");
if (/\u514d\u8d39\u4f53\u9a8c\u5df2\u7528\u5b8c|\u989d\u5ea6|pro_required|free_quota/i.test(msg)) break;
}
paintCourseUi();
updatePanel();
}
await syncCoursesFromPlatform();
log(state.stopFlag ? "\u5df2\u505c\u6b62" : "\u8bfe\u65f6\u961f\u5217\u7ed3\u675f");
if (!state.stopFlag && (state.cloudTier === "pro" || state.canHomework)) {
state.currentTask = "\u4f5c\u4e1a\u5904\u7406\u4e2d…";
updatePanel();
try {
await doHomeworkQueue();
} catch (e) {
log("\u4f5c\u4e1a\u5f02\u5e38\uff1a" + (e.message || e), "warn");
}
}
} catch (e) {
log("\u8fd0\u884c\u5f02\u5e38\uff1a" + (e.message || e), "warn");
} finally {
state.busy = false;
state.currentCourse = "";
state.currentTask = "\u70b9\u5f00\u59cb\u540e\u81ea\u52a8\u5b66\u4e60";
paintCourseUi();
updatePanel();
}
}
async function runAllHomework() {
if (state.busy || state.examBusy) return;
state.examBusy = true;
state.stopFlag = false;
updatePanel();
try {
if (!isLoggedIn()) {
log("\u8bf7\u5148\u767b\u5f55", "warn");
return;
}
try {
await ensureCloudLease(true);
} catch (e) {
log("\u6388\u6743\u5931\u8d25\uff1a" + (e.message || e), "warn");
return;
}
await doHomeworkQueue();
} catch (e) {
log("\u4f5c\u4e1a\u5f02\u5e38\uff1a" + (e.message || e), "warn");
} finally {
state.examBusy = false;
state.currentCourse = "";
state.currentTask = "\u70b9\u5f00\u59cb\u540e\u81ea\u52a8\u5b66\u4e60";
updatePanel();
}
}
async function runExamPlaceholder() {
try {
await ensureCloudLease(true);
const data = await cloudJson("/api/zs55/exam/engine/start", "POST", {
lease: state.cloudLease,
context: { kind: "exam" },
config: {},
});
log((data.command && data.command.message) || data.log || "\u8003\u8bd5\u529f\u80fd\u5f85\u5f00\u653e", "warn");
} catch (e) {
log("\u8003\u8bd5\u529f\u80fd\u5f85\u5f00\u653e", "warn");
}
}
async function refreshCourses() {
try {
if (!isLoggedIn()) {
log("\u8bf7\u5148\u767b\u5f55");
return;
}
state.courses = await fetchCourseList();
await refreshHomeworkStatus();
state.queue = state.queue.filter((id) => state.courses.some((c) => c.id === id && !c.done));
saveJson(QUEUE_KEY, state.queue);
renderCourseList();
updatePanel();
void refreshChapterPreview();
log(`\u5df2\u52a0\u8f7d ${state.courses.length} \u95e8\u8bfe`);
try {
await ensureCloudLease(true);
updatePanel();
} catch (_) {}
} catch (e) {
log("\u5237\u65b0\u5931\u8d25\uff1a" + (e.message || e), "warn");
}
}
function homeworkChipText(c) {
if (!c.hasHomework) return "\u4f5c\u4e1a \u65e0";
if (c.hwDone) return "\u4f5c\u4e1a \u5df2\u5b8c\u6210";
if (c.hwScore != null) return `\u4f5c\u4e1a ${Math.round(Number(c.hwScore))}\u5206`;
return "\u4f5c\u4e1a \u5f85\u505a";
}
function switchTab(tab) {
document.querySelectorAll(".zs55-tab-btn").forEach((b) => {
b.classList.toggle("active", b.dataset.tab === tab);
});
document.querySelectorAll(".zs55-pane").forEach((p) => {
p.classList.toggle("active", p.dataset.pane === tab);
});
}
function applyPanelCollapsed(panel, collapsed) {
panel.classList.toggle("zs55-collapsed", !!collapsed);
const min = document.getElementById("zs55-btn-min");
const max = document.getElementById("zs55-btn-max");
if (min) min.style.display = collapsed ? "none" : "";
if (max) max.style.display = collapsed ? "" : "none";
}
function renderCourseList() {
const box = document.getElementById("zs55-course-list");
if (!box) return;
if (!state.courses.length) {
box.innerHTML = `\u767b\u5f55\u540e\u70b9\u5237\u65b0\u52a0\u8f7d\u8bfe\u7a0b
`;
return;
}
box.innerHTML = state.courses
.map((c) => {
const checked = !c.done && state.queue.includes(c.id) ? "checked" : "";
const disabled = c.done ? "disabled" : "";
const itemCls = c.done ? "zs55-course-item zs55-course-done" : "zs55-course-item";
const studyChip = c.studyDone
? "\u8bfe\u65f6 \u5df2\u5b8c\u6210"
: `\u8bfe\u65f6 ${Number(c.progress) || 0}%`;
return ``;
})
.join("");
box.querySelectorAll("input[type=checkbox]").forEach((el) => {
el.addEventListener("change", () => {
if (el.disabled) {
el.checked = false;
return;
}
const id = el.getAttribute("data-id");
if (el.checked) {
if (!state.queue.includes(id)) state.queue.push(id);
} else {
state.queue = state.queue.filter((x) => x !== id);
}
saveJson(QUEUE_KEY, state.queue);
updatePanel();
void refreshChapterPreview();
});
});
}
function renderChapterPreview() {
const box = document.getElementById("zs55-chapter-preview");
if (!box) return;
if (!state.previewChapters.length) {
box.innerHTML = `\u8bf7\u52fe\u9009\u8bfe\u7a0b\u540e\u67e5\u770b\u7ae0\u8282
`;
return;
}
box.innerHTML = state.previewChapters
.map((ch) => {
const meta = [];
if (ch.durationSec) meta.push(formatSec(ch.durationSec));
meta.push(ch.done ? "\u5df2\u5b8c\u6210" : "\u672a\u5b8c\u6210");
return `
${escapeHtml(
(ch.chapterName ? ch.chapterName + " · " : "") + ch.periodName
)}
${meta.join(" · ")}
`;
})
.join("");
}
async function refreshChapterPreview(opts) {
const force = !!(opts && opts.force);
const needStudy = state.courses.filter(
(c) => state.queue.includes(c.id) && !c.studyDone
);
const picked =
needStudy.length > 0
? needStudy
: state.courses.filter((c) => state.queue.includes(c.id) && !c.done);
if (!picked.length) {
state.previewChapters = [];
renderChapterPreview();
return;
}
const course = picked[0];
try {
await ensureCoursePlan(course);
let periods = state.chapterCache[course.courseId];
if (!periods || force) {
periods = await fetchChapters(course);
try {
mergeProgress(periods, await fetchPeriodProgress(course));
} catch (_) {}
state.chapterCache[course.courseId] = periods;
}
state.previewChapters = periods.slice(0, 40);
} catch (_) {
state.previewChapters = [];
}
renderChapterPreview();
}
function updatePanel() {
const runBusy = state.busy || state.examBusy;
const st = document.getElementById("zs55-auto-status");
if (st) st.textContent = runBusy ? "\u8fd0\u884c\u4e2d" : "\u5df2\u505c\u6b62";
const task = document.getElementById("zs55-current-task");
if (task) {
task.textContent = state.currentCourse
? `${state.currentCourse} · ${state.currentTask}`
: state.currentTask;
}
const done = document.getElementById("zs55-queue-done");
const total = document.getElementById("zs55-queue-total");
const pct = document.getElementById("zs55-queue-percent");
const bar = document.getElementById("zs55-queue-progress");
const qtext = document.getElementById("zs55-queue-text");
if (done) done.textContent = String(state.queueDone);
if (total) total.textContent = String(state.queueTotal);
const p =
state.queueTotal > 0
? Math.min(100, Math.round((state.queueDone / state.queueTotal) * 100))
: 0;
if (pct) pct.textContent = `${p}%`;
if (bar) bar.style.width = `${p}%`;
if (qtext) {
qtext.textContent = state.queue.length
? `\u5df2\u9009 ${state.queue.length} \u95e8\u8bfe`
: "\u672a\u9009\u62e9\u8bfe\u7a0b";
}
const tier = document.getElementById("zs55-cloud-tier");
const sub = document.getElementById("zs55-cloud-sub");
if (tier) {
tier.textContent = state.cloudTier === "pro" ? "Pro \u4f1a\u5458" : "\u514d\u8d39\u7528\u6237";
}
if (sub) {
if (state.cloudTier === "pro") {
sub.textContent = state.proExpiresText
? `\u5230\u671f ${state.proExpiresText}`
: "\u4e13\u4e1a\u7248\u5df2\u6fc0\u6d3b";
} else {
sub.textContent = `\u514d\u8d39\u7ae0\u8282 ${state.freeUsedChapters}/${state.freeChapterLimit} \u8282`;
}
}
const ann = document.getElementById("zs55-ann-text");
if (ann && state.panelNotice) ann.textContent = state.panelNotice;
const start = document.getElementById("zs55-start");
const stop = document.getElementById("zs55-stop");
if (start) {
start.disabled = runBusy;
start.classList.toggle("zs55-btn-off", runBusy);
}
if (stop) {
stop.disabled = !runBusy;
stop.classList.toggle("zs55-btn-off", !runBusy);
}
document.querySelectorAll("[data-study-mode]").forEach((btn) => {
btn.classList.toggle("active", btn.getAttribute("data-study-mode") === state.mode);
});
}
function injectPanelStyles() {
if (document.getElementById("zs55-panel-style")) return;
const style = document.createElement("style");
style.id = "zs55-panel-style";
style.textContent = `
#zs55-auto-panel{position:fixed;right:16px;top:72px;z-index:2147483000;width:360px;max-width:calc(100vw - 20px);background:#fff7ed;border:1px solid #fdba74;border-radius:14px;box-shadow:0 12px 40px rgba(154,52,18,.18);font:13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#7c2d12;overflow:hidden}
#zs55-auto-panel.zs55-collapsed{width:auto;min-width:0}
#zs55-auto-panel.zs55-collapsed #zs55-panel-body,.zs55-collapsed .zs55-footer-extra,#zs55-auto-panel.zs55-collapsed #zs55-panel-footer{display:none!important}
#zs55-panel-header{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;padding:10px 12px 8px;background:linear-gradient(135deg,#ffedd5,#fed7aa);cursor:move;user-select:none}
#zs55-panel-brand{display:flex;gap:8px;align-items:flex-start;min-width:0}
#zs55-panel-logo{width:34px;height:34px;border-radius:8px;object-fit:cover;flex:0 0 auto;background:#fff}
#zs55-panel-title{font-size:13px;font-weight:800;color:#9a3412;line-height:1.35}
.zs55-panel-version{margin-left:6px;font-size:11px;font-weight:600;color:#c2410c;opacity:.85}
#zs55-panel-sub{margin-top:2px;font-size:11px;color:#9a3412;opacity:.9}
.zs55-sub-chip{font-weight:700}
.zs55-sub-chip-em{color:#c2410c}
.zs55-sub-dot{margin:0 4px;opacity:.5}
#zs55-panel-controls{display:flex;gap:4px}
.zs55-panel-ctl{border:0;background:rgba(255,255,255,.7);width:26px;height:26px;border-radius:8px;cursor:pointer;color:#9a3412;font-size:14px;line-height:1}
#zs55-panel-body{padding:8px 10px 10px;max-height:min(72vh,640px);overflow:auto}
.zs55-card{background:#fff;border:1px solid #fed7aa;border-radius:12px;padding:8px 9px;margin-bottom:8px}
.zs55-status-row{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:4px}
.zs55-status-label{font-size:12px;color:#a16207}
#zs55-auto-status{font-weight:800;color:#9a3412}
#zs55-current-task{font-size:11px;color:#a16207;margin-top:4px;min-height:16px}
.zs55-metric em{font-style:normal;font-weight:800;color:#c2410c}
.zs55-progress-bar{height:7px;background:#ffedd5;border-radius:99px;overflow:hidden;margin-top:4px}
#zs55-queue-progress{display:block;height:100%;width:0;background:linear-gradient(90deg,#fb923c,#ea580c);border-radius:99px;transition:width .25s}
.zs55-tabbar{display:flex;gap:4px;margin-bottom:8px;flex-wrap:wrap}
.zs55-tab-btn{flex:1;min-width:64px;border:1px solid #fdba74;background:#fff7ed;color:#9a3412;border-radius:8px;padding:5px 6px;font-size:12px;cursor:pointer;font-weight:700}
.zs55-tab-btn.active{background:#ea580c;border-color:#ea580c;color:#fff}
.zs55-pane{display:none}
.zs55-pane.active{display:block}
.zs55-list-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}
.zs55-list-title{font-weight:800;font-size:12px}
.zs55-list-tag{font-size:11px;color:#a16207}
#zs55-course-list,#zs55-chapter-preview,#zs55-run-log{max-height:220px;overflow:auto}
.zs55-course-item,.zs55-chapter-item{display:flex;gap:8px;align-items:flex-start;padding:6px 4px;border-bottom:1px dashed #fed7aa}
.zs55-course-item.zs55-course-done{opacity:.62;background:#f8fafc;border-radius:8px}
.zs55-course-item.zs55-course-done .zs55-course-name{color:#94a3b8;text-decoration:line-through;text-decoration-color:#cbd5e1}
.zs55-done-tag{font-size:10px;font-weight:700;color:#16a34a;text-decoration:none}
.zs55-course-actions{display:flex;gap:6px;margin-bottom:6px;flex-wrap:wrap;align-items:center}
.zs55-course-actions button{font-size:11px;padding:4px 10px;border-radius:8px;border:1px solid #fdba74;background:#fff7ed;color:#9a3412;font-weight:700;cursor:pointer}
.zs55-course-actions button:hover{background:#ffedd5}
.zs55-mode-switch{display:flex;gap:4px;margin-bottom:8px}
.zs55-mode-switch button{flex:1;font-size:12px;padding:6px 8px;border-radius:8px;border:1px solid #fdba74;background:#fff;color:#9a3412;font-weight:700;cursor:pointer}
.zs55-mode-switch button.active{background:#f97316;border-color:#ea580c;color:#fff}
.zs55-mode-switch button:hover:not(.active){background:#ffedd5}
.zs55-course-item:last-child,.zs55-chapter-item:last-child{border-bottom:0}
.zs55-course-main{min-width:0;flex:1}
.zs55-course-name{font-weight:700;font-size:12px;word-break:break-all}
.zs55-course-meta,.zs55-chapter-meta{font-size:11px;color:#a16207;margin-top:2px}
.zs55-empty-state{padding:16px 8px;text-align:center;color:#a16207;font-size:12px}
.zs55-log-row{font-size:11px;padding:3px 0;border-bottom:1px dashed #ffedd5;word-break:break-all}
.zs55-log-warn{color:#b91c1c}
.zs55-meta-row{display:flex;align-items:center;gap:8px;margin:5px 0;font-size:12px}
.zs55-meta-label{flex:0 0 72px;color:#a16207}
.zs55-token-row{display:flex;gap:6px;align-items:center}
.zs55-token-row input{flex:1;border:1px solid #fdba74;border-radius:8px;padding:5px 7px;font-size:12px;background:#fff}
.zs55-btn-row{display:flex;gap:8px;margin-top:8px}
.zs55-btn{border:0;border-radius:10px;padding:8px 10px;font-size:13px;font-weight:800;cursor:pointer}
.zs55-btn-start{flex:1;background:#ea580c;color:#fff}
.zs55-btn-stop{flex:1;background:#9a3412;color:#fff}
.zs55-btn-off,.zs55-btn:disabled{opacity:.45;cursor:not-allowed}
.zs55-btn-ghost{background:#ffedd5;color:#9a3412;border:1px solid #fdba74}
.zs55-btn-pro{background:linear-gradient(135deg,#f59e0b,#ea580c);color:#fff}
.zs55-course-scores{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
.zs55-score-chip{font-size:10px;font-weight:700;padding:2px 6px;border-radius:6px;background:#ffedd5;color:#9a3412;border:1px solid #fed7aa}
.zs55-settings-card{padding:10px 11px}
.zs55-settings-pro{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 12px;border-radius:10px;background:linear-gradient(135deg,#ffedd5,#fed7aa);margin-bottom:10px}
.zs55-settings-pro-title{font-size:13px;font-weight:800;color:#9a3412}
.zs55-settings-pro-sub{font-size:11px;color:#a16207;margin-top:2px}
.zs55-settings-tip{font-size:11px;color:#a16207;line-height:1.5;margin-top:8px;padding:8px;border-radius:8px;background:#fff7ed;border:1px dashed #fdba74}
.zs55-start-hint{display:none;color:#b91c1c;font-size:12px;margin:4px 0}
.zs55-footer-extra{padding:0 10px 8px}
.zs55-ann{background:#fff;border:1px solid #fed7aa;border-radius:10px;padding:7px 8px;font-size:11px;margin-bottom:6px}
#zs55-panel-footer{padding:6px 12px 10px;font-size:11px;color:#a16207;border-top:1px solid #fed7aa;background:#fff7ed}
.zs55-log-clear-btn{border:0;background:#ffedd5;color:#9a3412;border-radius:6px;padding:2px 7px;font-size:11px;cursor:pointer}
`;
document.documentElement.appendChild(style);
}
function mountPanel() {
if (document.getElementById("zs55-auto-panel")) return;
injectPanelStyles();
const panel = document.createElement("div");
panel.id = "zs55-auto-panel";
panel.innerHTML = `
\u8fd0\u884c\u72b6\u6001
\u5df2\u505c\u6b62
0/0 \u8bfe\u7a0b\u5df2\u5904\u7406
0%
\u70b9\u5f00\u59cb\u540e\u81ea\u52a8\u5b66\u4e60
\u8bfe\u7a0b\u9009\u62e9${
state.mode === MODE_RT ? "\u5e38\u901f" : "\u6548\u7387"
}
\u7ae0\u8282\u9884\u89c8\u9996\u4e2a\u5df2\u9009\u8bfe\u7a0b
\u8bf7\u9009\u62e9\u8bfe\u7a0b
\u8fd0\u884c\u65e5\u5fd7
\u514d\u8d39\u7528\u6237
\u514d\u8d39\u7ae0\u8282 0/5 \u8282
\u6388\u6743\u7801
\u52fe\u9009\u8bfe\u7a0b\u540e\u70b9\u300c\u5f00\u59cb\u300d\uff1a\u5148\u5237\u8bfe\u65f6\uff0c\u5b8c\u6210\u540e\u81ea\u52a8\u505a\u4f5c\u4e1a\uff08\u4e13\u4e1a\u7248\uff09\u3002\u4e5f\u53ef\u5355\u72ec\u70b9\u300c\u4e00\u952e\u4f5c\u4e1a\u300d\u3002\u8003\u8bd5\u5f85\u5f00\u653e\uff0c\u6682\u4e0d\u5217\u5165\u6d41\u7a0b\u3002
`;
document.body.appendChild(panel);
try {
const saved = JSON.parse(localStorage.getItem(POS_KEY) || "null");
if (saved && saved.left != null) {
panel.style.right = "auto";
panel.style.left = saved.left + "px";
panel.style.top = saved.top + "px";
}
} catch (_) {}
applyPanelCollapsed(panel, localStorage.getItem(COLLAPSED_KEY) === "1");
const header = document.getElementById("zs55-panel-header");
let sx = 0,
sy = 0,
ol = 0,
ot = 0,
moving = false;
header.addEventListener("mousedown", (e) => {
if (e.target.closest(".zs55-panel-ctl")) return;
moving = true;
const rect = panel.getBoundingClientRect();
sx = e.clientX;
sy = e.clientY;
ol = rect.left;
ot = rect.top;
panel.style.right = "auto";
panel.style.left = `${ol}px`;
panel.style.top = `${ot}px`;
e.preventDefault();
});
window.addEventListener("mousemove", (e) => {
if (!moving) return;
panel.style.left = `${Math.max(0, ol + e.clientX - sx)}px`;
panel.style.top = `${Math.max(0, ot + e.clientY - sy)}px`;
});
window.addEventListener("mouseup", () => {
if (!moving) return;
moving = false;
const rect = panel.getBoundingClientRect();
saveJson(POS_KEY, { left: rect.left, top: rect.top });
});
document.getElementById("zs55-btn-min").onclick = (e) => {
e.stopPropagation();
localStorage.setItem(COLLAPSED_KEY, "1");
applyPanelCollapsed(panel, true);
};
document.getElementById("zs55-btn-max").onclick = (e) => {
e.stopPropagation();
localStorage.setItem(COLLAPSED_KEY, "0");
applyPanelCollapsed(panel, false);
};
panel.querySelectorAll(".zs55-tab-btn").forEach((btn) => {
btn.addEventListener("click", () => {
switchTab(btn.dataset.tab);
if (btn.dataset.tab === "course") renderCourseList();
if (btn.dataset.tab === "chapter") void refreshChapterPreview();
});
});
panel.querySelectorAll("[data-study-mode]").forEach((btn) => {
btn.addEventListener("click", () => {
state.mode = btn.getAttribute("data-study-mode") === MODE_RT ? MODE_RT : MODE_EFF;
localStorage.setItem(MODE_KEY, state.mode);
const tag = document.getElementById("zs55-list-mode-tag");
if (tag) tag.textContent = state.mode === MODE_RT ? "\u5e38\u901f" : "\u6548\u7387";
updatePanel();
});
});
document.getElementById("zs55-refresh").onclick = () => refreshCourses();
document.getElementById("zs55-select-unfinished").onclick = () => {
state.queue = state.courses.filter((c) => !c.done).map((c) => c.id);
saveJson(QUEUE_KEY, state.queue);
renderCourseList();
updatePanel();
void refreshChapterPreview();
};
document.getElementById("zs55-clear-selection").onclick = () => {
state.queue = [];
saveJson(QUEUE_KEY, state.queue);
renderCourseList();
updatePanel();
void refreshChapterPreview();
};
document.getElementById("zs55-start").onclick = () => runQueue();
document.getElementById("zs55-stop").onclick = () => {
state.stopFlag = true;
log("\u6b63\u5728\u505c\u6b62…");
};
document.getElementById("zs55-hw").onclick = () => runAllHomework();
document.getElementById("zs55-exam").onclick = () => runExamPlaceholder();
document.getElementById("zs55-clear-log").onclick = () => {
state.logLines = [];
renderRunLog();
};
document.getElementById("zs55-open-pro").onclick = () => {
const url = state.proBuyUrl || PRO_BUY_URL;
if (typeof GM_openInTab === "function") GM_openInTab(url, { active: true });
else window.open(url, "_blank");
};
document.getElementById("zs55-cloud-save").onclick = async () => {
const v = String(document.getElementById("zs55-cloud-token").value || "").trim();
state.cloudToken = v;
if (v) localStorage.setItem(TOKEN_KEY, v);
else localStorage.removeItem(TOKEN_KEY);
try {
await ensureCloudLease(true);
log(state.cloudTier === "pro" ? "\u4e13\u4e1a\u7248\u5df2\u6fc0\u6d3b" : "\u5df2\u4fdd\u5b58");
updatePanel();
} catch (e) {
log("\u6fc0\u6d3b\u5931\u8d25\uff1a" + (e.message || e), "warn");
}
};
updatePanel();
renderRunLog();
if (isLoggedIn()) {
refreshCourses().catch(() => {});
gmHttp(CLOUD_BASE + "/api/zs55/panel-notice", "GET", { Accept: "text/plain" }, null)
.then((r) => {
if (r.text && r.text.trim()) {
state.panelNotice = r.text.trim();
updatePanel();
}
})
.catch(() => {});
} else {
renderCourseList();
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", mountPanel);
} else {
mountPanel();
}
})();