/g, '
').trim(), cl = (str) => str.replace(/^【.*?】\s*/, "").replace(/\s*(\d+\.\d+分)$/, ""), COURSE_SELECTORS = "#coursename, .courseName, #courseName, .course-name, .course_title, .courseTitle, .courseNameWrap h1, .course-name-wrap, .mark_title_course", getCourseName = (() => {
let cached = "";
return function() {
if (cached) return cached;
const cleanup = (t) => String(t || "").replace(/\s+/g, " ").replace(/[-_|—·]\s*(超星学习通|超星|学习通)\s*$/i, "").replace(/(期末考试|期中考试|章节测验|章节练习|章节检测|课后作业|随堂练习|单元测试|作业|考试|测验|任务点|详情|预览)$/i, "").trim();
const pick = (doc) => {
if (!doc || !doc.querySelector) return "";
try {
const el = doc.querySelector(COURSE_SELECTORS);
if (el) {
const t = cleanup(el.textContent);
if (t && t.length <= 60) return t;
}
} catch (e) {
}
return "";
};
const docs = [];
try {
docs.push(_unsafeWindow.document);
} catch (e) {
}
try {
_unsafeWindow.top && _unsafeWindow.top.document && docs.push(_unsafeWindow.top.document);
} catch (e) {
}
try {
docs.push(document);
} catch (e) {
}
for (let i = 0; i < docs.length; i++) {
const t = pick(docs[i]);
if (t) {
cached = t;
return cached;
}
}
for (let i = 0; i < docs.length; i++) {
const raw = docs[i] && docs[i].title || "";
if (!raw) continue;
const first = cleanup(String(raw).split(/[-_|—]/)[0]);
if (first && first.length <= 60 && !/^(超星学习通|超星|学习通|个人空间|首页|登录)$/.test(first)) {
cached = first;
return cached;
}
}
return "";
};
})(), CATALOG_SELECTORS = ".posCatalog_active, .posCatalog_select.active, .posCatalog_cur, #mainid .active, .chapter_list .active, .catalog_list .active, .chapter_item.active, .catalogItem.active, .chapterList .active, .catalog .active, .posCatalog_level .active, .chapter_item.cur, .catalog_item.active, .chapter_item.current", getCatalogChapter = (() => {
let cached = "", at = 0;
return function() {
if (Date.now() - at < 2000) return cached;
at = Date.now();
const cleanup = (t) => String(t || "").replace(/\s+/g, " ").replace(/(已完成|未完成|待完成|已学完|学习中|进行中)/g, "").replace(/\b\d{1,3}:\d{2}(:\d{2})?\b/g, "").replace(/\s{2,}/g, " ").trim().slice(0, 80);
const docs = [];
try {
_unsafeWindow.top && _unsafeWindow.top.document && docs.push(_unsafeWindow.top.document);
} catch (e) {
}
try {
docs.push(_unsafeWindow.document);
} catch (e) {
}
try {
docs.push(document);
} catch (e) {
}
// 目录高亮项(章节会随导航变化,故只缓存 2 秒)
for (let i = 0; i < docs.length; i++) {
const d = docs[i];
if (!d || !d.querySelector) continue;
try {
const el = d.querySelector(CATALOG_SELECTORS);
if (el) {
const t = cleanup(el.textContent);
if (t && t.length <= 80 && !/^(目录|章节|课程目录|全部章节)$/.test(t)) {
cached = t;
return cached;
}
}
} catch (e) {
}
}
// 兜底:面包屑/章节标题
const fallbacks = ".chapterName, #chapterTitle, .chapter_title, .chapter-title, .prev_ul .current, .position .current";
for (let i = 0; i < docs.length; i++) {
const d = docs[i];
if (!d || !d.querySelector) continue;
try {
const el = d.querySelector(fallbacks);
if (el) {
const t = cleanup(el.textContent);
if (t && t.length <= 80) {
cached = t;
return cached;
}
}
} catch (e) {
}
}
cached = "";
return cached;
};
})(), SECTION_SELECTORS = ".Cy_TItle, .type_tit, .mark_title, .mark_title .title, .mark_name .colorShallow", getSectionTitle = (el) => {
const cleanTitle = (txt) => String(txt || "").replace(/\s+/g, " ").replace(/题型说明[::][\s\S]*$/, "").replace(/(共\s*\d+\s*题[^)]*)/g, "").replace(/\(\s*共\s*\d+\s*题?[^)]*\)/g, "").replace(/^[\s一二三四五六七八九十\d.、,,]+/, "").trim();
// 纯题型名(单选题/判断题…)不构成语境,判为无标题
const useful = (t) => !!t && !/^(单选题?|多选题?|判断题?|填空题?|简答题?|名词解释|论述题?|计算题?|选择题)$/.test(t) && !/^[\d\s.、]+$/.test(t);
const grap = (node) => {
if (!node || !node.querySelector) return "";
const hit = node.querySelector(SECTION_SELECTORS);
if (!hit) return "";
const t = cleanTitle(hit.textContent);
return useful(t) ? t : "";
};
try {
let node = el.parentElement;
for (let i = 0; i < 5 && node; i++) {
const t = grap(node);
if (t) return t;
node = node.parentElement;
}
const doc = (el.ownerDocument || document);
const pageHit = doc.querySelector(".Cy_TItle, .type_tit, .mark_title");
if (pageHit) {
const t = cleanTitle(pageHit.textContent);
if (useful(t)) return t;
}
// 兜底:页面标题(不少外语课直接以大题名作为页面标题,如 "Word in use")
const docTitle = cleanTitle(doc.title || "");
if (useful(docTitle) && !/超星|学习通|章节测验|作业|考试|测验|首页|登录/.test(docTitle))
return docTitle;
} catch (e) {
}
return "";
}, getQuestion = (type, html) => {
let questionHtml, questionText, questionTypeId, optionHtml, tokenHtml, workType, optionText, index;
switch (type) {
case "1":
return workType = "zj", questionHtml = Array.from(html.querySelectorAll(".clearfix .fontLabel")), questionText = cl(removeHtml(questionHtml[0].innerHTML)), questionTypeId = html.querySelectorAll("input[name^=answertype]")[0].value, optionHtml = Array.from(html.querySelectorAll("ul")[0].querySelectorAll("li .after")), tokenHtml = html.innerHTML, optionText = [], optionHtml.forEach(function(item) {
optionText.push(removeHtml(item.innerHTML));
}), { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType, section: getSectionTitle(html) };
case "2":
workType = "zy", questionHtml = Array.from(html.querySelectorAll(".mark_name")), index = questionHtml[0].innerHTML.indexOf(""), questionText = cl(removeHtml(questionHtml[0].innerHTML.substring(index + 7))), questionHtml[0].getElementsByTagName("span")[0].innerHTML.replace("(", "").replace(")", "").split(",")[0], questionTypeId = html.querySelectorAll("input[name^=answertype]")[0].value, optionHtml = Array.from(html.querySelectorAll(".answer_p")), tokenHtml = html.innerHTML, optionText = [];
for (let i = 0; i < optionHtml.length; i++)
optionText.push(removeHtml(optionHtml[i].innerHTML));
return { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType, section: getSectionTitle(html) };
case "3":
workType = "ks", questionHtml = Array.from(document.getElementsByClassName("mark_name colorDeep")), index = questionHtml[0].innerHTML.indexOf(""), questionText = cl(removeHtml(questionHtml[0].innerHTML.substring(index + 7))), questionHtml[0].getElementsByTagName("span")[0].innerHTML.replace("(", "").replace(")", "").split(",")[0], questionTypeId = (t => { if (t) return t.value; const m = questionHtml[0].innerHTML.match(/(单选题|多选题|填空题|判断题|简答题|名词解释|论述题|计算题)/); return m ? questionType[m[1]] : "0"; })(document.querySelector(".mark_table .questionLi input[name^=answertype]") || document.querySelector("input[name^=answertype]") || document.querySelectorAll("input[name^=type]")[1]), optionHtml = Array.from(document.getElementsByClassName("answer_p")), tokenHtml = document.getElementsByClassName("mark_table")[0].innerHTML, optionText = [];
for (let i = 0; i < optionHtml.length; i++)
optionText.push(removeHtml(optionHtml[i].innerHTML));
return { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType, section: getSectionTitle(html) };
}
}, decode = (iframeWindow) => {
var _a;
const styleElements = iframeWindow.document.querySelectorAll("style");
let tipElement = null;
if (styleElements.forEach((styleElement) => {
var _a2;
-1 !== ((_a2 = styleElement.textContent) == null ? void 0 : _a2.indexOf("font-cxsecret")) && (tipElement = styleElement);
}), !tipElement)
return;
const fontMatch = (_a = tipElement.textContent) == null ? void 0 : _a.match(/base64,([\w\W]+?)'/);
if (!fontMatch)
return;
const fontData = ((base64) => {
const decodedData = atob(base64), array = new Uint8Array(decodedData.length);
for (let i = 0; i < decodedData.length; i++)
array[i] = decodedData.charCodeAt(i);
return array;
})(fontMatch[1]), font = Typr$1.parse(fontData), table = JSON.parse(_GM_getResourceText("ttf"));
let text = {};
for (let i = 19968; i < 40870; i++) {
let t = Typr$1.U.codeToGlyph(font, i);
t && (t = Typr$1.U.glyphToPath(font, t), t = md5(JSON.stringify(t)).slice(24), text[i] = table[t]);
}
iframeWindow.document.querySelectorAll(".font-cxsecret").forEach((fontElement) => {
let html = fontElement.innerHTML;
Object.keys(text).forEach((key) => {
const regex = new RegExp(String.fromCharCode(key), "g");
html = html.replace(regex, String.fromCharCode(text[key]));
}), fontElement.innerHTML = html, fontElement.classList.remove("font-cxsecret");
});
}, extractAnswerLetters = (content) => {
const up = (content || "").toUpperCase();
const explicit = up.match(/答案[^A-Z]{0,6}([A-H]{1,8})/);
if (explicit)
return explicit[1];
const runs = up.match(/(?:^|[^A-Z])([A-H]{1,8})(?![A-Z])/g) || [];
const letters = [...new Set(runs.join("").match(/[A-H]/g) || [])];
return letters.join("");
}, JUNK_PATTERNS = ["付费题库", "购买后可查看", "点此购买", "点此查看", "卡密", "继续搜题", "扫码", "公众号", "题库未收录", "题库暂无", "暂无答案", "未找到答案", "没有找到答案", "未查到", "查无此题", "该题暂无", "请先登录", "请登录", "登录后查看", "余额不足", "次数不足", "点数不足", "充值", "开通会员", "会员专享", "联系客服", "授权码", "未授权", "密钥", "秘钥", "请填写", "无法获取", "无法回答", "能力有限", "抱歉"], isJunkAnswer = (answer) => {
const arr = Array.isArray(answer) ? answer : [answer];
const texts = arr.map(function(x) {
return String(x == null ? "" : x).replace(/<[^>]*>/g, "").replace(/\s+/g, "").trim();
}).filter(function(t) {
return t.length > 0;
});
if (0 === texts.length)
return true;
return texts.every(function(t) {
if (["略", "无", "-", "—", "null", "undefined", "NaN"].includes(t))
return true;
// 引流/付费提示常见特征
if (/[👉➡️]|https?:\/\//.test(t))
return true;
return JUNK_PATTERNS.some(function(p) {
return t.indexOf(p) !== -1;
});
});
}, normalizeAnswer = (answer, questionData) => {
if (answer == null)
return [];
let list = Array.isArray(answer) ? answer.slice() : [answer];
list = list.map(function(x) {
return "string" === typeof x ? x.trim() : String(x == null ? "" : x).trim();
}).filter(function(x) {
return x.length > 0;
});
if (0 === list.length)
return [];
const options = questionData && questionData.options ? questionData.options : [];
const type = questionData ? String(questionData.type) : "0";
const textTypes = ["2", "4", "5", "6", "7"];
if (textTypes.includes(type)) {
const flat = list.join("|");
const parts = flat.split(/[||]|\n/).map(function(x) {
return x.replace(/^\s*第[一二三四五六七八九十\d]+\s*空[::]?/, "").trim();
}).filter(function(x) {
return x.length > 0;
});
return parts.length > 0 ? parts : list;
}
if (0 === options.length)
return list;
const optByLetter = function(letter) {
const i = letter.charCodeAt(0) - 65;
return i >= 0 && i < options.length ? removeHtml(String(options[i] || "")) : null;
};
const cleaned = list.map(function(x) {
return removeHtml(x.replace(/^(答案|正确答案|参考答案)[::]?/, "").trim());
}).filter(Boolean);
const direct = cleaned.filter(function(x) {
return options.some(function(opt) {
return removeHtml(String(opt || "")) === x;
});
});
if (direct.length > 0)
return direct;
// 仅当整段文本就是字母组合时才按字母解析,避免 "deserve" 里的 D 被误当成选项
const letterOnly = cleaned.filter(function(x) {
return /^[A-Ha-h](\s*[,,、\/|]?\s*[A-Ha-h])*$/.test(String(x).trim());
});
if (letterOnly.length > 0) {
const letterRuns = letterOnly.join("").toUpperCase().match(/[A-H]/g) || [];
const fromLetters = [];
letterRuns.forEach(function(ch) {
const t = optByLetter(ch);
t !== null && -1 === fromLetters.indexOf(t) && fromLetters.push(t);
});
if (fromLetters.length > 0)
return fromLetters;
}
const byText = [];
cleaned.forEach(function(x) {
options.forEach(function(opt) {
const o = removeHtml(String(opt || ""));
if (o && (o === x || (x.length >= 2 && o.includes(x)) || (o.length >= 2 && x.includes(o))) && -1 === byText.indexOf(opt))
byText.push(opt);
});
});
if (byText.length > 0)
return byText;
// 第三轮:去标点/空白后再全等(AnswerUtil 思路,解决"多一个句号就匹配不上")
const squash = (s) => String(s == null ? "" : s).replace(/[\s,。、;:""''()()\[\]【】<>《》!!??.,;:'"“”‘’\-—_/\\|~`]/g, "").toLowerCase();
const bySquash = [];
cleaned.forEach(function(x) {
const sx = squash(x);
if (!sx) return;
options.forEach(function(opt) {
squash(opt) === sx && -1 === bySquash.indexOf(opt) && bySquash.push(opt);
});
});
if (bySquash.length > 0)
return bySquash;
// 第四轮:字符相似度(>=60% 且为最优项才采纳)
const sameRate = (a, b) => {
const A = squash(a), B = squash(b);
if (!A || !B) return 0;
const seen = {};
let n = 0;
for (let i = 0; i < A.length; i++) {
const ch = A[i];
if (B.indexOf(ch) !== -1 && !seen[ch]) {
seen[ch] = 1;
n++;
}
}
return n / Math.max(A.length, B.length);
};
const bySim = [];
cleaned.forEach(function(x) {
let bestI = -1, bestRate = 0;
options.forEach(function(opt, i) {
const r = sameRate(x, opt);
if (r > bestRate) {
bestRate = r, bestI = i;
}
});
if (bestI >= 0 && bestRate >= 0.6 && -1 === bySim.indexOf(options[bestI]))
bySim.push(options[bestI]);
});
if (bySim.length > 0)
return bySim;
// 单选/多选:映射不到任何选项的文本不算答案(避免"deserve"这类乱答占位、挡住题库)
if ("0" === type || "1" === type)
return [];
return cleaned;
}, bankVote = async (questionData, filled, windowz = _unsafeWindow, prefetched = null) => {
const server = new ServerApi(windowz);
const config = getConfig();
const q = questionData;
const isJudge = "3" === String(q.type);
const canonJudge = (s) => {
const t = String(s || "").trim();
if (/^(正确|对|是|√|true|t|ri|yes|y)$/i.test(t)) return "正确";
if (/^(错误|错|否|×|x|false|f|wr|no|n)$/i.test(t)) return "错误";
return t;
};
const norm = (a) => {
if (a == null) return [];
if (isJunkAnswer(a)) return [];
const n = normalizeAnswer(a, q);
const arr = Array.isArray(n) ? n : [n];
return arr.map(function(x) {
const s = removeHtml(String(x == null ? "" : x)).replace(/\s+/g, "").toLowerCase();
return isJudge ? canonJudge(s).toLowerCase() : s;
}).filter(function(s) {
return s.length > 0;
}).sort();
};
const keyOf = (arr) => arr.join("|");
const votes = /* @__PURE__ */ new Map();
const add = (arr, src) => {
if (!arr || 0 === arr.length) return;
const k = keyOf(arr);
if (!k) return;
const item = votes.get(k) || { key: k, answer: arr, sources: [] };
item.sources.indexOf(src) === -1 && item.sources.push(src);
votes.set(k, item);
};
const original = norm(filled);
add(original, "当前答案");
// 优先复用答题阶段已拿到的各渠道结果,避免复核时重复请求(请求数直接减半)
const reuse = Array.isArray(prefetched) ? prefetched.filter(function(x) {
return x && x.form && x.form !== "提示";
}) : [];
let res;
if (reuse.length > 0) {
res = reuse;
console.log("复核复用已有结果:", reuse.map(function(x) {
return x.form;
}).join("/"));
} else {
const enabled = Array.isArray(config.bankEnabled) ? config.bankEnabled : ["tkh", "yzt", "yx", "mkt", "datam"];
const proms = [];
enabled.includes("tkh") && proms.push(server.getAnswer(q));
enabled.includes("yx") && proms.push(server.getAnswer3(q));
enabled.includes("mkt") && proms.push(server.getAnswer4(q));
enabled.includes("yzt") && proms.push(server.getAnswer2(q));
config.customApiEnabled && config.customApiUrl && proms.push(server.getAnswerFromCustomApi(q));
enabled.includes("datam") && config.datamBank !== false && config.customApiKey && proms.push(server.getAnswerFromLikeApi(q));
enabled.includes("ze") && config.zetoken && proms.push(server.getAnswer5(q));
res = await Promise.all(proms.map(function(p) {
return Promise.resolve(p).catch(function() {
return null;
});
}));
}
res.forEach(function(r) {
r && add(norm(r.answer), r.form || "题库");
});
let best = null;
votes.forEach(function(v) {
!best || v.sources.length > best.sources.length ? best = v : 0;
});
const originalKey = keyOf(original);
const agree = !!best && best.key === originalKey;
// 只有单选/多选/判断题才做"对错"判定;简答/论述等文字题各库措辞不同,只作参考不判错
const checkable = ["0", "1", "3"].includes(String(q.type));
const mismatch = checkable && !!best && !agree && best.sources.length >= 2;
return { votes: Array.from(votes.values()), best, agree, mismatch, checkable, original, originalKey };
}, getAnswers = async (questionData, windowz = _unsafeWindow) => {
let server = new ServerApi(windowz);
const config = getConfig();
const typeNames = { "0": "单选题", "1": "多选题", "2": "填空题", "3": "判断题", "4": "简答题", "5": "名词解释", "6": "论述题", "7": "计算题" };
const typeName = typeNames[questionData.type] || "单选题";
console.log("答题配置:", { aiEnabled: !!config.aiEnabled, aiApiKey: config.aiApiKey ? "已填(已隐藏)" : "(未填)", aiApiUrl: config.aiApiUrl || "(默认)", aiModel: config.aiModel, aiOnly: !!config.aiOnly, customApiEnabled: !!config.customApiEnabled, bankEnabled: config.bankEnabled, datamModel: config.datamModel, datamKey: config.customApiKey ? "已填" : "(未填)" });
const settle = (p) => Promise.resolve(p).catch((e) => {
console.log("渠道请求异常:", e);
return null;
});
// ===== 缓存命中:同一题干 30 分钟内不重复请求(题库答案对同一题干是稳定的)=====
const cacheKey = AnswerCache.key(questionData.question) + "|" + (questionData.type || "");
const cached = config.aiOnly ? null : AnswerCache.get(cacheKey);
if (cached) {
console.log("命中答案缓存,跳过本次请求:", questionData.question.slice(0, 40));
return cached.map(function(x) {
return { ...x, cached: true };
});
}
// ===== 仅AI模式:只问 AI =====
if (config.aiOnly) {
if (!config.aiEnabled || !config.aiApiKey) {
return [{ form: "AI", answer: "", raw: "仅AI模式已开启,但未启用AI或未填密钥" }];
}
const aiOnlyRes = await settle(Inflight.run("ai|" + cacheKey, () => server.getAnswerFromAI(questionData)));
if (aiOnlyRes) {
const mapped = normalizeAnswer(aiOnlyRes.answer, questionData);
if (Array.isArray(mapped) && mapped.length > 0) {
aiOnlyRes.answer = mapped;
return [aiOnlyRes];
}
aiOnlyRes.raw = aiOnlyRes.raw || String(aiOnlyRes.answer || "");
aiOnlyRes.answer = "";
return [aiOnlyRes];
}
return [{ form: "AI", answer: "" }];
}
// ===== 全渠道并行查询:自定义题库 + 在线题库 + AI =====
const enabled = Array.isArray(config.bankEnabled) ? config.bankEnabled : ["tkh", "yzt", "yx", "mkt", "datam"];
const tasks = [];
const names = [];
if (config.customApiEnabled && config.customApiUrl) {
tasks.push(server.getAnswerFromCustomApi(questionData)), names.push("自定义题库");
}
enabled.includes("tkh") && (tasks.push(server.getAnswer(questionData)), names.push("题库海"));
enabled.includes("yzt") && (tasks.push(server.getAnswer2(questionData)), names.push("一之题库"));
enabled.includes("yx") && (tasks.push(server.getAnswer3(questionData)), names.push("言溪题库"));
enabled.includes("mkt") && (tasks.push(server.getAnswer4(questionData)), names.push("muketool"));
enabled.includes("datam") && config.datamBank !== false && config.customApiKey && (tasks.push(server.getAnswerFromLikeApi(questionData)), names.push("LIKE题库"));
enabled.includes("ze") && config.zetoken && (tasks.push(server.getAnswer5(questionData)), names.push("ZE题库"));
const askAI = config.aiEnabled && !!config.aiApiKey;
askAI && (tasks.push(server.getAnswerFromAI(questionData)), names.push("AI"));
if (0 === tasks.length) {
return [{ form: "提示", answer: "", raw: "没有启用任何答题渠道:请开启AI,或勾选在线题库,或启用自定义题库" }];
}
console.log(`并行查询 ${tasks.length} 个渠道: ${names.join(" / ")} 题型: ${typeName}`);
const settled = await Promise.all(tasks.map(settle)).then(function(arr) {
return arr;
});
// ===== 结果整理:全部保留展示,按 自定义题库 > 在线题库 > AI 的顺序排列 =====
const hits = [];
const misses = [];
settled.forEach(function(r) {
if (!r) return;
const mapped = normalizeAnswer(r.answer, questionData);
if (Array.isArray(mapped) && mapped.length > 0 && !isJunkAnswer(mapped)) {
r.answer = mapped;
hits.push(r);
} else {
if (r.answer && String(r.answer).trim())
r.raw = r.raw || ("题库返回无效内容(疑似付费/引流提示): " + String(r.answer).replace(/<[^>]*>/g, "").slice(0, 120));
r.answer = "";
(r.raw || r.form) && misses.push(r);
}
});
const merged = (hits.length > 0 ? hits.concat(misses) : (misses.length > 0 ? misses : [{ form: "AI", answer: "" }]));
hits.length > 0 ? console.log("命中渠道:", hits.map(function(h) {
return h.form + "=" + (Array.isArray(h.answer) ? h.answer.join("|") : h.answer);
}).join(" ; ")) : console.log("所有渠道均未取得可用答案");
// 写入缓存(仅当有命中;未命中的题下次仍可重试)
hits.length > 0 && AnswerCache.set(cacheKey, merged.map(function(x) {
return { form: x.form, answer: x.answer, raw: x.raw, num: x.num, usenum: x.usenum };
}));
return merged;
}, fillAnswer = (answer, questionData, html, iframeWindow) => {
answer = answer.filter(function(item) {
return item && !isJunkAnswer(item.answer) && (Array.isArray(item.answer) ? item.answer.length > 0 : String(item.answer || "").length > 0);
}), console.log(answer);
for (let i = 0; i < answer.length; i++) {
if ("string" == typeof answer[i].answer)
answer[i].answer = [answer[i].answer];
let tmp = setAnswer(answer[i].answer, questionData, html, iframeWindow);
if (tmp)
return tmp;
}
return false;
}, setAnswer = (answer, questionData, html, iframeWindow) => {
switch (questionData.type) {
case "0":
case "1":
const matchArr = matchAnswer(answer, questionData.options);
matchArr.length > 0 && clearCurrent(html, iframeWindow);
for (var i = 0; i < matchArr.length; i++)
console.log($$1(html).find("li").eq(matchArr[i]), matchArr[i]), $$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").eq(matchArr[i]).click(), $$1(html).find(".answerBg").eq(matchArr[i]).click(), $$1(html).find("li").eq(matchArr[i]).click();
return matchArr.length > 0 && answer;
case "3":
return clearCurrent(html, iframeWindow), answer instanceof Array && (answer = answer[0]), $$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").each(function() {
"true" == $$1(this).val() ? answer.match(/(^|,)(True|true|正确|是|对|√|T|ri)(,|$)/) && $$1(this).click() : answer.match(/(^|,)(False|false|错误|否|错|×|F|wr)(,|$)/) && $$1(this).click();
}), $$1(html).find(".answerBg").each(function() {
"true" == $$1(this).find(".num_option").attr("data") ? answer.match(/(^|,)(True|true|正确|是|对|√|T|ri)(,|$)/) && $$1(this).click() : answer.match(/(^|,)(False|false|错误|否|错|×|F|wr)(,|$)/) && $$1(this).click();
}), !!($$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").is(":checked") || $$1(html).find(".check_answer").length > 0 || $$1(html).find(".check_answer_dx").length > 0) && answer;
case "2":
case "9":
case "4":
case "5":
case "6":
case "7":
return clearCurrent(html, iframeWindow), $$1(html).find("textarea").each(function(index) {
if (index < answer.length) {
iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function() {
this.setContent(answer[index].replace(/第.空:/g, ""));
});
}
}), answer;
default:
return false;
}
}, matchAnswer = (answer, options) => {
answer = ((answer2) => {
if (answer2 instanceof Array) {
answer2 = answer2.filter(function(item) {
return null !== item;
});
for (let i2 = 0; i2 < answer2.length; i2++)
answer2[i2] = removeHtml(answer2[i2]);
} else
"string" == typeof answer2 && (answer2 = cl(answer2));
return answer2;
})(answer);
for (var matchArr = [], i = 0; i < answer.length; i++)
for (var j = 0; j < options.length; j++)
answer[i] == options[j] && matchArr.push(j);
return matchArr;
}, clearCurrent = (item, iframeWindow) => {
$$1(item).find(".answerBg, .textDIV, .eidtDiv").each(function() {
($$1(this).find(".check_answer").length || $$1(this).find(".check_answer_dx").length) && $$1(this).click();
}), $$1(item).find("textarea").each(function() {
iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function() {
this.setContent("");
});
}), $$1(item).find(":radio, :checkbox").prop("checked", false), $$1(item).find("textarea").each(function() {
iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function() {
this.setContent("");
});
});
}, useAskStore = pinia$1.defineStore({ id: "ask", state: () => ({ dialogVisible: true, count: 0, questionList: [], task: { name: "暂未加载", work: { questionList: [], inx: 0 }, video: [], log: [], status: "" } }), actions: { reset() {
this.task.name = "暂未加载", this.task.work = { questionList: [], inx: 0 }, this.task.video = [], this.task.status = "", this.count = 0;
}, select(index) {
this.task.work.questionList[index].selected = true, this.task.work.inx = index;
try {
this.task.work.questionList[index].dom.scrollIntoView({ block: "center" });
} catch (e) {
log(e, "error");
}
}, get(index) {
return this.task.work.questionList[index];
}, insert(question) {
this.task.work.questionList.push(question);
}, update(index, question) {
this.task.work.questionList[index] = question;
}, log(msg, level = "info") {
this.task.log.length > 20 && this.task.log.shift(), this.task.log.push({ time: (/* @__PURE__ */ new Date()).toLocaleTimeString(), msg, type: level });
}, msg(msg) {
this.task.status = msg;
} } }), _sfc_main = vue.defineComponent({ setup() {
const askstore = useAskStore(), { dialogVisible, count, questionList, task } = pinia$1.storeToRefs(askstore), askActiveName = vue.ref("first"), askActiveNames = vue.ref(["1"]), msg = vue.ref("本脚本仅用于学习交流,请24h内删除
禁止用于各种非法用途,否则后果自负
本脚本题库接口均来源于网络以及用户反馈添加,不对题库准确率以及可用性负责,请自行判断、评估是否使用。
"), formstoreObj = useformStore(), { forminput, dialogV, activeName } = pinia$1.storeToRefs(formstoreObj), ruleFormRef = vue.ref(), rules = vue.reactive({ interval: [{ required: true, message: "间隔时间不能为空" }, { type: "number", message: "间隔时间必须为数字" }, { validator: (rule, value) => value >= 1 ? Promise.resolve() : Promise.reject("间隔时间必须大于等于1") }], answerInterval: [{ required: true, message: "答题间隔不能为空" }, { type: "number", message: "答题间隔必须为数字" }, { validator: (rule, value) => value >= 1 ? Promise.resolve() : Promise.reject("答题间隔必须大于等于1") }], token: [{ validator: (rule, value) => {
if (value) {
return /^[a-zA-Z0-9]{6,}$/.test(value) ? Promise.resolve() : Promise.reject("token格式错误");
}
return Promise.resolve();
} }] });
vue.watch(() => forminput.value.aiApiUrl, (url) => formstoreObj.applyModelPresets(url), { immediate: true });
return { count, dialogVisible, questionList, askActiveName, askActiveNames, task, msg, Aim: aim_default, handleClick: (e) => {
askstore.select(e);
}, dialogV, activeName, ruleFormRef, forminput, rules, submitForm: async (formEl) => {
formEl && await formEl.validate((valid, fields) => {
valid && (formstoreObj.saveConfig(forminput.value), ElementPlus.ElNotification({ title: "Success", message: "配置保存成功,请自行刷新页面", type: "success" }), dialogV.value = false);
});
}, fetchModels: () => formstoreObj.fetchModels(), userConfig, Setting: setting_default };
} }), _hoisted_1 = { class: "dialog-footer" }, _hoisted_2 = { key: 0 }, _hoisted_3 = { class: "question_div" }, _hoisted_4 = { class: "question_ti" }, _hoisted_5 = { key: 0 }, _hoisted_6 = { key: 1 }, _hoisted_7 = { key: 2 }, _hoisted_8 = ["innerHTML"], _hoisted_9 = { key: 0, style: { "margin-top": "20px" } }, _hoisted_10 = { key: 1 }, _hoisted_11 = { key: 2 }, _hoisted_12 = { height: "100px" }, _hoisted_13 = ["innerHTML"];
const Ask = _export_sfc(_sfc_main, [["render", function(_ctx, _cache, $props, $setup, $data, $options) {
const _component_el_button = vue.resolveComponent("el-button"), _component_el_switch = vue.resolveComponent("el-switch"), _component_el_input = vue.resolveComponent("el-input"), _component_el_input_number = vue.resolveComponent("el-input-number"), _component_el_option = vue.resolveComponent("el-option"), _component_el_select = vue.resolveComponent("el-select"), _component_el_checkbox = vue.resolveComponent("el-checkbox"), _component_el_checkbox_group = vue.resolveComponent("el-checkbox-group"), _component_el_tooltip = vue.resolveComponent("el-tooltip"), _component_el_form_item = vue.resolveComponent("el-form-item"), _component_el_tab_pane = vue.resolveComponent("el-tab-pane"), _component_el_tabs = vue.resolveComponent("el-tabs"), _component_el_form = vue.resolveComponent("el-form"), _component_el_dialog = vue.resolveComponent("el-dialog"), _component_el_text = vue.resolveComponent("el-text"), _component_el_skeleton = vue.resolveComponent("el-skeleton"), _component_el_card = vue.resolveComponent("el-card"), _component_el_divider = vue.resolveComponent("el-divider"), _component_el_col = vue.resolveComponent("el-col"), _component_el_row = vue.resolveComponent("el-row"), _component_el_scrollbar = vue.resolveComponent("el-scrollbar"), _component_el_tag = vue.resolveComponent("el-tag"), _component_el_alert = vue.resolveComponent("el-alert"), _component_el_empty = vue.resolveComponent("el-empty");
return vue.openBlock(), vue.createElementBlock(vue.Fragment, null, [vue.createVNode(_component_el_button, { type: "danger", id: "csbutton", icon: _ctx.Setting, circle: "", onClick: _cache[0] || (_cache[0] = ($event) => _ctx.dialogV = !_ctx.dialogV) }, null, 8, ["icon"]), vue.createVNode(_component_el_dialog, { modelValue: _ctx.dialogV, "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => _ctx.dialogV = $event), title: "💯超星学习通满分助手", width: "30%", modal: false, center: "", draggable: "" }, { footer: vue.withCtx(() => [vue.createElementVNode("span", _hoisted_1, [vue.createVNode(_component_el_button, { onClick: _cache[2] || (_cache[2] = ($event) => _ctx.dialogV = false) }, { default: vue.withCtx(() => [vue.createTextVNode("取消")]), _: 1 }), vue.createVNode(_component_el_button, { onClick: _cache[9] || (_cache[9] = ($event) => _ctx.fetchModels()) }, { default: vue.withCtx(() => [vue.createTextVNode("获取模型列表")]), _: 1 }), vue.createVNode(_component_el_button, { type: "primary", onClick: _cache[3] || (_cache[3] = ($event) => _ctx.submitForm(_ctx.ruleFormRef)) }, { default: vue.withCtx(() => [vue.createTextVNode("保存")]), _: 1 })])]), default: vue.withCtx(() => [vue.createVNode(_component_el_form, { ref: "ruleFormRef", rules: _ctx.rules, model: _ctx.forminput, class: "demo-ruleForm" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_tabs, { class: "demo-tabs", modelValue: _ctx.activeName, "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => _ctx.activeName = $event) }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.userConfig, (item) => (vue.openBlock(), vue.createBlock(_component_el_tab_pane, { key: item.name, label: item.label, name: item.name }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(item.config, (item1) => (vue.openBlock(), vue.createBlock(_component_el_form_item, { label: item1.label, prop: item1.name }, { default: vue.withCtx(() => [vue.createVNode(_component_el_tooltip, { class: "box-item", effect: "dark", content: item1.desc || "", placement: "top" }, { default: vue.withCtx(() => ["switch" === item1.type ? (vue.openBlock(), vue.createBlock(_component_el_switch, { key: 0, modelValue: _ctx.forminput[item1.name], "onUpdate:modelValue": ($event) => _ctx.forminput[item1.name] = $event }, null, 8, ["modelValue", "onUpdate:modelValue"])) : "input" === item1.type ? (vue.openBlock(), vue.createBlock(_component_el_input, { key: 1, modelValue: _ctx.forminput[item1.name], "onUpdate:modelValue": ($event) => _ctx.forminput[item1.name] = $event }, null, 8, ["modelValue", "onUpdate:modelValue"])) : "number" === item1.type ? (vue.openBlock(), vue.createBlock(_component_el_input_number, { key: 2, modelValue: _ctx.forminput[item1.name], "onUpdate:modelValue": ($event) => _ctx.forminput[item1.name] = $event }, null, 8, ["modelValue", "onUpdate:modelValue"])) : "select" === item1.type ? (vue.openBlock(), vue.createBlock(_component_el_select, { key: 3, modelValue: _ctx.forminput[item1.name], "onUpdate:modelValue": ($event) => _ctx.forminput[item1.name] = $event, placeholder: "请选择", filterable: true, allowCreate: true, defaultFirstOption: true, clearable: true }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(item1.options, (item2) => (vue.openBlock(), vue.createBlock(_component_el_option, { key: item2.value, label: item2.label, value: item2.value }, null, 8, ["label", "value"]))), 128))]), _: 2 }, 1032, ["modelValue", "onUpdate:modelValue"])) : "checkbox" === item1.type ? (vue.openBlock(), vue.createBlock(_component_el_checkbox_group, { key: 4, modelValue: _ctx.forminput[item1.name], "onUpdate:modelValue": ($event) => _ctx.forminput[item1.name] = $event }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(item1.options, (item2) => (vue.openBlock(), vue.createBlock(_component_el_checkbox, { key: item2.value, label: item2.value, name: item2.value }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(item2.label), 1)]), _: 2 }, 1032, ["label", "name"]))), 128))]), _: 2 }, 1032, ["modelValue", "onUpdate:modelValue"])) : vue.createCommentVNode("", true)]), _: 2 }, 1032, ["content"])]), _: 2 }, 1032, ["label", "prop"]))), 256))]), _: 2 }, 1032, ["label", "name"]))), 128))]), _: 1 }, 8, ["modelValue"])]), _: 1 }, 8, ["rules", "model"])]), _: 1 }, 8, ["modelValue"]), (vue.openBlock(), vue.createBlock(vue.Teleport, { to: "body" }, [vue.createVNode(_component_el_button, { id: "zeokdjg", type: "success", plain: "", round: "", icon: _ctx.Aim, onClick: _cache[5] || (_cache[5] = ($event) => _ctx.dialogVisible = !_ctx.dialogVisible) }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString("暂未加载" == _ctx.task.name ? "等待任务加载" : "正在完成:" + _ctx.task.name), 1)]), _: 1 }, 8, ["icon"]), vue.createVNode(_component_el_dialog, { modelValue: _ctx.dialogVisible, "onUpdate:modelValue": _cache[8] || (_cache[8] = ($event) => _ctx.dialogVisible = $event), width: "400px", title: "💯超星学习通满分助手", modal: false, "append-to-body": false, "lock-scroll": false, center: "", draggable: "" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_button, { style: { "margin-bottom": "20px" }, type: "primary", onClick: _cache[6] || (_cache[6] = ($event) => _ctx.dialogV = !_ctx.dialogV), plain: "" }, { default: vue.withCtx(() => [vue.createTextVNode("打开配置")]), _: 1 }), vue.createVNode(_component_el_text, { class: "mx-1", size: "large", type: "danger" }, { default: vue.withCtx(() => [vue.createTextVNode("题库秘钥配置请点击这个按钮")]), _: 1 }), vue.createVNode(_component_el_tabs, { modelValue: _ctx.askActiveName, "onUpdate:modelValue": _cache[7] || (_cache[7] = ($event) => _ctx.askActiveName = $event), class: "demo-tabs" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_tab_pane, { label: "运行框", name: "first" }, { default: vue.withCtx(() => [_ctx.task.work.questionList.length > 0 ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_2, [vue.createElementVNode("div", _hoisted_3, [vue.createVNode(_component_el_card, { shadow: "hover" }, { default: vue.withCtx(() => [vue.createElementVNode("h1", _hoisted_4, [vue.createVNode(_component_el_text, { size: "large", truncated: "" }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(_ctx.task.work.inx + 1 + "." + _ctx.task.work.questionList[_ctx.task.work.inx].question), 1)]), _: 1 })]), _ctx.task.work.questionList[_ctx.task.work.inx].answer ? (vue.openBlock(), vue.createElementBlock("p", _hoisted_6, [vue.createElementVNode("p", null, [vue.createElementVNode("pre", null, vue.toDisplayString(_ctx.task.work.questionList[_ctx.task.work.inx].answer), 1)])])) : (vue.openBlock(), vue.createElementBlock("p", _hoisted_5, [vue.createVNode(_component_el_skeleton, { rows: 3, animated: "" })]))]), _: 1 })]), "考试" != _ctx.task.name ? (vue.openBlock(), vue.createBlock(_component_el_divider, { key: 0 }, { default: vue.withCtx(() => [vue.createTextVNode(" 题号 ")]), _: 1 })) : vue.createCommentVNode("", true), "考试" != _ctx.task.name ? (vue.openBlock(), vue.createBlock(_component_el_scrollbar, { key: 1, height: "100px" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_row, null, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.task.work.questionList, (item, index) => (vue.openBlock(), vue.createBlock(_component_el_col, { span: 4, key: index }, { default: vue.withCtx(() => [vue.createVNode(_component_el_button, { type: item.status || "info", plain: "", class: "question_btn", onClick: ($event) => _ctx.handleClick(index) }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(index + 1), 1)]), _: 2 }, 1032, ["type", "onClick"])]), _: 2 }, 1024))), 128))]), _: 1 })]), _: 1 })) : vue.createCommentVNode("", true), _ctx.task.work.questionList[_ctx.task.work.inx].allAnswer ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_7, [vue.createVNode(_component_el_divider, null, { default: vue.withCtx(() => [vue.createTextVNode(" 接口返回 ")]), _: 1 }), vue.createVNode(_component_el_tabs, { "tab-position": "left", style: { height: "200px" }, class: "demo-tabs" }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.task.work.questionList[_ctx.task.work.inx].allAnswer, (item, index) => (vue.openBlock(), vue.createBlock(_component_el_tab_pane, { label: item.form }, { default: vue.withCtx(() => [vue.createElementVNode("div", null, [vue.createElementVNode("div", { innerHTML: (item.answer || item.raw || "暂无答案") + "
如果要填写付费秘钥,在本悬浮窗最上方的打开配置中填入秘钥,切记填写完要刷新页面才会生效
" }, null, 8, _hoisted_8), null != item.num ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_9, [vue.createElementVNode("div", null, [vue.createVNode(_component_el_tag, { class: "ml-2", type: "info" }, { default: vue.withCtx(() => [vue.createTextVNode("已用次数:" + vue.toDisplayString(item.usenum), 1)]), _: 2 }, 1024)]), vue.createElementVNode("div", null, [vue.createVNode(_component_el_tag, { class: "ml-2", type: "success" }, { default: vue.withCtx(() => [vue.createTextVNode("剩余次数:" + vue.toDisplayString(item.num), 1)]), _: 2 }, 1024)])])) : vue.createCommentVNode("", true)])]), _: 2 }, 1032, ["label"]))), 256))]), _: 1 })])) : vue.createCommentVNode("", true)])) : _ctx.task.video.status ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_10, [vue.createVNode(_component_el_alert, { title: "倍速有风险,挂科两行泪", type: "error", center: "", "show-icon": "" }), vue.createVNode(_component_el_text, { class: "mx-1", size: "large", type: "danger" }, { default: vue.withCtx(() => [vue.createTextVNode(" 正在完成视频任务 ")]), _: 1 })])) : (vue.openBlock(), vue.createElementBlock("div", _hoisted_11, [vue.createElementVNode("div", _hoisted_12, [vue.createVNode(_component_el_empty, { description: _ctx.task.name }, null, 8, ["description"])])]))]), _: 1 }), vue.createVNode(_component_el_tab_pane, { label: "运行日志", name: "second" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_scrollbar, { height: "200px" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_row, null, { default: vue.withCtx(() => [vue.createVNode(_component_el_col, { span: 24 }, { default: vue.withCtx(() => [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.task.log, (item, index) => (vue.openBlock(), vue.createElementBlock("p", { key: index, class: "cx_log" }, [vue.createVNode(_component_el_text, { size: "small", type: "info", class: "mx-1" }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(item.time), 1)]), _: 2 }, 1024), vue.createVNode(_component_el_text, { class: "mx-1", type: "info" == item.type ? "" : item.type }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(" " + item.msg), 1)]), _: 2 }, 1032, ["type"])]))), 128))]), _: 1 })]), _: 1 })]), _: 1 })]), _: 1 }), vue.createVNode(_component_el_tab_pane, { label: "公告", name: "msg" }, { default: vue.withCtx(() => [vue.createVNode(_component_el_card, { shadow: "hover" }, { default: vue.withCtx(() => [vue.createElementVNode("div", { innerHTML: _ctx.msg }, null, 8, _hoisted_13)]), _: 1 })]), _: 1 })]), _: 1 }, 8, ["modelValue"]), vue.createElementVNode("p", null, [_ctx.task.status ? (vue.openBlock(), vue.createBlock(_component_el_tag, { key: 0 }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(_ctx.task.status), 1)]), _: 1 })) : vue.createCommentVNode("", true)])]), _: 1 }, 8, ["modelValue"])]))], 64);
}], ["__scopeId", "data-v-c3c6b09f"]]);
class Cx {
constructor() {
__publicField(this, "app");
__publicField(this, "askStore");
__publicField(this, "ServerApi");
__publicField(this, "defaultConfig");
this.app = vue.createApp(Ask).use(ElementPlus).use(pinia$1.createPinia()), this.askStore = useAskStore(), this.ServerApi = new ServerApi(), this.defaultConfig = getConfig(), this.app.mount((() => {
const div = _unsafeWindow.top.document.createElement("div");
return div.id = "xxxxzx", _unsafeWindow.top.document.getElementById(div.id) || _unsafeWindow.top.document.body.append(div), div;
})());
}
innerbook() {
}
async audio(iframeWindow) {
this.askStore.reset(), this.askStore.task.name = "视频音频";
const audio = iframeWindow.document.getElementById("audio_html5_api");
return audio.muted = true, audio.autoplay = true, audio.volume = 0, audio.play().then(function() {
console.log("播放成功");
}).catch(function(error) {
"NotAllowedError" === error.name ? ElementPlus.ElMessageBox.alert("由于自动播放需要用户点击过浏览器,请确认即可", "温馨提示", { confirmButtonText: "确认", callback: () => {
audio.play();
} }) : console.error("视频播放失败,原因:", error);
}), new Promise((resolve) => {
const intervalId = setInterval(() => {
audio.ended ? (clearInterval(intervalId), log("监听到音频已完成", "success"), resolve()) : audio.paused && audio.play();
}, 1e3);
audio.addEventListener("ended", function() {
log("监听到音频已完成1", "success"), audio.pause(), clearInterval(intervalId), resolve();
});
});
}
async video(iframeWindow) {
this.askStore.reset(), this.askStore.task.name = "视频", this.askStore.task.video.status = 1, await waitElementLoaded(iframeWindow, "#video_html5_api"), console.log("视频加载完成");
const player = iframeWindow.videojs("video_html5_api"), playerButton = iframeWindow.document.querySelector(".vjs-big-play-button");
player.muted(true), player.playbackRate(16), player.play();
// 生成随机暂停时间(30-93秒)
const randomPauseTime = Math.floor(Math.random() * (93 - 30 + 1)) + 30;
let pauseTimer = null;
let mouseMoveTimer = null;
// 随机暂停功能
const scheduleRandomPause = () => {
const delay = Math.floor(Math.random() * (93 - 30 + 1) + 30) * 1000;
pauseTimer = setTimeout(() => {
if (!player.paused()) {
player.pause();
console.log(`[视频] 已随机暂停,暂停时间: ${delay / 1000}秒`);
// 暂停2-5秒后恢复播放
setTimeout(() => {
if (player.paused() && "isUnFinishJob" in iframeWindow && iframeWindow.isUnFinishJob()) {
player.play();
console.log("[视频] 已恢复播放");
scheduleRandomPause();
}
}, Math.floor(Math.random() * (5 - 2 + 1) + 2) * 1000);
}
}, delay);
};
scheduleRandomPause();
// 模拟鼠标滑动功能
const simulateMouseMovement = () => {
const doc = iframeWindow.document;
const videoElement = doc.querySelector("#video_html5_api") || doc.body;
// 生成随机位置
const rect = videoElement.getBoundingClientRect();
const x = Math.floor(Math.random() * rect.width) + rect.left;
const y = Math.floor(Math.random() * rect.height) + rect.top;
// 创建并分发鼠标事件
const events = ["mousemove", "mouseover", "mouseenter"];
events.forEach(eventType => {
const event = new MouseEvent(eventType, {
bubbles: true,
cancelable: true,
view: iframeWindow,
clientX: x,
clientY: y,
screenX: x + (iframeWindow.screenX || 0),
screenY: y + (iframeWindow.screenY || 0),
movementX: Math.floor(Math.random() * 10) - 5,
movementY: Math.floor(Math.random() * 10) - 5
});
videoElement.dispatchEvent(event);
});
// 随机滚动页面
if (Math.random() > 0.7) {
const scrollAmount = Math.floor(Math.random() * 100) - 50;
iframeWindow.scrollBy(0, scrollAmount);
}
};
// 每3-8秒模拟一次鼠标活动
const scheduleMouseMovement = () => {
const delay = Math.floor(Math.random() * (8 - 3 + 1) + 3) * 1000;
mouseMoveTimer = setTimeout(() => {
simulateMouseMovement();
if ("isUnFinishJob" in iframeWindow && iframeWindow.isUnFinishJob()) {
scheduleMouseMovement();
}
}, delay);
};
scheduleMouseMovement();
await new Promise((resolve) => {
const intervalId = setInterval(() => {
"isUnFinishJob" in iframeWindow && iframeWindow.isUnFinishJob() ? player.paused() && (playerButton == null ? void 0 : playerButton.click()) : (clearInterval(intervalId), clearTimeout(pauseTimer), clearTimeout(mouseMoveTimer), resolve());
}, 1e3), pauseBase = player.pause;
player.pause = function() {
player.currentTime() >= player.duration() && (console.log("视频播放完成"), player.pause = pauseBase, clearTimeout(pauseTimer), clearTimeout(mouseMoveTimer), resolve());
}, player.on("ended", () => {
console.log("视频播放完成1"), player.pause = pauseBase, player.pause(), clearInterval(intervalId), clearTimeout(pauseTimer), clearTimeout(mouseMoveTimer), resolve();
});
}), console.log("任务点完成");
}
work(iframeWindow) {
return new Promise(async (resolve) => {
try {
decode(iframeWindow);
} catch (e) {
console.log("加密字体解码失败,跳过解码(不影响答题):", e);
}
const Timu = iframeWindow.document.querySelectorAll(".TiMu");
if (!Timu)
return void resolve();
let ques = [], succ = 0;
for (let i = 0; i < Timu.length; i++) {
let data;
try {
data = getQuestion("1", Timu[i]);
} catch (e) {
console.log(`第${i + 1}题解析失败,已跳过:`, e);
continue;
}
console.log(data), ques.push(data);
}
if (0 === ques.length) {
this.askStore.log("未解析到题目,页面结构可能已变化", "error");
return void resolve();
}
this.askStore.reset(), this.askStore.count = ques.length, this.askStore.task.name = "章节测验";
for (let i = 0; i < ques.length; i++) {
await PauseCtl.wait(), PauseCtl.paused && (this.askStore.task.status = "已暂停,点左下角「继续」恢复");
await randomSleep(this.defaultConfig.answerIntervalMin, this.defaultConfig.answerIntervalMax), this.askStore.insert(ques[i]), this.askStore.task.work.inx = i;
let data = await getAnswers(ques[i], iframeWindow);
this.askStore.get(i).allAnswer = data;
let tmp = fillAnswer(data, ques[i], Timu[i], iframeWindow);
tmp ? (this.askStore.get(i).status = "primary", this.askStore.get(i).answer = tmp, succ++) : (this.askStore.get(i).status = "danger", this.askStore.get(i).answer = "暂无答案"), this.askStore.get(i).dom = Timu[i];
}
// ===== 题库复核环节:用题库交叉检查答案 =====
if (this.defaultConfig.verifyAnswers && ques.length > 0) {
this.askStore.log("开始题库复核:交叉检查每道题答案", "info");
let fixed = 0, checked = 0;
for (let i = 0; i < ques.length; i++) {
const raw = this.askStore.get(i).answer;
if (raw == null || "暂无答案" === raw) continue;
const cur = Array.isArray(raw) ? raw : [raw];
if (0 === cur.length) continue;
checked++;
let vr;
try {
vr = await bankVote(ques[i], cur, iframeWindow, this.askStore.get(i).allAnswer);
} catch (e) {
this.askStore.log(`第${i + 1}题复核异常: ${(e && e.message) || e}`, "error");
continue;
}
const bestText = vr.best ? vr.best.answer.join("、") : "";
const srcList = vr.best ? vr.best.sources.join("/") : "";
if (!vr.checkable) {
this.askStore.log(`第${i + 1}题为文字题,不做对错判定${bestText ? ",题库参考答案:「" + bestText + "」" : ""}`, "info");
} else if (vr.mismatch) {
this.askStore.log(`第${i + 1}题复核不一致:当前「${cur.join("、")}」,题库「${bestText}」(${srcList})`, "warning");
if (this.defaultConfig.verifyAutoFix) {
try {
const ok = setAnswer(vr.best.answer, ques[i], Timu[i], iframeWindow);
if (ok) {
this.askStore.get(i).answer = vr.best.answer;
this.askStore.get(i).status = "primary";
fixed++;
this.askStore.log(`第${i + 1}题已按题库修正为「${bestText}」`, "success");
} else {
this.askStore.log(`第${i + 1}题修正失败(页面未接受),保持原答案`, "error");
}
} catch (e) {
this.askStore.log(`第${i + 1}题修正异常: ${(e && e.message) || e}`, "error");
}
}
} else if (vr.agree) {
this.askStore.log(`第${i + 1}题复核一致(${srcList})`, "success");
} else {
this.askStore.log(`第${i + 1}题题库无一致结论${bestText ? ",参考:「" + bestText + "」" : ""},保持原答案`, "info");
}
}
this.askStore.log(`题库复核完成:检查 ${checked} 题,修正 ${fixed} 题`, "success");
}
await PauseCtl.wait();
this.defaultConfig.autoSubmit ? (succ / ques.length < this.defaultConfig.minAccuracy ? (this.askStore.log("章节测验正确率不足,暂存", "error"), iframeWindow.alert = function(e) {
console.log("alert 方法被阻止", e);
}, iframeWindow.noSubmit()) : (await randomSleep(this.defaultConfig.submitDelayMin, this.defaultConfig.submitDelayMax), iframeWindow.btnBlueSubmit(), await sleep(3), iframeWindow.submitCheckTimes(), this.askStore.log("章节测验已完成", "success"), await randomSleep(5, 10), this.askStore.log("正在刷新页面...", "info"), iframeWindow.location.reload()), this.askStore.task.status = `章节测验已完成,等待切换,正确率:${succ}/${ques.length}`, resolve()) : (this.askStore.log("已完成答题,未开启自动提交,等待手动提交中", "success"), this.askStore.task.status = `正在等待手动提交,正确率:${succ}/${ques.length}`);
});
}
homework() {
return new Promise(async (resolve) => {
const Timu = _unsafeWindow.document.querySelectorAll(".questionLi");
if (!Timu)
return void resolve();
let ques = [];
for (let i = 0; i < Timu.length; i++) {
let data;
try {
data = getQuestion("2", Timu[i]);
} catch (e) {
console.log(`第${i + 1}题解析失败,已跳过:`, e);
continue;
}
ques.push(data);
}
this.askStore.reset(), this.askStore.count = ques.length, this.askStore.task.name = "作业";
for (let i = 0; i < ques.length; i++) {
await PauseCtl.wait(), PauseCtl.paused && (this.askStore.task.status = "已暂停,点左下角「继续」恢复");
await randomSleep(this.defaultConfig.answerIntervalMin, this.defaultConfig.answerIntervalMax), this.askStore.insert(ques[i]), this.askStore.task.work.inx = i;
let data = await getAnswers(ques[i]);
this.askStore.get(i).allAnswer = data;
let tmp = fillAnswer(data, ques[i], Timu[i], _unsafeWindow);
tmp ? (this.askStore.get(i).status = "primary", this.askStore.get(i).answer = tmp) : (this.askStore.get(i).status = "danger", this.askStore.get(i).answer = "暂无答案"), this.askStore.get(i).dom = Timu[i];
}
// ===== 题库复核环节 =====
if (this.defaultConfig.verifyAnswers && ques.length > 0) {
this.askStore.log("开始题库复核:交叉检查每道题答案", "info");
let fixed = 0;
for (let i = 0; i < ques.length; i++) {
const raw = this.askStore.get(i).answer;
if (raw == null || "暂无答案" === raw) continue;
const cur = Array.isArray(raw) ? raw : [raw];
if (0 === cur.length) continue;
let vr;
try {
vr = await bankVote(ques[i], cur, _unsafeWindow, this.askStore.get(i).allAnswer);
} catch (e) {
this.askStore.log(`第${i + 1}题复核异常: ${(e && e.message) || e}`, "error");
continue;
}
const bestText = vr.best ? vr.best.answer.join("、") : "";
const srcList = vr.best ? vr.best.sources.join("/") : "";
if (!vr.checkable) {
this.askStore.log(`第${i + 1}题为文字题,不做对错判定${bestText ? ",题库参考答案:「" + bestText + "」" : ""}`, "info");
} else if (vr.mismatch) {
this.askStore.log(`第${i + 1}题复核不一致:当前「${cur.join("、")}」,题库「${bestText}」(${srcList})`, "warning");
if (this.defaultConfig.verifyAutoFix) {
try {
const ok = setAnswer(vr.best.answer, ques[i], Timu[i], _unsafeWindow);
if (ok) {
this.askStore.get(i).answer = vr.best.answer;
this.askStore.get(i).status = "primary";
fixed++;
this.askStore.log(`第${i + 1}题已按题库修正为「${bestText}」`, "success");
}
} catch (e) {
this.askStore.log(`第${i + 1}题修正异常: ${(e && e.message) || e}`, "error");
}
}
} else if (vr.agree) {
this.askStore.log(`第${i + 1}题复核一致(${srcList})`, "success");
} else {
this.askStore.log(`第${i + 1}题题库无一致结论${bestText ? ",参考:「" + bestText + "」" : ""},保持原答案`, "info");
}
}
this.askStore.log(`题库复核完成:修正 ${fixed} 题`, "success");
}
});
}
exam() {
return new Promise(async (resolve) => {
this.askStore.reset();
this.askStore.task.name = "考试";
const cfg = this.defaultConfig;
const answeredMap = {};
const getMarkHtml = () => {
try {
const el = _unsafeWindow.document.querySelector(".questionLi .mark_name") || _unsafeWindow.document.querySelector(".mark_name");
return el ? el.innerHTML : "";
} catch (e) {
return "";
}
};
let guard = 0, finished = false;
this.askStore.log("考试模式启动:自动识别并整卷作答", "success");
while (!finished && guard++ < (cfg.autoExam ? 400 : 3600)) {
await PauseCtl.wait(), PauseCtl.paused && (this.askStore.task.status = "已暂停,点左下角「继续」恢复");
await waitElementLoaded(_unsafeWindow, ".mark_name");
let data;
try {
data = getQuestion("3", _unsafeWindow.document.body);
} catch (e) {
this.askStore.log("考试题目解析失败: " + ((e && e.message) || e), "error");
break;
}
if (!answeredMap[data.question]) {
answeredMap[data.question] = true;
const idx = this.askStore.task.work.questionList.length;
this.askStore.insert(data);
this.askStore.task.work.inx = idx;
this.askStore.task.status = `正在作答第 ${idx + 1} 题`;
const answers = await getAnswers(data);
this.askStore.get(idx).allAnswer = answers;
const tmp = fillAnswer(answers, data, _unsafeWindow.document.getElementsByClassName("mark_table")[0], _unsafeWindow);
if (tmp) {
this.askStore.get(idx).status = "primary", this.askStore.get(idx).answer = tmp, this.askStore.log(`第 ${idx + 1} 题已填写`, "success");
} else {
this.askStore.get(idx).status = "danger", this.askStore.get(idx).answer = "暂无答案", this.askStore.log(`第 ${idx + 1} 题暂无答案`, "error");
}
// ===== 题库复核:考试翻页后无法回填,故每题填写后立即复核 =====
if (cfg.verifyAnswers && tmp) {
const cur = Array.isArray(tmp) ? tmp : [tmp];
let vr = null;
try {
vr = await bankVote(data, cur, _unsafeWindow, this.askStore.get(idx).allAnswer);
} catch (e) {
this.askStore.log(`第 ${idx + 1} 题复核异常: ${(e && e.message) || e}`, "error");
}
if (vr) {
const bestText = vr.best ? vr.best.answer.join("、") : "";
const srcList = vr.best ? vr.best.sources.join("/") : "";
if (!vr.checkable) {
this.askStore.log(`第 ${idx + 1} 题为文字题,不做对错判定${bestText ? ",题库参考答案:「" + bestText + "」" : ""}`, "info");
} else if (vr.mismatch) {
this.askStore.log(`第 ${idx + 1} 题复核不一致:当前「${cur.join("、")}」,题库「${bestText}」(${srcList})`, "warning");
if (cfg.verifyAutoFix) {
try {
const ok = setAnswer(vr.best.answer, data, _unsafeWindow.document.getElementsByClassName("mark_table")[0], _unsafeWindow);
if (ok) {
this.askStore.get(idx).answer = vr.best.answer;
this.askStore.log(`第 ${idx + 1} 题已按题库修正为「${bestText}」`, "success");
} else {
this.askStore.log(`第 ${idx + 1} 题修正失败(页面未接受),保持原答案`, "error");
}
} catch (e) {
this.askStore.log(`第 ${idx + 1} 题修正异常: ${(e && e.message) || e}`, "error");
}
}
} else if (vr.agree) {
this.askStore.log(`第 ${idx + 1} 题复核一致(${srcList})`, "success");
} else {
this.askStore.log(`第 ${idx + 1} 题题库无一致结论${bestText ? ",参考:「" + bestText + "」" : ""},保持原答案`, "info");
}
}
}
}
if (!cfg.autoExam) {
this.askStore.task.status = "已完成当前题,等待手动切换(切到新题自动继续)";
await sleep(2);
continue;
}
await randomSleep(cfg.answerIntervalMin, cfg.answerIntervalMax);
const before = getMarkHtml();
const nextButton = $('.nextDiv .jb_btn:contains("下一题")');
if (nextButton && nextButton.length > 0) {
nextButton.click();
} else if ("function" == typeof _unsafeWindow.getTheNextQuestion) {
_unsafeWindow.getTheNextQuestion(1);
} else {
this.askStore.log("已到最后一题,考试答题完成", "success");
this.askStore.task.status = "考试答题完成";
finished = true;
break;
}
let changed = false;
for (let t = 0; t < 40 && !changed; t++) {
await sleep(0.5);
const cur = getMarkHtml();
changed = "" !== cur && cur !== before;
}
if (!changed) {
this.askStore.log("页面未出现新题目,判定答题完成", "success");
this.askStore.task.status = "考试答题完成";
finished = true;
break;
}
}
await PauseCtl.wait();
if (cfg.examAutoSubmit && finished) {
await this.examSubmit();
}
resolve();
});
}
async examSubmit() {
this.askStore.log("配置已开启考试自动交卷,开始执行交卷流程", "warning");
await sleep(3);
try {
const previewBtn = $(".completeBtn");
if (previewBtn && previewBtn.length > 0)
previewBtn.click();
else if ("function" == typeof _unsafeWindow.topreview)
_unsafeWindow.topreview();
else {
this.askStore.log("未找到整卷预览入口,请手动交卷", "error");
return;
}
await sleep(3);
const submitBtn = $('a:contains("交卷")').filter(function() {
return "交卷" === $(this).text().trim();
});
if (submitBtn && submitBtn.length > 0) {
this.askStore.log("点击交卷...", "warning");
submitBtn.click();
} else {
this.askStore.log("预览页未找到交卷按钮,请手动交卷", "error");
return;
}
for (let t = 0; t < 20; t++) {
await sleep(0.5);
const confirmBtn = $('.jb_btn:contains("确定"), .btnBlue:contains("确定"), #popok, .layui-layer-btn0, a:contains("确认")');
if (confirmBtn && confirmBtn.length > 0) {
this.askStore.log("检测到交卷确认弹窗,点击确定...", "warning");
confirmBtn.click();
break;
}
}
await sleep(2);
this.askStore.log("自动交卷流程执行完毕,请自行确认交卷结果", "success");
} catch (e) {
this.askStore.log("自动交卷异常: " + ((e && e.message) || e), "error");
}
}
// ===== 讨论任务(module=insertbbs):AI 生成简短发言并提交 =====
async discuss(iframeWindow, meta) {
return new Promise(async (resolve) => {
const topic = String((meta && (meta.title || meta.name)) || "").trim();
this.askStore.reset();
this.askStore.task.name = "讨论";
if (!topic) {
this.askStore.log("讨论题目为空,跳过", "error");
return void resolve(false);
}
this.askStore.log("开始处理讨论: " + topic.replace(/\s+/g, " ").slice(0, 50), "info");
await PauseCtl.wait();
let replies = [];
try {
replies = this.discussCollectReplies(iframeWindow);
} catch (e) {
}
if (replies.length > 0) this.askStore.log(`收集到 ${replies.length} 条他人发言,作为参考`, "success");
let text = "";
try {
text = await new ServerApi(iframeWindow).getAnswerForDiscussion(topic, replies, {
course: getCourseName(),
chapter: getCatalogChapter()
});
} catch (e) {
this.askStore.log("讨论AI生成异常: " + ((e && e.message) || e), "error");
}
if (!text) {
this.askStore.log("AI未生成讨论内容,跳过(请确认已启用AI并填写密钥)", "error");
return void resolve(false);
}
this.askStore.log("已生成发言: " + text.slice(0, 60) + (text.length > 60 ? "…" : ""), "success");
try {
this.askStore.insert({ question: topic, options: [], type: "4", answer: text, section: "" });
this.askStore.get(0).status = "primary";
this.askStore.get(0).answer = text;
} catch (e) {
}
// 打开发言框并填入(最多 3 次)
let filled = "";
for (let attempt = 0; attempt < 3 && !filled; attempt++) {
filled = this.discussFill(iframeWindow, text);
if (!filled) {
const opened = this.discussOpenEditor(iframeWindow);
this.askStore.log(opened ? "已点击「回复」展开输入框,重试填写…" : "未找到输入框,重试中…", "warning");
await sleep(1.5);
}
}
if (!filled) {
this.askStore.log("讨论 iframe 内没有可编辑框(该课程讨论需在独立页面作答)", "warning");
return void resolve(false);
}
this.askStore.log("发言已填入输入框(" + filled + ")", "success");
await PauseCtl.wait();
await sleep(1);
if (!this.discussSubmit(iframeWindow)) {
this.askStore.log("未找到提交按钮,内容已填好请手动提交", "error");
return void resolve(false);
}
// 匿名确认弹窗:选取消(匿名不计成绩)
try {
const anon = iframeWindow.document.querySelector(".popAnonymousShowHide");
if (anon && anon.getClientRects && anon.getClientRects().length) {
const cancel = anon.querySelector(".cancle, .btn_92_cancel");
cancel && cancel.click();
this.askStore.log("已取消匿名,按实名提交", "warning");
}
} catch (e) {
}
await sleep(2);
this.askStore.task.status = "讨论已完成";
resolve(true);
});
}
discussOpenTab(iframe) {
try {
const win = iframe && iframe.contentWindow;
let url = "";
// ① iframe 自身就是讨论页
try {
const loc = win.location.href;
if (/\/bbs\/|course\/topic|jumpToTopicDetail/i.test(loc)) url = loc;
} catch (e) {
}
// ② iframe 里第一条指向讨论详情的链接
if (!url && win && win.document) {
const a = Array.from(win.document.querySelectorAll('a[href]')).find((n) => /\/bbs\/|course\/topic|jumpToTopicDetail/i.test(n.getAttribute("href") || ""));
if (a) {
try {
url = new URL(a.getAttribute("href"), win.location.href).href;
} catch (e) {
url = a.href;
}
}
}
if (!url) return false;
const key = "mfBbsOpened";
let seen = [];
try {
seen = JSON.parse(sessionStorage.getItem(key) || "[]");
} catch (e) {
seen = [];
}
if (seen.indexOf(url) !== -1) return false;
seen.push(url);
try {
sessionStorage.setItem(key, JSON.stringify(seen.slice(-20)));
} catch (e) {
}
window.open(url, "_blank");
this.askStore.log("已在后台标签打开讨论页,将由该页脚本自动作答", "success");
return true;
} catch (e) {
return false;
}
}
discussCollectReplies(iframeWindow) {
const doc = iframeWindow.document;
const out = [];
// 精确:超星讨论页 .topicDetail_replyItem .replyContent(content 属性是纯文本)
try {
doc.querySelectorAll(".topicDetail_replyItem .replyContent, .replyContent[content]").forEach((el) => {
const t = String(el.getAttribute("content") || el.innerText || el.textContent || "").replace(/\s+/g, " ").trim();
if (t.length >= 6 && t.length <= 800 && -1 === out.indexOf(t)) out.push(t);
});
} catch (e) {
}
if (out.length > 0) return out.slice(0, 8);
const sels = [".reply_content", ".replyContent", ".reply-content", ".answer-content", ".ans-content", ".bbs_reply .content", ".reply_list .content", ".reply-item .content", ".replyItem .content", ".content-box .content", ".fr .content", ".detail p"];
sels.forEach((s) => {
try {
doc.querySelectorAll(s).forEach((el) => {
const t = String(el.innerText || el.textContent || "").replace(/\s+/g, " ").trim();
if (t.length >= 6 && t.length <= 800 && -1 === out.indexOf(t)) out.push(t);
});
} catch (e) {
}
});
return out.slice(0, 6);
}
discussFill(iframeWindow, text) {
const doc = iframeWindow.document;
const visible = (el) => {
try {
return !!(el.getClientRects && el.getClientRects().length);
} catch (e) {
return false;
}
};
// 精确:超星讨论页的回复框 .textareawrap textarea
const precise = Array.from(doc.querySelectorAll(".editContainer textarea, .textareawrap textarea")).filter(visible)[0] || doc.querySelector(".editContainer textarea, .textareawrap textarea");
if (precise) {
try {
precise.focus && precise.focus();
precise.value = text;
precise.dispatchEvent(new iframeWindow.Event("input", { bubbles: true }));
precise.dispatchEvent(new iframeWindow.Event("change", { bubbles: true }));
precise.dispatchEvent(new iframeWindow.Event("keyup", { bubbles: true }));
precise.scrollIntoView && precise.scrollIntoView({ block: "center" });
return "discuss-textarea";
} catch (e) {
}
}
// ① 富文本编辑器 UE
const tas = Array.from(doc.querySelectorAll("textarea"));
for (const ta of tas) {
const name = ta.getAttribute("name") || ta.id;
try {
if (name && iframeWindow.UE && typeof iframeWindow.UE.getEditor === "function") {
const ed = iframeWindow.UE.getEditor(name);
if (ed && ed.setContent) {
ed.setContent(text.replace(/\n/g, "
"));
return "UE:" + name;
}
}
} catch (e) {
}
if (visible(ta) || ta.id || ta.name) {
try {
ta.value = text;
ta.dispatchEvent(new iframeWindow.Event("input", { bubbles: true }));
ta.dispatchEvent(new iframeWindow.Event("change", { bubbles: true }));
return "textarea:" + (name || "未命名");
} catch (e) {
}
}
}
// ② contenteditable 区域
const ces = Array.from(doc.querySelectorAll('[contenteditable="true"], .edui-body-container, .edui-iframe'));
for (const ce of ces) {
if (!visible(ce)) continue;
try {
ce.focus && ce.focus();
if (ce.tagName === "IFRAME") {
const bd = ce.contentDocument && ce.contentDocument.body;
if (!bd) continue;
bd.innerHTML = text.replace(/\n/g, "
");
bd.dispatchEvent(new iframeWindow.Event("input", { bubbles: true }));
return "edui-iframe";
}
ce.innerHTML = text.replace(/\n/g, "
");
ce.dispatchEvent(new iframeWindow.Event("input", { bubbles: true }));
return "contenteditable";
} catch (e) {
}
}
// ③ 页面内嵌套的 ueditor iframe
const frames = Array.from(doc.querySelectorAll("iframe"));
for (const f of frames) {
try {
const bd = f.contentDocument && f.contentDocument.body;
if (bd && bd.getAttribute && "true" === bd.getAttribute("contenteditable")) {
bd.innerHTML = text.replace(/\n/g, "
");
bd.dispatchEvent(new iframeWindow.Event("input", { bubbles: true }));
return "nested-iframe";
}
} catch (e) {
}
}
return "";
}
discussOpenEditor(iframeWindow) {
const doc = iframeWindow.document;
// 精确:超星讨论页顶部 .replyBtn 才会展开 .editContainer
try {
const rb = Array.from(doc.querySelectorAll(".topicDetail_head .replyBtn, .topicDetail_title_right .replyBtn, .replyBtn")).filter((n) => {
try {
return !!(n.getClientRects && n.getClientRects().length);
} catch (e) {
return false;
}
})[0];
if (rb) {
rb.click();
return true;
}
} catch (e) {
}
const nodes = Array.from(doc.querySelectorAll('a,button,span,div,p,li'));
const hit = nodes.find((n) => {
const t = String(n.textContent || "").replace(/\s+/g, "").trim();
if (!t || t.length > 6) return false;
if (!/^(回复|我要回复|发表|写回复|参与讨论|发表评论|评论)$/.test(t)) return false;
try {
return !!(n.getClientRects && n.getClientRects().length);
} catch (e) {
return false;
}
});
if (hit) {
hit.click();
return true;
}
return false;
}
discussSubmit(iframeWindow) {
const doc = iframeWindow.document;
// 精确:超星讨论页提交按钮 .addReply(注意不能点到 .replyBtn,那是"打开发言框")
try {
const add = Array.from(doc.querySelectorAll(".addReply")).filter((n) => {
try {
return !!(n.getClientRects && n.getClientRects().length);
} catch (e) {
return false;
}
})[0];
if (add) {
add.click();
return true;
}
} catch (e) {
}
const nodes = Array.from(doc.querySelectorAll('a,button,span,div,input[type="button"],input[type="submit"]'));
const cands = nodes.filter((n) => {
const t = String(n.textContent || n.value || "").replace(/\s+/g, "").trim();
if (!t || t.length > 8) return false;
if (/replyBtn|cancleReply/.test(n.className || "")) return false;
if (!/^(发表|发布|提交|发送|确定|回复|发表回复|提交回复)$/.test(t)) return false;
try {
return !!(n.getClientRects && n.getClientRects().length);
} catch (e) {
return false;
}
});
if (0 === cands.length) return false;
cands.sort((a, b) => String(a.textContent || "").length - String(b.textContent || "").length);
cands[0].click();
return true;
}
discussDebug(iframeWindow) {
try {
const doc = iframeWindow.document;
return {
textareas: doc.querySelectorAll("textarea").length,
editables: doc.querySelectorAll('[contenteditable="true"]').length,
iframes: doc.querySelectorAll("iframe").length,
url: iframeWindow.location.href
};
} catch (e) {
return String(e);
}
}
discussDebugButtons(iframeWindow) {
try {
return Array.from(iframeWindow.document.querySelectorAll("a,button,span")).map((n) => String(n.textContent || "").replace(/\s+/g, "").trim()).filter((t) => t && t.length <= 8).slice(0, 30);
} catch (e) {
return [];
}
}
pdf(iframeWindow) {
return new Promise(async (resolve) => {
const contentWindow = iframeWindow.document.querySelector("#panView").contentWindow;
contentWindow.scrollTo(0, contentWindow.document.body.scrollHeight), resolve();
});
}
async s(iframeWindow) {
const questionList = $(iframeWindow.document).find(".TiMu").map(function(index, element) {
try {
let questionHtml, questionText, questionType$1, questionAnswer, questionOption = [], questionAnalysis = "";
switch (questionHtml = $(element).find(".Zy_TItle .clearfix"), questionText = removeHtml(questionHtml[0].innerHTML), questionType$1 = questionText.match(/^\【(.+?)\】/)[1], questionText = questionText.replace(questionText.match(/^\【(.+?)\】/)[0], ""), questionType$1) {
case "单选题":
case "多选题":
return questionOption = $(element).find("ul>li").map(function(inx, item) {
return removeHtml($(item).find("a").html());
}).get(), null;
case "判断题":
if (questionAnalysis = removeHtml($(element).find(".Py_addpy:eq(0)").html() || ""), element.innerHTML.includes("正确答案"))
questionAnswer = removeHtml($(element).find(".Py_answer.clearfix>span").html());
else {
const match = $(element).find(".Py_answer.clearfix").html().match(/^(.*?)(?=<\/i>)/s), result = match ? match[1] : "";
questionAnswer = removeHtml(result);
}
if (questionAnswer.includes("正确答案"))
questionAnswer = questionAnswer.replace("正确答案:", "").trim();
else if ($(element).find(".fr.dui").length > 0)
questionAnswer = questionAnswer.replace("我的答案:", "").trim();
else {
if (!questionAnswer.replace("我的答案:", "").trim().includes("√") && !questionAnswer.replace("我的答案:", "").trim().includes("×"))
return null;
questionAnswer = "√" == questionAnswer.replace("我的答案:", "").trim() ? "×" : "√";
}
break;
case "填空题":
if (questionAnswer = $("span.font14", $(element)).map(function(inx, item) {
return removeHtml($(item).html()).replace(/^第.空:/, "").trim();
}).get(), 0 == questionAnswer.length) {
if (questionAnswer = $(element).find(".Py_answer.clearfix>div>div[class='font14']"), !(questionAnswer.length = $(element).find(".Py_answer.clearfix>div>div[class='font14']>>.fr.dui").length))
return null;
questionAnswer = questionAnswer.map(function(inx, item) {
return removeHtml($(item).html()).replace(/^第.空:/, "").trim();
}).get();
}
break;
default:
return null;
}
return { question: questionText, options: questionOption, type: questionType[questionType$1], answer: questionAnswer };
} catch {
return null;
}
}).get();
await this.ServerApi.s(questionList, iframeWindow.location.href);
}
}
const pinia = pinia$1.createPinia(), app = vue.createApp(App).use(ElementPlus).use(pinia), _self = _unsafeWindow, top = _self.top, formStore = useformStore();
var iframeCom = null;
switch (app.mount((() => {
try {
const div = top.document.createElement("div");
return div.id = "cccxapp", top.document.getElementById(div.id) ? div : (top.document.body.append(div), div);
} catch (e) {
log(e, "error");
}
})()), (() => {
document.body.oncopy = null, document.body.oncut = null, document.body.onpaste = null, document.body.onselectstart = null, document.body.ondragstart = null;
const style = document.createElement("style");
style.innerHTML = "\n * {\n -webkit-user-select: auto !important;\n -moz-user-select: auto !important;\n -o-user-select: auto !important;\n user-select: auto !important;\n }\n ", document.head.appendChild(style);
})(), _self.location.pathname) {
case "/work/doHomeWorkNew":
case "/mooc-ans/work/doHomeWorkNew":
case "/mooc2-ans/work/doHomeWorkNew":
location.href.includes("mooc2=1") && (location.href = location.href.replace(/&mooc2=1/g, ""));
break;
case "/mycourse/studentstudy":
case "/mooc-ans/mycourse/studentstudy":
case "/mooc2-ans/mycourse/studentstudy":
if (!_self.location.href.match(/mooc2=1/)) {
ElementPlus.ElNotification({ title: "Auto Ask", message: "暂不支持旧版章节,尝试切换至新版", type: "error" }), _self.location.href = _self.location.href + "&mooc2=1";
break;
}
const cxModel = new Cx();
cxModel.askStore.log("脚本初始化成功!", "success");
const startWork = async () => {
var _a, _b, _c, _d, _e;
await waitElementLoaded(_self, "#iframe");
const cardsIframe = _self.document.querySelector("#iframe");
await waitIframeLoaded(cardsIframe);
const _self1 = cardsIframe.contentWindow;
top.scroll2Job();
let jobList = _self1.document.querySelectorAll(".ans-job-icon") || [];
// 逐个任务点解析"任务容器 + 它自己的 iframe":避免把含多个任务点的外层容器当成单个任务而误判完成
const jobWrapOf = (icon) => {
let node = icon, wrap = icon.parentElement, iframe = null;
for (let k = 0; k < 4 && node; k++) {
node = node.parentElement;
if (!node || !node.querySelectorAll) break;
const frames = node.querySelectorAll("iframe");
// 最近的、含 iframe 的祖先就是这一任务点的容器:立刻停止上溯,
// 否则会爬到章节级容器(那里也可能带 ans-job-finished),把整章任务误判为已完成
if (frames.length > 0) {
wrap = node, iframe = frames[0];
break;
}
}
if (!iframe && wrap && wrap.querySelector) iframe = wrap.querySelector("iframe");
return { wrap, iframe };
};
const isFinishedJob = (icon, wrap) => {
if (icon.classList && icon.classList.contains("ans-job-finished")) return "图标已标记完成";
if (wrap && wrap.classList && wrap.classList.contains("ans-job-finished")) return "外层已标记完成";
if (wrap && wrap.querySelector && wrap.querySelector(".ans-job-finished")) return "容器内含完成标记";
return "";
};
const redoFinished = formStore.forminput.redoFinished !== false;
for (let i = 0; i < jobList.length; i++) {
const item = jobList[i];
const resolved = jobWrapOf(item);
const iframe = resolved.iframe;
const finishedMark = isFinishedJob(item, resolved.wrap);
await PauseCtl.wait();
if (!iframe) {
cxModel.askStore.log("第" + (i + 1) + "个任务点未找到 iframe,跳过", "error");
continue;
}
if (finishedMark && !redoFinished) {
if (iframe.src.match(/\/ananas\/modules\/work\/index\.html/)) {
await waitIframeLoaded(iframe);
const workIframe = (_c = iframe.contentWindow) == null ? void 0 : _c.document.querySelector("iframe");
workIframe && (await waitIframeLoaded(workIframe), cxModel.s(workIframe.contentWindow));
}
console.log(iframe.src, "已完成"), cxModel.askStore.log("已完成的任务点(" + finishedMark + "),跳过");
continue;
}
if (finishedMark && redoFinished) {
cxModel.askStore.log("已完成的任务点(" + finishedMark + "),按配置重新处理", "warning");
}
await waitIframeLoaded(iframe);
let otherInfo = {};
try { otherInfo = JSON.parse(iframe.getAttribute("data") || "{}"); } catch (e) { }
cxModel.askStore.log("正在完成任务:" + (otherInfo.name || otherInfo.title || ("任务点" + (i + 1))));
if (iframe.src.match(/\/ananas\/modules\/video\/index\.html/)) {
if (!formStore.forminput.autoVideo) { cxModel.askStore.log("视频任务已跳过", "success"); continue; }
await cxModel.video(iframe.contentWindow), cxModel.askStore.log("视频任务已完成", "success");
} else if (iframe.src.match(/\/ananas\/modules\/work\/index\.html/)) {
cxModel.askStore.log("即将开始做作业", "info");
const workIframe = (_e = iframe.contentWindow) == null ? void 0 : _e.document.querySelector("iframe");
workIframe && (await waitIframeLoaded(workIframe), await cxModel.work(workIframe.contentWindow), cxModel.askStore.log("作业任务已完成", "success"));
} else if (iframe.src.match(/\/ananas\/modules\/audio\/index\.html/)) {
if (!formStore.forminput.autoVideo) { cxModel.askStore.log("音频任务已跳过", "success"); continue; }
await cxModel.audio(iframe.contentWindow), cxModel.askStore.log("音频任务已完成", "success");
} else if (iframe.src.match(/\/ananas\/modules\/pdf\/index\.html/)) {
await cxModel.pdf(iframe.contentWindow), cxModel.askStore.log("pdf任务已完成", "success");
} else if (/insertbbs/i.test((iframe.getAttribute("module") || "") + " " + iframe.className)) {
if (formStore.forminput.autoDiscuss === false) {
cxModel.askStore.log("讨论任务已跳过(配置关闭)", "success");
continue;
}
const discOk = await cxModel.discuss(iframe.contentWindow, otherInfo);
discOk ? cxModel.askStore.log("讨论任务已完成", "success") : (cxModel.discussOpenTab(iframe) || cxModel.askStore.log("讨论需手动处理:请点开该讨论页,脚本会在讨论页自动作答", "warning"));
} else {
console.log(iframe.src, "未知"), cxModel.askStore.log("未知任务跳过", "success");
}
}
// 兜底:部分讨论卡片没有 ans-job-icon,直接扫描页面里的 insertbbs iframe
if (formStore.forminput.autoDiscuss !== false) {
try {
const bbsFrames = Array.from(_self1.document.querySelectorAll('iframe[module="insertbbs"], iframe.ans-insertbbs-module'));
for (let bi = 0; bi < bbsFrames.length; bi++) {
const bf = bbsFrames[bi];
if (bf.__mfDiscussed) continue;
bf.__mfDiscussed = true;
const wrapInfo = jobWrapOf(bf);
if (!redoFinished && isFinishedJob(bf, wrapInfo.wrap)) {
cxModel.askStore.log("讨论任务已完成,跳过");
continue;
}
if (formStore.forminput.autoDiscuss === false) break;
await PauseCtl.wait();
await waitIframeLoaded(bf);
let bbsInfo = {};
try {
bbsInfo = JSON.parse(bf.getAttribute("data") || "{}");
} catch (e) {
}
await cxModel.discuss(bf.contentWindow, bbsInfo);
}
} catch (e) {
console.log("讨论兜底扫描失败:", e);
}
}
await sleep(formStore.forminput.interval), !formStore.forminput.autoJump && cxModel.askStore.msg("由于未开启自动切换,请手动切换"), formStore.forminput.autoJump && (top == null ? void 0 : top.document.querySelector(".nextChapter").click());
};
setInterval(async () => {
await waitElementLoaded(_self, "#iframe");
const cardsIframe = _self.document.querySelector("#iframe");
await waitIframeLoaded(cardsIframe);
const _self1 = cardsIframe.contentWindow;
iframeCom != _self1.location.href && (iframeCom = _self1.location.href, cxModel.askStore.reset(), startWork());
}, 2e3);
break;
case "/mooc2-ans/mycourse/stu":
case "/mooc-ans/mycourse/stu":
case "/mycourse/stu":
ElementPlus.ElNotification({ title: "Auto Ask", message: "此页面无任务,请自行进入章节页面", type: "error" });
break;
case "/work/selectWorkQuestionYiPiYue":
case "/knowledge/cards":
break;
case "/mooc2/work/dowork":
case "/mooc-ans/mooc2/work/dowork":
case "/mooc2-ans/mooc2/work/dowork":
const cxModel1 = new Cx();
cxModel1.askStore.log("脚本初始化成功!", "success"), await( cxModel1.homework());
break;
case "/exam-ans/exam/test/reVersionTestStartNew":
case "/mooc-ans/exam/test/reVersionTestStartNew":
case "/mooc2-ans/exam/test/reVersionTestStartNew":
case "/exam-ans/exam/test/testStartNew":
case "/mooc-ans/exam/test/testStartNew":
const cxModel2 = new Cx();
cxModel2.askStore.log("脚本初始化成功!", "success");
formStore.forminput.examEnabled === false ? cxModel2.askStore.log("考试自动答题已在配置中关闭,跳过", "warning") : await cxModel2.exam();
break;
}
// ===== 讨论页(groupweb 独立 BBS 页面)自动作答 =====
// 真实结构(已按超星 2026 版页面核对):
// 题目:window.obj.topic.title 或 .topicDetail_title
// 他人回复:.topicDetail_replyItem .replyContent(content 属性为纯文本)
// 打开发言框:.replyBtn
// 回复输入框:.textareawrap > textarea
// 提交按钮:.addReply(注意 .replyBtn 是"打开发言框",不能点错)
(async () => {
try {
const isBbs = /groupweb\.chaoxing\.com/i.test(location.hostname) || /\/course\/topic\/v3\/bbs\//i.test(location.pathname);
if (!isBbs) return;
console.log("[讨论页] 检测到讨论页面:", location.href);
const $ = (s) => document.querySelector(s);
const $$ = (s) => Array.from(document.querySelectorAll(s));
const vis = (el) => {
try {
return !!(el && el.getClientRects && el.getClientRects().length);
} catch (e) {
return false;
}
};
const pickVisible = (s) => $$(s).filter(vis)[0] || null;
// 等话题详情渲染完成
for (let i = 0; i < 40 && !$(".topicDetail_title, #bbsTopicDetail .topicDetail_detail"); i++) await sleep(0.5);
const getTopic = () => {
try {
if (window.obj && window.obj.topic && window.obj.topic.title) return String(window.obj.topic.title).trim();
} catch (e) {
}
const el = $(".topicDetail_title");
if (el) {
const t = String(el.textContent || "").replace(/\s+/g, " ").replace(/^无标题/, "").trim();
if (t) return t;
}
return String(document.title || "").replace(/[-_|—]\s*(超星学习通|超星|学习通)\s*$/i, "").trim();
};
const getReplies = () => {
const out = [];
$$(".topicDetail_replyItem .replyContent, .replyContent[content]").forEach((el) => {
const t = String(el.getAttribute("content") || el.innerText || el.textContent || "").replace(/\s+/g, " ").trim();
if (t.length >= 6 && t.length <= 800 && out.indexOf(t) === -1) out.push(t);
});
return out.slice(0, 8);
};
const openEditor = () => {
const rb = pickVisible(".topicDetail_head .replyBtn") || pickVisible(".topicDetail_title_right .replyBtn") || pickVisible(".replyBtn");
if (rb) {
rb.click();
return true;
}
return false;
};
const fillReply = (text) => {
const ta = pickVisible(".textareawrap textarea") || pickVisible(".editContainer textarea") || $(".textareawrap textarea") || $(".editContainer textarea");
if (!ta) return false;
ta.focus && ta.focus();
ta.value = text;
ta.dispatchEvent(new Event("input", { bubbles: true }));
ta.dispatchEvent(new Event("change", { bubbles: true }));
ta.dispatchEvent(new Event("keyup", { bubbles: true }));
ta.scrollIntoView && ta.scrollIntoView({ block: "center" });
return ta.value.length > 0;
};
const submitReply = () => {
const add = pickVisible(".addReply") || $(".addReply");
if (add) {
add.click();
return true;
}
// 兜底:文本为"回复"且不是 .replyBtn 的元素
const cand = $$("div,a,span,button").filter((n) => vis(n) && /^回复$/.test(String(n.textContent || "").trim()) && !/replyBtn|cancleReply/.test(n.className || ""));
if (cand[0]) {
cand[0].click();
return true;
}
return false;
};
const countReplies = () => $$(".topicDetail_replyItem").length;
window.__mfBbsDebug = function () {
const info = {
url: location.href,
topic: getTopic().slice(0, 80),
replyItems: countReplies(),
collectedReplies: getReplies().length,
replyBtn: !!pickVisible(".replyBtn"),
textarea: !!($(".textareawrap textarea") || $(".editContainer textarea")),
textareaVisible: !!pickVisible(".textareawrap textarea"),
addReply: !!$(".addReply"),
addReplyVisible: !!pickVisible(".addReply"),
buttons: $$(".addReply,.replyBtn,.cancleReplyBtn").map((n) => ({ cls: n.className, text: String(n.textContent || "").trim() }))
};
console.groupCollapsed("%c[讨论页诊断] 点击展开", "color:#409eff;font-weight:bold");
Object.keys(info).forEach((k) => console.log(k + ":", info[k]));
console.groupEnd();
return info;
};
const run = async (manual) => {
const doneKey = "mfBbsDone:" + location.pathname;
if (!manual && sessionStorage.getItem(doneKey)) {
console.log("[讨论页] 本页已处理过,跳过自动作答(可点右下角按钮手动再来一次)");
return false;
}
const cxm = new Cx();
const topic = getTopic();
if (!topic) {
cxm.askStore.log("讨论页未取到题目,可点右下角按钮重试", "error");
window.__mfBbsDebug();
return false;
}
cxm.askStore.log("讨论题目: " + topic.replace(/\s+/g, " ").slice(0, 50), "info");
const replies = getReplies();
if (replies.length) cxm.askStore.log(`参考了 ${replies.length} 条他人回复`, "success");
const text = await new ServerApi(window).getAnswerForDiscussion(topic, replies, {
course: getCourseName(),
chapter: getCatalogChapter()
});
if (!text) {
cxm.askStore.log("AI未生成内容(请确认已启用AI并填写密钥)", "error");
return false;
}
cxm.askStore.log("生成回复: " + text.slice(0, 60) + (text.length > 60 ? "…" : ""), "success");
// 打开发言框 → 填入
let filled = fillReply(text);
if (!filled) {
openEditor();
await sleep(1.2);
filled = fillReply(text);
}
if (!filled) {
openEditor();
await sleep(1.8);
filled = fillReply(text);
}
if (!filled) {
cxm.askStore.log("未找到回复输入框,已导出诊断信息", "error");
window.__mfBbsDebug();
return false;
}
cxm.askStore.log("回复内容已填入", "success");
await PauseCtl.wait();
await sleep(1);
const before = countReplies();
if (!submitReply()) {
cxm.askStore.log("未找到提交按钮,内容已填好请手动提交", "error");
window.__mfBbsDebug();
return false;
}
await sleep(1.5);
// 匿名确认弹窗:选「取消」,因为匿名不计成绩
const anon = $(".popAnonymousShowHide");
if (anon && vis(anon)) {
const cancel = anon.querySelector(".cancle, .btn_92_cancel");
cancel && cancel.click();
cxm.askStore.log("已取消匿名,按实名提交", "warning");
await sleep(0.8);
}
await sleep(2);
const after = countReplies();
const okToast = /添加成功|回复成功/.test(document.body.innerText || "");
if (after > before || okToast) {
sessionStorage.setItem(doneKey, "1");
cxm.askStore.log(`讨论回复已提交(回复数 ${before} → ${after})`, "success");
return true;
}
cxm.askStore.log("提交后未检测到新回复,请在页面上确认是否成功", "warning");
window.__mfBbsDebug();
return false;
};
if (formStore.forminput.autoDiscuss !== false) {
await run(false);
} else {
console.log("[讨论页] 自动讨论已关闭,仅提供手动按钮");
}
// 手动按钮
const btn = document.createElement("button");
btn.textContent = "🤖 AI回答此讨论";
btn.style.cssText = "position:fixed;right:16px;bottom:96px;z-index:2147483646;border:1px solid #a0cfff;background:#ecf5ff;color:#409eff;border-radius:16px;padding:6px 14px;font:13px -apple-system,'Microsoft YaHei',sans-serif;cursor:pointer;box-shadow:0 2px 8px rgba(64,158,255,.2)";
btn.addEventListener("click", async () => {
if (btn.disabled) return;
btn.disabled = true;
btn.textContent = "生成中…";
try {
await run(true);
} finally {
btn.disabled = false;
btn.textContent = "🤖 AI回答此讨论";
}
});
document.body.appendChild(btn);
} catch (e) {
console.log("[讨论页] 处理失败:", e);
}
})();
// ===== 考试页 DOM 自动识别兜底(未枚举的考试路由也能跑)=====
(async () => {
try {
const path = _self.location.pathname;
const handled = ["/work/doHomeWorkNew", "/mooc-ans/work/doHomeWorkNew", "/mooc2-ans/work/doHomeWorkNew", "/mycourse/studentstudy", "/mooc-ans/mycourse/studentstudy", "/mooc2-ans/mycourse/studentstudy", "/mooc2-ans/mycourse/stu", "/mooc-ans/mycourse/stu", "/mycourse/stu", "/work/selectWorkQuestionYiPiYue", "/knowledge/cards", "/mooc2/work/dowork", "/mooc-ans/mooc2/work/dowork", "/mooc2-ans/mooc2/work/dowork", "/exam-ans/exam/test/reVersionTestStartNew", "/mooc-ans/exam/test/reVersionTestStartNew", "/mooc2-ans/exam/test/reVersionTestStartNew", "/exam-ans/exam/test/testStartNew", "/mooc-ans/exam/test/testStartNew"];
if (handled.includes(path))
return;
let tries = 0;
while (tries++ < 10) {
if (document.querySelector(".mark_name") && (document.querySelector("input[name^=answertype]") || document.querySelectorAll("input[name^=type]").length > 1))
break;
await sleep(1);
}
const isExamPage = document.querySelector(".mark_name") && (document.querySelector("input[name^=answertype]") || document.querySelectorAll("input[name^=type]").length > 1);
if (!isExamPage)
return;
console.log("[考试自动识别] 检测到考试作答页:", path);
const cxModelExam = new Cx();
cxModelExam.askStore.log("自动识别到考试页面,开始处理", "success");
if (formStore.forminput.examEnabled === false) {
cxModelExam.askStore.log("考试自动答题已在配置中关闭,跳过", "warning");
return;
}
await cxModelExam.exam();
} catch (e) {
console.log("[考试自动识别] 处理失败:", e);
}
})();
})(Vue, Pinia, ElementPlus, md5, $);
// ==================== 微信扫码验证弹窗检测功能 ====================
(function() {
'use strict';
// 配置
const CONFIG = {
// 检测的关键词
keywords: ['微信扫码验证', '请使用微信"扫一扫"扫码', '跳转小程序进行学习验证'],
// 检测间隔(毫秒)
checkInterval: 1000,
// 延迟执行时间范围(秒)
minDelay: 5,
maxDelay: 10
};
let isProcessing = false;
let checkTimer = null;
// 生成随机延迟时间(5-10秒)
function getRandomDelay() {
return Math.floor(Math.random() * (CONFIG.maxDelay - CONFIG.minDelay + 1) + CONFIG.minDelay) * 1000;
}
// 检查元素是否包含关键词
function containsKeywords(element) {
if (!element) return false;
const text = element.textContent || element.innerText || '';
return CONFIG.keywords.some(keyword => text.includes(keyword));
}
// 检查页面中是否存在微信扫码验证弹窗
function checkWechatVerifyPopup() {
if (isProcessing) return false;
// 常见的弹窗选择器
const popupSelectors = [
'.el-dialog',
'.el-message-box',
'.van-dialog',
'.weui-dialog',
'.layui-layer',
'.modal',
'.dialog',
'.popup',
'[class*="dialog"]',
'[class*="popup"]',
'[class*="modal"]',
// 学习通特定的弹窗类名
'.verify-dialog',
'.qrcode-dialog',
'.scan-dialog'
];
// 检查所有可能的弹窗元素
for (const selector of popupSelectors) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (containsKeywords(element)) {
return true;
}
}
}
// 检查整个页面文本(作为备用方案)
const bodyText = document.body.innerText || '';
if (CONFIG.keywords.every(keyword => bodyText.includes(keyword))) {
return true;
}
return false;
}
// 执行刷新操作
function executeRefresh() {
if (isProcessing) return;
isProcessing = true;
console.log('[微信扫码检测] 检测到微信扫码验证弹窗,准备刷新页面...');
// 获取当前网址
const currentUrl = window.location.href;
// 复制网址到剪贴板
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(currentUrl).then(() => {
console.log('[微信扫码检测] 网址已复制到剪贴板:', currentUrl);
}).catch(err => {
console.error('[微信扫码检测] 复制网址失败:', err);
// 备用方案:使用传统方法
const textarea = document.createElement('textarea');
textarea.value = currentUrl;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
console.log('[微信扫码检测] 网址已复制到剪贴板(备用方法)');
});
}
// 在新标签页打开当前页面
window.open(currentUrl, '_blank');
// 关闭当前页面
setTimeout(() => {
window.close();
}, 500);
}
// 主检测函数
function startDetection() {
console.log('[微信扫码检测] 检测功能已启动,将在检测到微信扫码验证弹窗后自动处理');
checkTimer = setInterval(() => {
if (checkWechatVerifyPopup()) {
console.log('[微信扫码检测] 检测到微信扫码验证弹窗!');
clearInterval(checkTimer);
// 生成随机延迟(5-10秒)
const delay = getRandomDelay();
console.log(`[微信扫码检测] 将在 ${delay / 1000} 秒后执行刷新操作`);
setTimeout(() => {
executeRefresh();
}, delay);
}
}, CONFIG.checkInterval);
}
// 页面加载完成后启动检测
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startDetection);
} else {
startDetection();
}
// 监听页面变化(用于检测动态加载的弹窗)
const observer = new MutationObserver((mutations) => {
if (!isProcessing && checkWechatVerifyPopup()) {
console.log('[微信扫码检测] 通过MutationObserver检测到微信扫码验证弹窗!');
clearInterval(checkTimer);
const delay = getRandomDelay();
console.log(`[微信扫码检测] 将在 ${delay / 1000} 秒后执行刷新操作`);
setTimeout(() => {
executeRefresh();
}, delay);
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
})();
// ==================== 接口日志可视化面板 ====================
(function () {
'use strict';
// 只在顶层窗口注入一次:脚本会在每个子 iframe 各执行一遍,若都注入会叠加多份面板导致无法收起
if (window.top !== window.self) return;
var doc = window.document;
if (!doc || !doc.head) return;
var api = window.__mfAPILog;
if (!api) return;
// 幂等:清掉历史残留(脚本热重载/多次注入时)
['mf-apilog', 'mf-apilog-btn'].forEach(function (id) {
var old = doc.getElementById(id);
old && old.parentNode && old.parentNode.removeChild(old);
});
var CSS = [
'#mf-apilog{position:fixed;left:10px;bottom:120px;width:430px;max-height:52vh;z-index:2147483646;background:#fff;border:1px solid #dcdfe6;border-radius:8px;box-shadow:0 6px 24px rgba(0,0,0,.12);font:12px/1.5 -apple-system,"Microsoft YaHei",sans-serif;color:#303133;display:none;flex-direction:column;overflow:hidden}',
'#mf-apilog.mf-open{display:flex}',
'#mf-apilog .mf-hd{display:flex;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid #ebeef5;background:#fafafa;cursor:default;flex-shrink:0}',
'#mf-apilog .mf-hd b{font-size:13px}',
'#mf-apilog .mf-hd .mf-sp{flex:1}',
'#mf-apilog button{border:1px solid #dcdfe6;background:#fff;border-radius:4px;padding:2px 8px;font-size:12px;cursor:pointer;color:#606266}',
'#mf-apilog button:hover{border-color:#409eff;color:#409eff}',
'#mf-apilog .mf-stat{padding:6px 10px;background:#f5f7fa;color:#909399;flex-shrink:0;display:flex;gap:12px;flex-wrap:wrap}',
'#mf-apilog .mf-stat em{font-style:normal;color:#409eff;font-weight:600}',
'#mf-apilog .mf-body{overflow:auto;flex:1;min-height:80px}',
'#mf-apilog table{width:100%;border-collapse:collapse}',
'#mf-apilog th{position:sticky;top:0;background:#f5f7fa;font-weight:600;color:#909399;text-align:left;padding:5px 8px;border-bottom:1px solid #ebeef5;font-size:11px}',
'#mf-apilog td{padding:4px 8px;border-bottom:1px solid #f2f6fc;vertical-align:top}',
'#mf-apilog tr.mf-ok td{color:#303133}',
'#mf-apilog tr.mf-err td{color:#c0392b}',
'#mf-apilog tr.mf-hit{background:#f0f9eb}',
'#mf-apilog .mf-tag{display:inline-block;padding:0 5px;border-radius:3px;font-size:11px}',
'#mf-apilog .mf-tag.ok{background:#e1f3d8;color:#529b2e}',
'#mf-apilog .mf-tag.err{background:#fde2e2;color:#c45656}',
'#mf-apilog .mf-tag.wait{background:#fdf6ec;color:#b88230}',
'#mf-apilog .mf-pv{color:#909399;display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'#mf-apilog-btn{position:fixed;left:10px;bottom:88px;z-index:2147483646;border:1px solid #c6e2ff;background:#ecf5ff;color:#409eff;border-radius:16px;padding:5px 12px;font:12px -apple-system,"Microsoft YaHei",sans-serif;cursor:pointer;box-shadow:0 2px 8px rgba(64,158,255,.18)}',
'#mf-apilog-btn:hover{background:#d9ecff}'
].join('\n');
var style = doc.createElement('style');
style.textContent = CSS;
doc.head.appendChild(style);
var btn = doc.createElement('button');
btn.id = 'mf-apilog-btn';
btn.textContent = '📡 接口日志';
var panel = doc.createElement('div');
panel.id = 'mf-apilog';
panel.innerHTML = '📡 接口 / AI 请求日志' +
'
' +
'';
doc.body.appendChild(btn);
doc.body.appendChild(panel);
var paused = false;
var tbody = panel.querySelector('tbody');
var statBox = panel.querySelector('.mf-stat');
function fmtTime(t) {
var d = new Date(t);
return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
}
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) {
return ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c];
});
}
function render() {
if (paused) return;
var items = api.items.slice(-80).reverse();
var html = '';
for (var i = 0; i < items.length; i++) {
var it = items[i];
var st = it.state === 'ok' ? '200' : it.state === 'pending' ? '···' : '' + esc(it.status || 'ERR') + '';
var cls = (it.state === 'ok' ? 'mf-ok' : it.state === 'pending' ? '' : 'mf-err') + (it.hit ? ' mf-hit' : '');
html += '| ' + fmtTime(it.t) + ' | ' + esc(it.provider) + ' | ' + (it.ms || 0) + 'ms | ' + st + ' | ' +
'' + (it.hit ? '✅ ' : '') + '' + esc(it.preview || it.note || '') + ' |
';
}
tbody.innerHTML = html || '| 暂无请求,答题后这里会实时显示各渠道的发送与返回 |
';
var s = api.summary();
statBox.innerHTML = '总请求 ' + s.total + ' · 成功 ' + s.ok + ' · 命中 ' + s.hit + ' · 平均耗时 ' + s.avg + 'ms';
}
function setOpen(open) {
panel.classList.toggle('mf-open', !!open);
btn.textContent = open ? '📡 收起日志' : '📡 接口日志';
open && render();
}
btn.addEventListener('click', function (e) {
e.stopPropagation();
setOpen(!panel.classList.contains('mf-open'));
});
panel.addEventListener('click', function (e) {
var act = e.target && e.target.getAttribute && e.target.getAttribute('data-act');
if (!act) return;
e.stopPropagation();
if (act === 'clear') {
api.clear();
render();
} else if (act === 'close') {
setOpen(false);
} else if (act === 'pause') {
paused = !paused;
e.target.textContent = paused ? '继续刷新' : '暂停刷新';
paused || render();
}
});
// ESC 也能收起,避免被页面其它浮层挡住按钮时关不掉
doc.addEventListener('keydown', function (e) {
"Escape" === e.key && panel.classList.contains('mf-open') && setOpen(false);
}, true);
api.onChange(function () {
panel.classList.contains('mf-open') && render();
});
setInterval(function () {
panel.classList.contains('mf-open') && render();
}, 1500);
})();
// ==================== 暂停 / 继续按钮 ====================
(function () {
'use strict';
if (window.top !== window.self) return;
var doc = window.document;
if (!doc || !doc.head) return;
var ctl = window.__mfPause;
if (!ctl) return;
var old = doc.getElementById('mf-pause-btn');
old && old.parentNode && old.parentNode.removeChild(old);
var style = doc.createElement('style');
style.textContent = [
'#mf-pause-btn{position:fixed;left:10px;bottom:52px;z-index:2147483646;border:1px solid #a0cfff;background:#ecf5ff;color:#409eff;border-radius:16px;padding:5px 12px;font:12px -apple-system,"Microsoft YaHei",sans-serif;cursor:pointer;box-shadow:0 2px 8px rgba(64,158,255,.18);transition:all .15s}',
'#mf-pause-btn:hover{background:#d9ecff}',
'#mf-pause-btn.mf-paused{background:#fef0f0;border-color:#fab6b6;color:#f56c6c;box-shadow:0 2px 10px rgba(245,108,108,.28)}',
'#mf-pause-mask{position:fixed;left:0;right:0;top:0;height:3px;z-index:2147483647;background:repeating-linear-gradient(90deg,#f56c6c 0 10px,#fbc4c4 10px 20px);display:none}',
'#mf-pause-mask.mf-on{display:block}'
].join('\n');
doc.head.appendChild(style);
var btn = doc.createElement('button');
btn.id = 'mf-pause-btn';
btn.type = 'button';
var mask = doc.createElement('div');
mask.id = 'mf-pause-mask';
doc.body.appendChild(btn);
doc.body.appendChild(mask);
function sync() {
btn.textContent = ctl.paused ? '▶ 继续答题' : '⏸ 暂停答题';
btn.classList.toggle('mf-paused', ctl.paused);
mask.classList.toggle('mf-on', ctl.paused);
btn.title = ctl.paused ? '当前已暂停:不会继续点题/交卷' : '点击暂停自动答题(可随时继续)';
}
btn.addEventListener('click', function (e) {
e.stopPropagation();
ctl.toggle();
sync();
});
// 快捷键:Alt+P
doc.addEventListener('keydown', function (e) {
if (e.altKey && (e.key === 'p' || e.key === 'P')) {
e.preventDefault();
ctl.toggle();
sync();
}
}, true);
ctl.onChange(sync);
sync();
})();
// ==================== 弹窗右下角拖拽调整大小 ====================
(function () {
'use strict';
// 只在顶层窗口注入:子 iframe 重复注入会产生多个 observer 与样式,拖拽行为错乱
if (window.top !== window.self) return;
var doc = window.document;
if (!doc || !doc.head) return;
var KEY = 'dialogSize';
var MIN_W = 320;
var MIN_H = 200;
var saved = null;
try {
if (typeof GM_getValue === 'function') saved = GM_getValue(KEY);
} catch (e) {
}
if (saved && typeof saved === 'string') {
try {
saved = JSON.parse(saved);
} catch (e) {
saved = null;
}
}
if (saved && !(saved.w > 0)) saved = null;
var style = doc.createElement('style');
style.textContent = [
'.cs-resize-handle{position:absolute;right:0;bottom:0;width:18px;height:18px;cursor:nwse-resize;z-index:2147483647;background:transparent;}',
'.cs-resize-handle::after{content:"";position:absolute;right:3px;bottom:3px;width:10px;height:10px;border-right:2px solid #c0c4cc;border-bottom:2px solid #c0c4cc;border-radius:0 0 2px 0;opacity:.7;}',
'.cs-resize-handle:hover::after{border-color:#409eff;opacity:1;}',
'.el-dialog.cs-resized{overflow:auto!important;}'
].join('\n');
doc.head.appendChild(style);
function applySize(dialog) {
if (!saved || !saved.w) return;
dialog.style.width = saved.w + 'px';
if (saved.h) dialog.style.height = saved.h + 'px';
dialog.classList.add('cs-resized');
}
function persist() {
try {
if (typeof GM_setValue === 'function') GM_setValue(KEY, saved ? JSON.stringify(saved) : '');
} catch (e) {
}
}
function startResize(ev, dialog) {
ev.preventDefault();
ev.stopPropagation();
var rect = dialog.getBoundingClientRect();
var startX = ev.clientX;
var startY = ev.clientY;
var startW = rect.width;
var startH = rect.height;
function move(e2) {
var w = Math.max(MIN_W, Math.round(startW + e2.clientX - startX));
var h = Math.max(MIN_H, Math.round(startH + e2.clientY - startY));
dialog.style.width = w + 'px';
dialog.style.height = h + 'px';
dialog.style.maxHeight = 'none';
dialog.classList.add('cs-resized');
}
function up() {
doc.removeEventListener('mousemove', move, true);
doc.removeEventListener('mouseup', up, true);
var r = dialog.getBoundingClientRect();
saved = { w: Math.round(r.width), h: Math.round(r.height) };
persist();
}
doc.addEventListener('mousemove', move, true);
doc.addEventListener('mouseup', up, true);
}
function inject(dialog) {
if (!dialog || dialog.querySelector(':scope > .cs-resize-handle')) return;
if (!dialog.style.position) dialog.style.position = 'relative';
var handle = doc.createElement('div');
handle.className = 'cs-resize-handle';
handle.title = '拖拽调整窗口大小(双击恢复默认)';
handle.addEventListener('mousedown', function (e) {
startResize(e, dialog);
});
handle.addEventListener('dblclick', function (e) {
e.stopPropagation();
e.preventDefault();
dialog.style.width = '';
dialog.style.height = '';
dialog.style.maxHeight = '';
dialog.classList.remove('cs-resized');
saved = null;
persist();
});
dialog.appendChild(handle);
applySize(dialog);
}
function scan() {
var list = doc.querySelectorAll('.el-dialog');
for (var i = 0; i < list.length; i++) inject(list[i]);
}
try {
var mo = new MutationObserver(function () {
scan();
});
mo.observe(doc.body, { childList: true, subtree: true });
} catch (e) {
}
if ('loading' === doc.readyState) doc.addEventListener('DOMContentLoaded', scan);
else scan();
setInterval(scan, 2000);
})();