// ==UserScript==
// @name 学习通作业/考试/任务列表(优化版)
// @namespace https://github.com/Cooanyh
// @version 2.6.0
// @author 甜檸Cirtron (lcandy2); Modified by Coren
// @description 【优化版】支持作业、考试与课程任务快速查看;提供深浅色主题、KPI概览、全局搜索、作业直达答题页、考试自动整卷预览、轻量/定时同步与配置导入导出。
// @license AGPL-3.0-or-later
// @copyright lcandy2 All Rights Reserved
// @copyright 2025, Coren (Modified based on original work)
// @icon https://www.google.com/s2/favicons?sz=64&domain=chaoxing.com
// @source https://github.com/Cooanyh/chaoxing-list
// @match *://i.chaoxing.com/*
// @match *://i.mooc.chaoxing.com/space/index*
// @match *://i.mooc.chaoxing.com/settings*
// @match *://mooc2-ans.chaoxing.com/*
// @match *://mooc1-api.chaoxing.com/work/stu-work*
// @match *://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode*
// @match *://mooc1.chaoxing.com/exam-ans/exam/test/examcode/examlist*
// @match *://mooc1.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew*
// @match *://mooc2-ans.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew*
// @match *://mooc1-api.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew*
// @match *://mobilelearn.chaoxing.com/widget/pcpick/stu/index*
// @require https://cdn.jsdelivr.net/npm/vue@3.4.27/dist/vue.global.prod.js
// @require data:application/javascript,%3Bwindow.Vue%3DVue%3B
// @require https://cdn.jsdelivr.net/npm/vuetify@3.6.6/dist/vuetify.min.js
// @require data:application/javascript,%3B
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant unsafeWindow
// @connect cdn.jsdelivr.net
// @connect fonts.googlefonts.cn
// @connect mooc1-api.chaoxing.com
// @connect mobilelearn.chaoxing.com
// @connect stat2-ans.chaoxing.com
// @connect mooc2-ans.chaoxing.com
// @connect mooc1.chaoxing.com
// @connect i.chaoxing.com
// @connect task.chaoxing.com
// @run-at document-end
// ==/UserScript==
(function (vuetify, vue) {
'use strict';
// --- 开源内联 SVG 图标(Lucide 风格,MIT/ISC 几何路径,零外链依赖) ---
const CX_ICON_PATHS = Object.freeze({
barChart: '',
settings: '',
sun: '',
moon: '',
contrast: '',
zap: '',
refreshCw: '',
search: '',
ban: '',
xCircle: '',
x: '',
check: '',
checkCircle: '',
clock: '',
bell: '',
sparkles: '',
bookOpen: '',
fileText: '',
clipboardList: '',
book: '',
messageSquare: '',
alertTriangle: '',
shield: '',
upload: '',
download: '',
user: ''
});
const cxSvgHtml = (name, size = 15) => {
const body = CX_ICON_PATHS[name] || CX_ICON_PATHS.sparkles;
return ``;
};
const cxIcon = (name, size = 15, extraClass = '') => vue.createVNode('span', {
class: extraClass ? `cx-icon ${extraClass}` : 'cx-icon',
'aria-hidden': 'true',
innerHTML: cxSvgHtml(name, size)
});
// --- 核心工具函数 ---
const wrapElements = () => {
const wrapper = document.createElement("body");
wrapper.id = "chaoxing-assignment-wrapper";
while (document.body.firstChild) {
wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
wrapper.style.display = "none";
};
const ensureResponsiveViewport = () => {
if (!document.head) return;
let viewport = Array.from(document.head.querySelectorAll('meta[name]'))
.find(meta => meta.getAttribute('name')?.trim().toLowerCase() === 'viewport');
if (!viewport) {
viewport = document.createElement('meta');
viewport.setAttribute('name', 'viewport');
document.head.appendChild(viewport);
}
const directives = (viewport.getAttribute('content') || '')
.split(',')
.map(directive => directive.trim())
.filter(Boolean);
const widthIndex = directives.findIndex(directive => /^width\s*=/i.test(directive));
if (widthIndex >= 0) directives[widthIndex] = 'width=device-width';
else directives.unshift('width=device-width');
if (!directives.some(directive => /^initial-scale\s*=/i.test(directive))) {
directives.push('initial-scale=1');
}
viewport.setAttribute('content', directives.join(', '));
};
const removeStyles = () => {
removeHtmlStyle();
const styles = document.querySelectorAll("link[rel=stylesheet]");
styles.forEach((style) => {
var _a;
if ((_a = style.getAttribute("href")) == null ? void 0 : _a.includes("chaoxing")) {
style.remove();
}
});
};
const removeHtmlStyle = () => {
const html = document.querySelector("html");
html == null ? void 0 : html.removeAttribute("style");
};
const keepRemoveHtmlStyle = () => {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "attributes" && mutation.attributeName === "style") {
removeHtmlStyle();
}
});
});
const html = document.querySelector("html");
html && observer.observe(html, { attributes: true });
};
const removeScripts = () => {
const scripts = document.querySelectorAll("script");
scripts.forEach((script) => {
var _a;
if ((_a = script.getAttribute("src")) == null ? void 0 : _a.includes("chaoxing")) {
script.remove();
}
});
};
// --- 课程进度查询开关管理 ---
const PROGRESS_ENABLED_KEY = 'chaoxing_progress_enabled';
const PROGRESS_DELAY_KEY = 'chaoxing_progress_delay';
const DEFAULT_PROGRESS_DELAY = 500;
const MIN_PROGRESS_DELAY = 300;
const MAX_PROGRESS_DELAY = 10000;
const isProgressEnabled = () => {
try {
const stored = localStorage.getItem(PROGRESS_ENABLED_KEY);
return stored === null ? true : stored === 'true';
} catch { return true; }
};
const setProgressEnabled = (enabled) => {
try {
localStorage.setItem(PROGRESS_ENABLED_KEY, String(enabled));
console.log('[课程进度] 查询功能已', enabled ? '开启' : '关闭');
} catch (e) {
console.error('[课程进度] 保存开关状态失败:', e);
}
};
const normalizeProgressDelay = (value) => {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) return DEFAULT_PROGRESS_DELAY;
return Math.min(MAX_PROGRESS_DELAY, Math.max(MIN_PROGRESS_DELAY, parsed));
};
const getProgressDelay = () => {
try {
const stored = localStorage.getItem(PROGRESS_DELAY_KEY);
return stored === null ? DEFAULT_PROGRESS_DELAY : normalizeProgressDelay(stored);
} catch { return DEFAULT_PROGRESS_DELAY; }
};
const setProgressDelay = (delay) => {
const normalizedDelay = normalizeProgressDelay(delay);
try {
localStorage.setItem(PROGRESS_DELAY_KEY, String(normalizedDelay));
console.log('[课程进度] 请求延迟已设置为', normalizedDelay, 'ms');
} catch (e) {
console.error('[课程进度] 保存延迟设置失败:', e);
}
return normalizedDelay;
};
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const getCourseCompletionRate = (item) => {
const rate = Number.parseFloat(String(item?.completionRate ?? '').replace('%', ''));
return Number.isFinite(rate) ? rate : null;
};
const hasCourseProgressTaskCount = item => item?.totalTasks !== null && item?.totalTasks !== undefined && item?.totalTasks !== '';
const compareEmptyProgressLast = (a, b) => {
const emptyA = hasCourseProgressTaskCount(a) && Number(a.totalTasks) === 0;
const emptyB = hasCourseProgressTaskCount(b) && Number(b.totalTasks) === 0;
if (emptyA === emptyB) return 0;
return emptyA ? 1 : -1;
};
const compareCourseProgress = (a, b, direction = 1) => {
const emptyOrder = compareEmptyProgressLast(a, b);
if (emptyOrder) return emptyOrder;
const rateA = getCourseCompletionRate(a);
const rateB = getCourseCompletionRate(b);
if (rateA === null && rateB !== null) return 1;
if (rateA !== null && rateB === null) return -1;
if (rateA !== null && rateB !== null && rateA !== rateB) return (rateA - rateB) * direction;
return (a.courseName || '').localeCompare(b.courseName || '', 'zh-CN');
};
const compareCourseProgressByName = (a, b) => compareEmptyProgressLast(a, b)
|| (a.courseName || '').localeCompare(b.courseName || '', 'zh-CN');
// --- 忽略管理 - 使用 localStorage 持久化 ---
const IGNORE_STORAGE_KEY = 'chaoxing_ignored_items';
const SETTINGS_STORAGE_KEY = 'chaoxing_list_settings_v1';
const DASHBOARD_CACHE_STORAGE_KEY = 'chaoxing_list_dashboard_cache_v1';
const DEADLINE_REMINDER_STORAGE_KEY = 'chaoxing_list_deadline_reminders_v1';
const SCHEDULED_SYNC_LOG_KEY = 'chaoxing_list_scheduled_sync_log_v1';
const DASHBOARD_CACHE_TTL = 5 * 60 * 1000;
const LIGHT_REFRESH_MIN_INTERVAL = 2 * 60 * 1000;
const DEADLINE_REMINDER_CHECK_INTERVAL = 30 * 1000;
const DEADLINE_REMINDER_THRESHOLDS = Object.freeze([
{ key: '12h', label: '12 小时', milliseconds: 12 * 60 * 60 * 1000 },
{ key: '6h', label: '6 小时', milliseconds: 6 * 60 * 60 * 1000 },
{ key: '3h', label: '3 小时', milliseconds: 3 * 60 * 60 * 1000 },
{ key: '30m', label: '30 分钟', milliseconds: 30 * 60 * 1000 }
]);
const COURSE_IGNORE_PREFIX = 'course__';
const PRESET_SYNC_TIMES = Object.freeze(['07:00', '08:00', '12:00', '18:00', '21:00', '22:00']);
const DEFAULT_SETTINGS = Object.freeze({
ignoreEnabled: false,
showOtherTasks: false,
otherTaskTypes: [],
deadlineReminderEnabled: true,
deadlineBrowserNotificationEnabled: false,
shortTermCacheEnabled: true,
dynamicIgnoreRules: { homework: false, exam: false, activities: false, progress: false },
settingsHintSeen: false,
courseIgnoreHintSeen: false,
themeMode: 'system',
tabBadgeCountMode: 'pending',
defaultTaskFilter: 'pending',
zeroTaskSuggestSeen: false,
onboardingTourSeen: false,
directHomeworkJumpEnabled: true,
examAutoFullPreviewEnabled: true,
lightRefreshEnabled: true,
scheduledSyncEnabled: true,
scheduledSyncTimes: ['08:00', '12:00', '18:00', '21:00']
});
const CORE_TASK_TYPES = new Set(['作业', '视频/任务点', 'AI实践', '任务引擎', '分组讨论', '分组任务', '测验', '随堂练习', '考试']);
const OTHER_TASK_TYPES = ['签到', '问卷', '抢答', '通知', '投票', '直播', '评分', '拍照', '笔记', '其他任务'];
const getSettings = () => {
try {
const parsed = JSON.parse(localStorage.getItem(SETTINGS_STORAGE_KEY) || '{}');
return {
...DEFAULT_SETTINGS,
...parsed,
scheduledSyncTimes: Array.isArray(parsed?.scheduledSyncTimes) && parsed.scheduledSyncTimes.length
? parsed.scheduledSyncTimes
: [...DEFAULT_SETTINGS.scheduledSyncTimes]
};
} catch {
return { ...DEFAULT_SETTINGS, scheduledSyncTimes: [...DEFAULT_SETTINGS.scheduledSyncTimes] };
}
};
const EXAM_AUTO_PREVIEW_GM_KEY = 'chaoxing_list_exam_auto_preview_v1';
const syncExamAutoPreviewPreference = (enabled) => {
try {
if (typeof GM_setValue === 'function') {
GM_setValue(EXAM_AUTO_PREVIEW_GM_KEY, Boolean(enabled));
}
} catch {}
};
const isExamAutoFullPreviewEnabled = () => {
try {
if (typeof GM_getValue === 'function') {
const stored = GM_getValue(EXAM_AUTO_PREVIEW_GM_KEY, null);
if (typeof stored === 'boolean') return stored;
}
} catch {}
return Boolean(getSettings().examAutoFullPreviewEnabled);
};
const saveSettings = (settings) => {
const merged = { ...DEFAULT_SETTINGS, ...settings };
localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(merged));
syncExamAutoPreviewPreference(merged.examAutoFullPreviewEnabled);
};
let vuetifyInstance = null;
const HOST_THEME_STORAGE_KEY = 'chaoxing_list_host_theme_v1';
const resolveThemeMode = (mode = getSettings().themeMode) => {
if (mode === 'dark' || mode === 'light') return mode;
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
const extractThemeOrigin = (originEvent) => {
if (!originEvent) return null;
try {
const rect = originEvent.currentTarget?.getBoundingClientRect?.();
if (rect && (rect.width > 0 || rect.height > 0)) {
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
}
if (typeof originEvent.clientX === 'number' && typeof originEvent.clientY === 'number' && (originEvent.clientX > 0 || originEvent.clientY > 0)) {
return { x: originEvent.clientX, y: originEvent.clientY };
}
} catch {}
return null;
};
const runCircularThemeTransition = (origin, commitFn, prevTheme = 'light') => {
const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
if (!origin || reduced || !document.body) {
commitFn();
return;
}
try {
const rootEl = document.querySelector?.('.chaoxing-list-root');
if (!rootEl || typeof rootEl.animate !== 'function') {
commitFn();
return;
}
if (window.__cxThemeRevealAnim) {
try { window.__cxThemeRevealAnim.cancel(); } catch {}
window.__cxThemeRevealAnim = null;
}
const prevSnap = document.getElementById('cx-theme-old-snapshot');
if (prevSnap) prevSnap.remove();
const rootRect = rootEl.getBoundingClientRect?.() || { left: 0, top: 0, width: window.innerWidth || 1280 };
const vw = window.innerWidth || document.documentElement.clientWidth || 1280;
const vh = window.innerHeight || document.documentElement.clientHeight || 800;
const scrollX = window.scrollX || 0;
const scrollY = window.scrollY || 0;
const localX = origin.x - rootRect.left;
const localY = origin.y - rootRect.top;
const endRadius = Math.hypot(Math.max(origin.x, vw - origin.x), Math.max(origin.y, vh - origin.y)) + 24;
const clone = rootEl.cloneNode(true);
clone.querySelectorAll?.('style')?.forEach?.((s) => s.remove());
const scrollSelector = '.cx-panel-body, .cx-progress-body, .card-body, .detail-body, .cx-settings-main';
const origScrolls = rootEl.querySelectorAll?.(scrollSelector) || [];
const cloneScrolls = clone.querySelectorAll?.(scrollSelector) || [];
for (let i = 0; i < origScrolls.length && i < cloneScrolls.length; i++) {
if (origScrolls[i].scrollTop) cloneScrolls[i].scrollTop = origScrolls[i].scrollTop;
}
clone.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;
clone.style.width = `${rootRect.width || vw}px`;
clone.style.margin = '0';
clone.style.pointerEvents = 'none';
const snapHost = document.createElement('div');
snapHost.id = 'cx-theme-old-snapshot';
snapHost.setAttribute('data-cx-theme', prevTheme || 'light');
snapHost.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none;overflow:hidden;background:var(--cx-bg);color:var(--cx-text);';
snapHost.appendChild(clone);
document.body.appendChild(snapHost);
const savedStyles = {
position: rootEl.style.position,
zIndex: rootEl.style.zIndex,
willChange: rootEl.style.willChange,
backgroundColor: rootEl.style.backgroundColor,
clipPath: rootEl.style.clipPath
};
rootEl.style.position = 'relative';
rootEl.style.zIndex = '2';
rootEl.style.willChange = 'clip-path';
rootEl.style.backgroundColor = 'var(--cx-bg)';
commitFn();
let cleaned = false;
const cleanup = () => {
if (cleaned) return;
cleaned = true;
window.__cxThemeRevealAnim = null;
snapHost.remove();
rootEl.style.position = savedStyles.position;
rootEl.style.zIndex = savedStyles.zIndex;
rootEl.style.willChange = savedStyles.willChange;
rootEl.style.backgroundColor = savedStyles.backgroundColor;
rootEl.style.clipPath = savedStyles.clipPath;
};
const anim = rootEl.animate(
[
{ clipPath: `circle(0px at ${localX}px ${localY}px)` },
{ clipPath: `circle(${endRadius}px at ${localX}px ${localY}px)` }
],
{ duration: 460, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' }
);
window.__cxThemeRevealAnim = anim;
if (anim && typeof anim.finished?.then === 'function') {
anim.finished.then(cleanup).catch(cleanup);
}
setTimeout(cleanup, 520);
} catch {
commitFn();
}
};
const broadcastHostThemeSync = (themeMode, resolved, animate = false, origin = null) => {
try {
if (window.parent && window.parent !== window) {
window.parent.postMessage({
type: 'chaoxing-list-theme-sync',
themeMode,
resolved,
animate,
origin
}, '*');
}
} catch {}
};
const applyThemeMode = (mode = getSettings().themeMode, originEvent = null) => {
const resolved = resolveThemeMode(mode);
const prevResolved = document.documentElement.getAttribute('data-cx-theme');
const origin = extractThemeOrigin(originEvent);
const shouldAnimate = Boolean(origin && prevResolved && prevResolved !== resolved);
const commit = () => {
document.documentElement.setAttribute('data-cx-theme', resolved);
if (vuetifyInstance?.theme?.global?.name) {
vuetifyInstance.theme.global.name.value = resolved;
}
};
if (shouldAnimate) {
runCircularThemeTransition(origin, commit, prevResolved);
} else {
commit();
}
broadcastHostThemeSync(mode, resolved, shouldAnimate, origin);
return resolved;
};
const getScheduledSyncLog = () => {
try {
const parsed = JSON.parse(localStorage.getItem(SCHEDULED_SYNC_LOG_KEY) || '{}');
return parsed && typeof parsed === 'object' ? parsed : {};
} catch { return {}; }
};
const saveScheduledSyncLog = (log) => {
try { localStorage.setItem(SCHEDULED_SYNC_LOG_KEY, JSON.stringify(log)); } catch {}
};
const isScheduledSyncDueNow = (settings) => {
if (!settings?.scheduledSyncEnabled) return null;
const times = Array.isArray(settings.scheduledSyncTimes) && settings.scheduledSyncTimes.length
? [...settings.scheduledSyncTimes].sort()
: [...DEFAULT_SETTINGS.scheduledSyncTimes];
const now = new Date();
const todayKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
const nowHHmm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
const log = getScheduledSyncLog();
const triggeredToday = Array.isArray(log[todayKey]) ? log[todayKey] : [];
const dueSlots = times.filter(t => /^\d{2}:\d{2}$/.test(t) && t <= nowHHmm && !triggeredToday.includes(t));
if (!dueSlots.length) return null;
return { todayKey, dueSlots, triggeredToday };
};
const markScheduledSyncTriggered = (todayKey, dueSlots, triggeredToday) => {
const next = Array.from(new Set([...(triggeredToday || []), ...(dueSlots || [])])).sort();
saveScheduledSyncLog({ [todayKey]: next });
};
const exportScriptConfigJson = () => {
let ignoredItems = {};
try { ignoredItems = JSON.parse(localStorage.getItem(IGNORE_STORAGE_KEY) || '{}'); } catch {}
return JSON.stringify({
schema: 'chaoxing-list-config-v1',
exportedAt: new Date().toISOString(),
settings: getSettings(),
ignoredItems,
progressEnabled: isProgressEnabled(),
progressDelay: getProgressDelay()
}, null, 2);
};
const importScriptConfigJson = (rawText) => {
const parsed = JSON.parse(String(rawText || '').trim());
if (!parsed || typeof parsed !== 'object' || (!parsed.settings && !parsed.ignoredItems)) {
throw new Error('无效的配置 JSON 格式');
}
if (parsed.settings && typeof parsed.settings === 'object') {
saveSettings({ ...getSettings(), ...parsed.settings });
}
if (parsed.ignoredItems && typeof parsed.ignoredItems === 'object' && !Array.isArray(parsed.ignoredItems)) {
localStorage.setItem(IGNORE_STORAGE_KEY, JSON.stringify(parsed.ignoredItems));
}
if (typeof parsed.progressEnabled === 'boolean') setProgressEnabled(parsed.progressEnabled);
if (parsed.progressDelay !== undefined) setProgressDelay(parsed.progressDelay);
return getSettings();
};
const getDeadlineReminderState = () => {
try {
const stored = JSON.parse(localStorage.getItem(DEADLINE_REMINDER_STORAGE_KEY) || '{}');
if (!stored || typeof stored !== 'object' || !stored.tasks || typeof stored.tasks !== 'object') return { tasks: {} };
return {
...stored,
tasks: Object.fromEntries(Object.entries(stored.tasks)
.filter(([, entry]) => entry && typeof entry === 'object' && !Array.isArray(entry)))
};
} catch { return { tasks: {} }; }
};
const saveDeadlineReminderState = (state) => {
try { localStorage.setItem(DEADLINE_REMINDER_STORAGE_KEY, JSON.stringify(state)); }
catch (error) { console.warn('[临近提醒] 保存提醒状态失败:', error); }
};
const getDashboardCache = () => {
try { return JSON.parse(localStorage.getItem(DASHBOARD_CACHE_STORAGE_KEY) || '{}'); }
catch { return {}; }
};
const cleanupDashboardCache = () => {
const cache = getDashboardCache();
const now = Date.now();
Object.keys(cache).forEach(key => {
if (!cache[key] || !cache[key].savedAt || now - cache[key].savedAt > DASHBOARD_CACHE_TTL) delete cache[key];
});
try { localStorage.setItem(DASHBOARD_CACHE_STORAGE_KEY, JSON.stringify(cache)); } catch { /* localStorage 不可用时直接跳过 */ }
return cache;
};
const saveDashboardCache = (key, data) => {
const cache = cleanupDashboardCache();
cache[key] = { savedAt: Date.now(), data };
try { localStorage.setItem(DASHBOARD_CACHE_STORAGE_KEY, JSON.stringify(cache)); } catch (error) { console.warn('[短时缓存] 写入失败', error); }
};
const isOtherTask = (item) => item && item.isActivity && !CORE_TASK_TYPES.has(item.type);
const isOtherTaskVisible = (item, settings) => !isOtherTask(item) || settings.showOtherTasks || (settings.otherTaskTypes || []).includes(item.type);
// 动态忽略只接受明确的完成/过期标记,避免状态缺失或未知内容被误选。
const isExplicitlyCompletedAiPractice = (item) => item?.type === 'AI实践'
&& (item.finished === true || item.status === '已完成');
const isExplicitlyCompletedHomework = (item) => {
if (!item) return false;
if (item.type === 'AI实践') return isExplicitlyCompletedAiPractice(item);
return item.uncommitted === false || item.finished === true || item.status === '已完成';
};
const isExplicitlyClosedExam = (item) => item?.finished === true || item?.expired === true;
const isExplicitlyEndedActivity = (item) => item?.finished === true || item?.status === '已结束';
const isExplicitlyCompletedProgress = (item) => item?.isComplete === true || Number.parseInt(item?.completionRate, 10) >= 100;
const getTaskEnginePlanSection = (item) => {
if (!item?.taskEnginePlan) return 'activities';
if (item.type === '作业') return 'homework';
if (item.type === '考试') return 'exam';
return 'activities';
};
const isDynamicallyIgnored = (item, sectionType, settings) => {
const rules = settings.dynamicIgnoreRules || {};
// 待办中的任务引擎子任务按实际类目应用规则,其余课程任务沿用课程任务规则。
if (sectionType === 'todo' && item.isActivity) sectionType = getTaskEnginePlanSection(item);
switch (sectionType) {
case 'homework': return !!rules.homework && isExplicitlyCompletedHomework(item);
case 'exam': return !!rules.exam && isExplicitlyClosedExam(item);
case 'activities': return !!rules.activities && isExplicitlyEndedActivity(item);
case 'progress': return !!rules.progress && isExplicitlyCompletedProgress(item);
default: return false;
}
};
const getCourseIgnoreKey = (item) => `${COURSE_IGNORE_PREFIX}${item.courseId || ''}__${item.clazzId || item.classId || ''}`;
const isCourseIgnored = (item) => {
const courseId = item && item.courseId;
if (!courseId) return false;
return !!getIgnoredItems()[getCourseIgnoreKey(item)];
};
const ignoreCourse = (course) => {
const ignored = getIgnoredItems();
ignored[getCourseIgnoreKey(course)] = {
title: course.courseName || course.course || '未知课程',
course: course.courseName || course.course || '',
sectionType: 'course',
ignoredAt: Date.now(),
courseId: course.courseId,
clazzId: course.clazzId || course.classId
};
saveIgnoredItems(ignored);
};
const unignoreCourse = (course) => {
const ignored = getIgnoredItems();
delete ignored[getCourseIgnoreKey(course)];
saveIgnoredItems(ignored);
};
const getIgnoredItems = () => {
try {
return JSON.parse(localStorage.getItem(IGNORE_STORAGE_KEY) || '{}');
} catch { return {}; }
};
const saveIgnoredItems = (items) => {
localStorage.setItem(IGNORE_STORAGE_KEY, JSON.stringify(items));
};
// 生成唯一标识(包含板块前缀,防止不同板块同名项冲突)
const getItemKey = (item, sectionType) => {
const sec = sectionType || item._sectionType || 'unknown';
const id = item.courseId || item.examId || item.workId || item.activeId || '';
const title = item.title || item.courseName || '';
return `${sec}__${id}__${title}`;
};
const isItemIgnored = (item, sectionType) => {
const ignored = getIgnoredItems();
return isCourseIgnored(item) || !!ignored[getItemKey(item, sectionType)];
};
const ignoreItem = (item, sectionType) => {
const ignored = getIgnoredItems();
const sec = sectionType || item._sectionType || 'unknown';
ignored[getItemKey(item, sectionType)] = {
title: item.title || item.courseName || '',
type: item.type || '',
course: item.course || item.courseName || '',
sectionType: sec,
ignoredAt: Date.now()
};
saveIgnoredItems(ignored);
};
const unignoreItem = (item, sectionType) => {
const ignored = getIgnoredItems();
delete ignored[getItemKey(item, sectionType)];
saveIgnoredItems(ignored);
};
const ignoreItems = (items, sectionType) => {
const ignored = getIgnoredItems();
items.forEach(item => {
const sec = sectionType || item._sectionType || 'unknown';
ignored[getItemKey(item, sectionType)] = {
title: item.title || item.courseName || '',
type: item.type || '',
course: item.course || item.courseName || '',
sectionType: sec,
ignoredAt: Date.now()
};
});
saveIgnoredItems(ignored);
};
const unignoreItems = (items, sectionType) => {
const ignored = getIgnoredItems();
items.forEach(item => {
delete ignored[getItemKey(item, sectionType)];
});
saveIgnoredItems(ignored);
};
// 获取某板块的所有已忽略项(按 sectionType 过滤)
const getIgnoredItemsBySection = (sectionType) => {
const ignored = getIgnoredItems();
const result = [];
for (const [key, val] of Object.entries(ignored)) {
if ((val.sectionType || 'unknown') === sectionType) {
result.push({ ...val, _key: key });
}
}
return result;
};
const unignoreByKey = (key) => {
const ignored = getIgnoredItems();
delete ignored[key];
saveIgnoredItems(ignored);
};
const unignoreByKeys = (keys) => {
const ignored = getIgnoredItems();
keys.forEach(k => delete ignored[k]);
saveIgnoredItems(ignored);
};
const urlDetection = () => {
const url = window.location.href;
const hash = window.location.hash;
// 新版仪表盘检测
if (hash.includes("chaoxing-dashboard")) {
return "dashboard";
}
if (hash.includes("chaoxing-assignment-activities")) {
return "activities";
}
if (hash.includes("chaoxing-assignment-todo")) {
return "todo";
}
if (hash.includes("chaoxing-assignment")) {
if (url.includes("mooc1-api.chaoxing.com/work/stu-work")) {
return "homework";
}
if (url.includes("mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode")) {
return "exam";
}
}
if (url.includes("mooc1.chaoxing.com/exam-ans/exam/test/examcode/examlist")) {
return "exam";
}
if (url.includes("i.chaoxing.com")) {
return "home";
}
if (url.includes("i.mooc.chaoxing.com/space/index") || url.includes("i.mooc.chaoxing.com/settings")) {
return "legacyHome";
}
if (url.includes("/exam-ans/exam/test/reVersionTestStartNew")) {
return "exam_take";
}
if (url.includes("mobilelearn.chaoxing.com/widget/pcpick/stu/index") && hash.includes("active_")) {
return "pcpick_auto";
}
// 课程章节页面检测
if (url.includes("mooc2-ans.chaoxing.com/mooc2-ans/mycourse/studentcourse") ||
url.includes("mooc2-ans.chaoxing.com/mooc2-ans/mycourse/stu")) {
return "course_chapter";
}
};
const startHostDarkModeSync = () => {
if (!document.getElementById('cx-host-dark-style')) {
const hostStyle = document.createElement('style');
hostStyle.id = 'cx-host-dark-style';
hostStyle.textContent = `
html[data-cx-theme="dark"],
html[data-cx-theme="dark"] body {
color-scheme: dark !important;
background: #0b0d12 !important;
background-image: none !important;
color: #f3f4f6 !important;
}
html[data-cx-theme="dark"] .box,
html[data-cx-theme="dark"] .main,
html[data-cx-theme="dark"] .main-box,
html[data-cx-theme="dark"] .content,
html[data-cx-theme="dark"] .wrap,
html[data-cx-theme="dark"] .container,
html[data-cx-theme="dark"] .layout,
html[data-cx-theme="dark"] .page-wrap,
html[data-cx-theme="dark"] .space_main,
html[data-cx-theme="dark"] #space_main,
html[data-cx-theme="dark"] .right,
html[data-cx-theme="dark"] .right-box,
html[data-cx-theme="dark"] .frame_box,
html[data-cx-theme="dark"] .iframe-box,
html[data-cx-theme="dark"] .main-right,
html[data-cx-theme="dark"] .rightContent,
html[data-cx-theme="dark"] .right_content,
html[data-cx-theme="dark"] .wid100 {
background: #0b0d12 !important;
background-image: none !important;
color: #f3f4f6 !important;
border-color: rgba(255, 255, 255, 0.08) !important;
}
html[data-cx-theme="dark"] .header,
html[data-cx-theme="dark"] .head,
html[data-cx-theme="dark"] .top,
html[data-cx-theme="dark"] .header-wrap,
html[data-cx-theme="dark"] .top-header,
html[data-cx-theme="dark"] #header,
html[data-cx-theme="dark"] .space_top,
html[data-cx-theme="dark"] .headerBox,
html[data-cx-theme="dark"] .topbar,
html[data-cx-theme="dark"] header,
html[data-cx-theme="dark"] [data-cx-host-header="1"],
html[data-cx-theme="dark"] [data-cx-host-header="1"] > div {
background: #12151c !important;
background-color: #12151c !important;
background-image: none !important;
color: #f3f4f6 !important;
border-bottom: 1px solid rgba(255, 255, 255, 0.08) !important;
box-shadow: none !important;
}
html[data-cx-theme="dark"] .left,
html[data-cx-theme="dark"] .left-box,
html[data-cx-theme="dark"] .leftnav,
html[data-cx-theme="dark"] .left_nav,
html[data-cx-theme="dark"] .leftSide,
html[data-cx-theme="dark"] .left-side,
html[data-cx-theme="dark"] #space_left,
html[data-cx-theme="dark"] .space-left,
html[data-cx-theme="dark"] .menubar,
html[data-cx-theme="dark"] div.menubar[role="menubar"],
html[data-cx-theme="dark"] .menu-list,
html[data-cx-theme="dark"] .menu-list-box,
html[data-cx-theme="dark"] ul.menu-list-ul,
html[data-cx-theme="dark"] ul.funclistul,
html[data-cx-theme="dark"] .side-bar,
html[data-cx-theme="dark"] .sidebar,
html[data-cx-theme="dark"] .nav-left,
html[data-cx-theme="dark"] .leftMenu,
html[data-cx-theme="dark"] .left-menu,
html[data-cx-theme="dark"] .user-info,
html[data-cx-theme="dark"] .userInfo,
html[data-cx-theme="dark"] .personal-info,
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] {
background: #12151c !important;
background-color: #12151c !important;
background-image: none !important;
color: #d1d5db !important;
border-color: rgba(255, 255, 255, 0.08) !important;
box-shadow: none !important;
}
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(div, section, nav, header, footer, ul, li, a, button, p, span) {
background-color: transparent !important;
background-image: none !important;
border-color: rgba(255, 255, 255, 0.08) !important;
box-shadow: none !important;
}
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a, h1, h2, h3, h4, h5, p, span),
html[data-cx-theme="dark"] .leftnav a,
html[data-cx-theme="dark"] .left_nav a,
html[data-cx-theme="dark"] .menubar a,
html[data-cx-theme="dark"] .menu-list a,
html[data-cx-theme="dark"] ul.menu-list-ul li a,
html[data-cx-theme="dark"] ul.funclistul li a,
html[data-cx-theme="dark"] .leftnav h3,
html[data-cx-theme="dark"] .left_nav h3,
html[data-cx-theme="dark"] .menubar h5,
html[data-cx-theme="dark"] .menu-list h3,
html[data-cx-theme="dark"] .user-info *,
html[data-cx-theme="dark"] .personalName,
html[data-cx-theme="dark"] .schoolName,
html[data-cx-theme="dark"] .header a,
html[data-cx-theme="dark"] .header span {
color: #e5e7eb !important;
}
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a, li):hover,
html[data-cx-theme="dark"] .menubar a:hover,
html[data-cx-theme="dark"] .menu-list li:hover,
html[data-cx-theme="dark"] ul.menu-list-ul li a:hover,
html[data-cx-theme="dark"] ul.funclistul li a:hover {
background-color: rgba(255, 255, 255, 0.06) !important;
color: #ffffff !important;
}
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a.cur, a.active, a.on, a.selected, li.cur, li.active, li.on, li.selected, [class*="active"], [class*="selected"], [class*="cur"]),
html[data-cx-theme="dark"] .menubar a.cur,
html[data-cx-theme="dark"] .menubar a.active,
html[data-cx-theme="dark"] .menu-list li.active,
html[data-cx-theme="dark"] .menu-list li.cur,
html[data-cx-theme="dark"] ul.menu-list-ul li.cur a,
html[data-cx-theme="dark"] ul.funclistul li.cur a {
background-color: rgba(96, 165, 250, 0.16) !important;
color: #93c5fd !important;
}
html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a.cur, a.active, li.cur, li.active, [class*="active"], [class*="cur"]) :is(span, h3, h5) {
color: #93c5fd !important;
}
html[data-cx-theme="dark"] .space_opt a.manageBtn {
background: #181c26 !important;
color: #e5e7eb !important;
border: 1px solid rgba(255, 255, 255, 0.12) !important;
}
html[data-cx-theme="dark"] .dropdown-menu,
html[data-cx-theme="dark"] .user-dropdown,
html[data-cx-theme="dark"] .pop {
background: #171b24 !important;
color: #f3f4f6 !important;
border-color: rgba(255, 255, 255, 0.12) !important;
}
html[data-cx-theme="dark"] iframe {
background: #0b0d12 !important;
border-color: rgba(255, 255, 255, 0.08) !important;
}
html[data-cx-theme-switching="1"],
html[data-cx-theme-switching="1"] body,
html[data-cx-theme-switching="1"] .box,
html[data-cx-theme-switching="1"] .main,
html[data-cx-theme-switching="1"] .header,
html[data-cx-theme-switching="1"] [data-cx-host-sidebar="1"],
html[data-cx-theme-switching="1"] [data-cx-host-sidebar="1"] *,
html[data-cx-theme-switching="1"] [data-cx-host-header="1"],
html[data-cx-theme-switching="1"] [data-cx-host-header="1"] * {
transition: background-color 360ms cubic-bezier(0.22, 1, 0.36, 1), color 360ms ease, border-color 360ms ease !important;
}
html[data-cx-theme="dark"] ::-webkit-scrollbar { width: 6px; height: 6px; }
html[data-cx-theme="dark"] ::-webkit-scrollbar-track { background: transparent; }
html[data-cx-theme="dark"] ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.16); border-radius: 3px; }
html[data-cx-theme="dark"] ::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.28); }
`;
(document.head || document.documentElement).appendChild(hostStyle);
}
const tagHostLayoutNodes = () => {
try {
const anchor = document.querySelector('div.menubar[role="menubar"], ul.menu-list-ul, ul.funclistul, #first1000000, #first_chaoxing_assignment_dashboard');
if (anchor) {
let cur = anchor;
let sidebarRoot = anchor;
while (cur && cur.parentElement && cur.parentElement !== document.body && cur.parentElement !== document.documentElement) {
const p = cur.parentElement;
const rect = p.getBoundingClientRect?.();
if (rect && rect.width > 0 && rect.width < 360 && !p.querySelector?.('iframe')) {
sidebarRoot = p;
cur = p;
} else {
break;
}
}
sidebarRoot?.setAttribute?.('data-cx-host-sidebar', '1');
}
const winW = window.innerWidth || 1000;
const candidates = document.querySelectorAll('body > div, body > header, .box > div, .main > div');
for (const el of candidates) {
if (el.getAttribute('data-cx-host-header') === '1') continue;
const r = el.getBoundingClientRect?.();
if (r && r.top <= 8 && r.height >= 36 && r.height <= 96 && r.width >= winW * 0.6 && !el.querySelector?.('iframe')) {
el.setAttribute('data-cx-host-header', '1');
}
}
} catch {}
};
tagHostLayoutNodes();
setTimeout(tagHostLayoutNodes, 400);
setTimeout(tagHostLayoutNodes, 1500);
if (typeof MutationObserver === 'function' && !window.__cxHostLayoutObserver) {
let tagTimer = null;
const obs = new MutationObserver(() => {
if (tagTimer) return;
tagTimer = setTimeout(() => {
tagTimer = null;
tagHostLayoutNodes();
}, 120);
});
window.__cxHostLayoutObserver = obs;
obs.observe(document.documentElement || document, { childList: true, subtree: true });
setTimeout(() => { try { obs.disconnect(); } catch {} }, 15000);
}
const readHostMode = () => {
try { return localStorage.getItem(HOST_THEME_STORAGE_KEY) || 'system'; } catch { return 'system'; }
};
const applyHostTheme = (resolved, animate = false) => {
const prev = document.documentElement.getAttribute('data-cx-theme');
if (animate && prev && prev !== resolved) {
document.documentElement.setAttribute('data-cx-theme-switching', '1');
clearTimeout(window.__cxHostThemeSwitchTimer);
window.__cxHostThemeSwitchTimer = setTimeout(() => {
document.documentElement.removeAttribute('data-cx-theme-switching');
}, 460);
}
document.documentElement.setAttribute('data-cx-theme', resolved);
};
applyHostTheme(resolveThemeMode(readHostMode()));
window.matchMedia?.('(prefers-color-scheme: dark)')?.addEventListener?.('change', () => {
if (readHostMode() === 'system') applyHostTheme(resolveThemeMode('system'));
});
if (!window.__cxHostThemeSyncAttached) {
window.__cxHostThemeSyncAttached = true;
window.addEventListener('message', (event) => {
const payload = event?.data;
if (!payload || payload.type !== 'chaoxing-list-theme-sync') return;
if (event.origin && !event.origin.includes('chaoxing.com')) return;
if (payload.themeMode) {
try { localStorage.setItem(HOST_THEME_STORAGE_KEY, payload.themeMode); } catch {}
}
const resolved = (payload.resolved === 'dark' || payload.resolved === 'light')
? payload.resolved
: resolveThemeMode(payload.themeMode || readHostMode());
applyHostTheme(resolved, Boolean(payload.animate), payload.origin || null);
});
}
};
const fixCssConflict = () => {
const style = document.createElement('style');
style.textContent = `
.menu-list .label-item h3 {
font-size: 14px !important;
margin: 0 !important;
line-height: 24px !important;
font-weight: normal !important;
}
div.menubar a h5 {
font-size: 14px !important;
margin: 0 !important;
line-height: normal !important;
font-weight: bold !important;
white-space: nowrap !important;
}
.leftnav h3, .left_nav h3, .funclistul h3, .user-info h3,
div[class*="menu"] h3, div[class*="nav"] h3, #space_left h3, .space-left h3 {
font-size: 14px !important;
}
.space_opt .manageBtn {
font-size: 12px !important;
line-height: 24px !important;
height: auto !important;
width: auto !important;
padding: 0 10px !important;
margin: 0 5px !important;
display: inline-block !important;
box-sizing: content-box !important;
text-align: center !important;
white-space: nowrap !important;
border-radius: 4px !important;
}
.space_opt a.manageBtn {
text-decoration: none !important;
color: #333 !important;
}
`;
document.head.appendChild(style);
};
const createMenuItem = (id, text, iconClass, targetUrl, insertFunc) => {
const url = targetUrl;
const menubarElement = document.querySelector('div.menubar[role="menubar"]');
if (menubarElement) {
const a = document.createElement("a");
a.setAttribute("role", "menuitem");
a.setAttribute("tabindex", "-1");
a.id = `first${id}`;
a.setAttribute("onclick", `setUrl('${id}','${url}',this,'0','${text}')`);
a.setAttribute("dataurl", url);
const icon = document.createElement("span");
icon.className = `icon-space ${iconClass}`;
a.appendChild(icon);
const h5 = document.createElement("h5");
h5.title = text;
h5.innerHTML = `${text}`;
a.appendChild(h5);
const arrow = document.createElement("span");
arrow.className = "arrow icon-uniE900";
a.appendChild(arrow);
if (insertFunc) insertFunc(menubarElement, a);
else menubarElement.prepend(a);
}
};
const createMenuItemNew = (id, text, iconClass, targetUrl, insertFunc) => {
const menuListElement = document.querySelector("ul.menu-list-ul");
if (menuListElement) {
const li = document.createElement("li");
li.setAttribute("level", "1");
li.setAttribute("table-type", "1");
li.setAttribute("data-id", `chaoxing-assignment-${id}`);
const div = document.createElement("div");
div.className = "label-item";
div.setAttribute("role", "menuitem");
div.setAttribute("level", "1");
div.setAttribute("tabindex", "-1");
div.setAttribute("name", text);
div.setAttribute("id", `first_chaoxing_assignment_${id}`);
div.setAttribute("onclick", `setUrl('chaoxing-assignment-${id}','${targetUrl}',this,'0','${text}')`);
div.setAttribute("dataurl", targetUrl);
const icon = document.createElement("span");
icon.className = `icon-space ${iconClass}`;
div.appendChild(icon);
const h3 = document.createElement("h3");
h3.title = text;
h3.textContent = text;
div.appendChild(h3);
const arrow = document.createElement("span");
arrow.className = "slide-arrow icon-h-arrow-l hide";
div.appendChild(arrow);
li.appendChild(div);
li.appendChild(Object.assign(document.createElement("div"), { className: "school-level" })).appendChild(document.createElement("ul"));
if (insertFunc) insertFunc(menuListElement, li);
else menuListElement.prepend(li);
}
};
const createMenuItemLegacy = (id, text, iconClass, targetUrl) => {
const list = document.querySelector("ul.funclistul");
if (list && !document.querySelector(`#li_chaoxing-assignment-${id}`)) {
const li = document.createElement("li");
li.id = `li_chaoxing-assignment-${id}`;
li.className = '';
li.innerHTML = `${text}`;
list.prepend(li);
}
};
// URL 常量
const URL_HOMEWORK = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment';
const URL_EXAM = 'https://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode#chaoxing-assignment';
const URL_TODO = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment-todo';
const URL_ACTIVITIES = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment-activities';
const URL_DASHBOARD = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-dashboard';
const API_COURSE_LIST = 'https://mooc1-api.chaoxing.com/mycourse/backclazzdata?view=json&mcode=';
const initMenus = () => {
// 只创建单个"学习仪表盘"入口
if (document.querySelector('div.menubar[role="menubar"]')) {
if (!document.querySelector('#first1000000')) {
createMenuItem('1000000', '学习仪表盘', 'icon-bj', URL_DASHBOARD);
}
}
else if (document.querySelector("ul.menu-list-ul")) {
if (!document.querySelector('#first_chaoxing_assignment_dashboard')) {
createMenuItemNew('dashboard', '学习仪表盘', 'icon-bj', URL_DASHBOARD);
}
}
else if (document.querySelector("ul.funclistul")) {
createMenuItemLegacy('dashboard', '学习仪表盘', 'zne_bj_icon', URL_DASHBOARD);
}
};
const getDashboardMenuItem = () => document.querySelector(
'#first1000000, #first_chaoxing_assignment_dashboard, #li_chaoxing-assignment-dashboard a, a[href*="chaoxing-dashboard"]'
);
const startDashboardMenuBootstrap = () => {
let stopped = false;
let autoOpenScheduled = false;
let observerTimer = null;
const stop = () => {
if (stopped) return;
stopped = true;
observer.disconnect();
clearInterval(pollTimer);
clearTimeout(stopTimer);
if (observerTimer !== null) clearTimeout(observerTimer);
window.removeEventListener('pagehide', stop);
};
const ensureMenu = () => {
if (stopped) return;
initMenus();
if (autoOpenScheduled) return;
const menuItem = getDashboardMenuItem();
if (!menuItem) return;
autoOpenScheduled = true;
setTimeout(() => {
const currentMenuItem = getDashboardMenuItem();
if (currentMenuItem?.isConnected) {
currentMenuItem.click();
console.log('[脚本] 自动切换到学习仪表盘');
}
}, 500);
};
const scheduleEnsureMenu = () => {
if (stopped || observerTimer !== null) return;
observerTimer = setTimeout(() => {
observerTimer = null;
ensureMenu();
}, 100);
};
const observer = new MutationObserver(scheduleEnsureMenu);
observer.observe(document.documentElement || document, { childList: true, subtree: true });
const pollTimer = setInterval(ensureMenu, 1000);
const stopTimer = setTimeout(stop, 60000);
window.addEventListener('pagehide', stop, { once: true });
ensureMenu();
};
// 新标签页打开的菜单项创建函数
const createMenuItemNewTab = (id, text, iconClass, targetUrl) => {
const menubarElement = document.querySelector('div.menubar[role="menubar"]');
if (menubarElement) {
const a = document.createElement("a");
a.setAttribute("role", "menuitem");
a.setAttribute("tabindex", "-1");
a.id = `first${id}`;
a.href = targetUrl;
a.target = "_blank";
a.style.cursor = "pointer";
const icon = document.createElement("span");
icon.className = `icon-space ${iconClass}`;
a.appendChild(icon);
const h5 = document.createElement("h5");
h5.title = text;
h5.innerHTML = `${text}`;
a.appendChild(h5);
const arrow = document.createElement("span");
arrow.className = "arrow icon-uniE900";
a.appendChild(arrow);
menubarElement.prepend(a);
}
};
const createMenuItemNewTabNew = (id, text, iconClass, targetUrl) => {
const menuListElement = document.querySelector("ul.menu-list-ul");
if (menuListElement) {
const li = document.createElement("li");
li.setAttribute("level", "1");
li.setAttribute("table-type", "1");
li.setAttribute("data-id", `chaoxing-assignment-${id}`);
const div = document.createElement("div");
div.className = "label-item";
div.setAttribute("role", "menuitem");
div.setAttribute("level", "1");
div.setAttribute("tabindex", "-1");
div.setAttribute("name", text);
div.setAttribute("id", `first_chaoxing_assignment_${id}`);
div.style.cursor = "pointer";
div.onclick = () => window.open(targetUrl, '_blank');
const icon = document.createElement("span");
icon.className = `icon-space ${iconClass}`;
div.appendChild(icon);
const h3 = document.createElement("h3");
h3.title = text;
h3.textContent = text;
div.appendChild(h3);
const arrow = document.createElement("span");
arrow.className = "slide-arrow icon-h-arrow-l hide";
div.appendChild(arrow);
li.appendChild(div);
li.appendChild(Object.assign(document.createElement("div"), { className: "school-level" })).appendChild(document.createElement("ul"));
menuListElement.prepend(li);
}
};
const createMenuItemLegacyNewTab = (id, name, iconClass, url) => {
const list = document.querySelector("ul.funclistul");
if (list && !document.querySelector(`#first_chaoxing_assignment_${id}`)) {
const existingItem = list.querySelector('li a');
if (existingItem) {
const li = document.createElement("li");
li.id = `first_chaoxing_assignment_${id}`;
const a = document.createElement("a");
a.href = url;
a.target = "_blank";
a.title = name;
const span = document.createElement("span");
span.className = iconClass;
a.appendChild(span);
a.appendChild(document.createTextNode(name));
li.appendChild(a);
list.prepend(li);
}
}
};
// --- 课程任务汇总功能 ---
// GM_xmlhttpRequest 封装为 Promise
const gmFetch = (url, options = {}) => {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: options.method || 'GET',
url: url,
headers: options.headers || {},
data: options.data,
responseType: options.responseType || 'text',
timeout: options.timeout || 15000,
onload: (response) => {
if (response.status >= 200 && response.status < 300) {
resolve(response);
} else {
const error = new Error(`Request failed: ${response.status}`);
error.status = response.status;
reject(error);
}
},
onerror: (error) => reject(error),
ontimeout: () => reject(new Error('Request timeout'))
});
});
};
const gmFetchWithRetry = async (url, options = {}, retries = 1) => {
let attempt = 0;
while (true) {
try {
return await gmFetch(url, options);
} catch (error) {
const status = Number(error?.status);
const retryable = !Number.isFinite(status) || status === 0 || status === 408 || status === 429 || status >= 500;
if (!retryable || attempt >= retries) throw error;
await delay(status === 429 ? 1200 : 350 * (attempt + 1));
attempt += 1;
}
}
};
// 获取所有课程列表
const fetchCourseList = async () => {
let skippedCourseCount = 0;
let wasEmpty = false;
try {
console.log('[课程任务] 正在获取课程列表:', API_COURSE_LIST);
const response = await gmFetchWithRetry(API_COURSE_LIST);
const data = JSON.parse(response.responseText);
if (!data || !Array.isArray(data.channelList)) throw new Error('课程列表响应格式无法识别');
console.log('[课程任务] 收到课程栏位:', data.channelList.length);
wasEmpty = data.channelList.length === 0;
const courses = [];
for (const channel of data.channelList) {
if (!channel || typeof channel !== 'object') {
skippedCourseCount += 1;
continue;
}
const content = channel.content;
if (!content) continue;
// 检查是否是课程(有 course 对象)
if (content.course) {
if (!Array.isArray(content.course.data)) {
skippedCourseCount += 1;
continue;
}
if (content.course.data.length === 0) continue;
const courseInfo = content.course.data[0];
// 尝试多种方式获取 clazzId
let clazzId = '';
const clazzData = content.clazz?.data;
if (Array.isArray(clazzData) && clazzData[0]?.id != null) {
clazzId = String(clazzData[0].id).trim();
} else if (content.id != null && String(content.id).trim()) {
clazzId = String(content.id).trim();
} else if (channel.key != null && String(channel.key).trim()) {
clazzId = String(channel.key).trim();
}
// 只添加有 clazzId 的课程(API 需要此参数)
const courseId = courseInfo?.id == null ? '' : String(courseInfo.id).trim();
if (courseInfo && courseId && clazzId && courseId !== 'undefined' && clazzId !== 'undefined') {
courses.push({
courseId,
courseName: courseInfo.name || '未知课程',
clazzId: clazzId,
cpi: String(content.cpi || ''),
teacherName: courseInfo.teacherfactor || ''
});
console.log(`[课程任务] 解析课程: ${courseInfo.name}, clazzId=${clazzId}`);
} else {
skippedCourseCount += 1;
console.warn(`[课程任务] 跳过字段不完整的课程栏位: ${courseInfo?.name || '未知课程'}`);
}
}
}
if (data.channelList.length > 0 && courses.length === 0) {
throw new Error('课程列表有数据,但没有识别出可读取的课程');
}
console.log('[课程任务] 最终解析到课程:', courses.length, '个');
courseListDiagnostics.set(courses, { skippedCourseCount, wasEmpty });
return courses;
} catch (error) {
console.error('[课程任务] 获取课程列表失败:', error?.message || error);
throw error;
}
};
const getArrayByPaths = (value, paths) => {
for (const path of paths) {
let current = value;
for (const key of path) current = current?.[key];
if (Array.isArray(current)) return current;
}
return null;
};
const extractClassroomActivityList = (payload) => {
const list = getArrayByPaths(payload, [
['data', 'activeList'], ['data', 'list'], ['data', 'data'],
['activeList'], ['data'], []
]);
if (list) {
const items = list.filter(item => item && typeof item === 'object' && !Array.isArray(item));
return { items, invalidCount: list.length - items.length };
}
throw new Error('课堂活动响应格式无法识别');
};
const extractTaskEngineItems = (payload) => {
if (payload?.success === false || payload?.result === false) {
throw new Error('任务引擎接口返回失败');
}
const list = getArrayByPaths(payload, [
['data'], ['data', 'data'], ['data', 'list'], ['data', 'taskList'],
['data', 'taskListList'], ['data', 'tasks'], ['data', 'activeList'],
['data', 'records'], ['list'], ['taskList'], ['taskListList'],
['tasks'], ['activeList'], ['records'], []
]);
if (list) {
const items = list.filter(item => item && typeof item === 'object' && !Array.isArray(item));
return { items, invalidCount: list.length - items.length };
}
throw new Error('任务引擎响应格式无法识别');
};
const courseActivityIssues = new Map();
const courseActivityInFlight = new Map();
const courseListDiagnostics = new WeakMap();
const getCourseActivityKey = (course) => `${course?.courseId || ''}__${course?.clazzId || course?.classId || ''}`;
const clearCourseActivityIssues = () => courseActivityIssues.clear();
const recordCourseActivityIssue = (course, source) => {
const key = getCourseActivityKey(course);
const sources = courseActivityIssues.get(key) || new Set();
sources.add(source);
courseActivityIssues.set(key, sources);
};
const getCourseActivityIssues = (courses, diagnosticsSource = courses) => {
const courseListResult = Array.isArray(diagnosticsSource)
? (courseListDiagnostics.get(diagnosticsSource) || (Array.isArray(courses) ? courseListDiagnostics.get(courses) : null))
: (Array.isArray(courses) ? courseListDiagnostics.get(courses) : null);
const issues = (courses || []).flatMap(course => {
const sources = [...(courseActivityIssues.get(getCourseActivityKey(course)) || [])];
return sources.length ? [{ courseName: course.courseName, sources }] : [];
});
for (let i = 0; i < (courseListResult?.skippedCourseCount || 0); i += 1) {
issues.push({ courseName: '未识别课程', sources: ['课程列表'] });
}
if (courseListResult?.wasEmpty) issues.push({ courseName: '课程列表', sources: ['课程列表'] });
return issues;
};
const formatCourseActivityIssues = (issues) => {
if (!issues?.length) return '';
if (issues.some(issue => issue.sources?.includes('课程列表'))) {
const affectedCourses = issues.filter(issue => !issue.sources?.includes('课程列表')).length;
const detail = affectedCourses ? `另有 ${affectedCourses} 门课程读取失败。` : '';
return `课程列表为空或部分课程未能识别,待办任务可能遗漏。${detail}请刷新重试。`;
}
const sources = [...new Set(issues.flatMap(issue => issue.sources || []))].join('、');
return `读取不完整:${issues.length} 门课程的${sources || '课程任务'}接口或数据格式异常,列表可能遗漏。请刷新重试。`;
};
const normalizeTaskType = (item) => {
const typeMap = {
0: '签到', 2: '签到', 4: '抢答', 5: '分组讨论', 6: '投票',
14: '问卷', 17: '直播', 23: '随堂练习', 35: '分组任务', 42: '随堂练习',
43: '评分', 45: '拍照', 47: '作业', 64: '笔记'
};
const title = `${item.nameOne || item.name || item.title || ''}`;
if (/AI\s*实践|AI\s*评价/i.test(title)) return 'AI实践';
if (/分组/.test(title) && /讨论/.test(title)) return '分组讨论';
if (/考试/.test(title)) return '考试';
if (/测验|练习/.test(title)) return '测验';
return typeMap[item.activeType] || typeMap[item.type] || '其他任务';
};
const getTaskEngineLink = (taskId, course) => taskId
? `https://task.chaoxing.com/api/v1/middlePageApi/jumpStudyPlanList?taskId=${encodeURIComponent(taskId)}&moocClassId=${encodeURIComponent(course.clazzId)}`
: '';
const normalizeTaskEnginePlanType = (plan) => {
const typeName = `${plan.planTypeName || ''}`.trim();
const searchable = `${typeName} ${plan.name || ''}`;
if (/AI\s*实践|AI\s*评价|AI\s*对话/i.test(searchable)) return 'AI实践';
if (/分组/.test(searchable) && /(任务|作业)/.test(searchable)) return '分组任务';
if (/讨论/.test(searchable)) return '分组讨论';
if (/考试/.test(searchable)) return '考试';
if (/作业/.test(searchable)) return '作业';
if (/随堂练习/.test(searchable)) return '随堂练习';
if (/测验|自测|练习/.test(searchable)) return '测验';
if (/签到/.test(searchable)) return '签到';
if (/问卷/.test(searchable)) return '问卷';
if (/抢答/.test(searchable)) return '抢答';
if (/投票/.test(searchable)) return '投票';
if (/直播/.test(searchable)) return '直播';
if (/评分/.test(searchable)) return '评分';
if (/拍照/.test(searchable)) return '拍照';
if (/笔记/.test(searchable)) return '笔记';
if (/课程|章节|知识点|视频|文档|音频|阅读/.test(searchable)) return '视频/任务点';
const typeMap = {
0: '视频/任务点', 1: '视频/任务点', 4: '作业', 5: '考试',
8: '视频/任务点', 9: '签到', 10: '视频/任务点', 11: '视频/任务点',
13: '测验', 14: '分组讨论', 15: 'AI实践', 17: '测验', 22: '视频/任务点'
};
return typeMap[plan.planType] || '其他任务';
};
const normalizeTaskEngineSummaryItem = (item, course) => {
const planCount = Number(item.planCount) || 0;
const planFinishCount = Number(item.planFinishCount) || 0;
const studyProgress = Number(item.taskStudyProgress) || 0;
const qualifyStatus = `${item.userTaskQualifyStatus || ''}`;
const isFinished = qualifyStatus === '已达标'
|| qualifyStatus === '已完成'
|| studyProgress >= 1
|| (planCount > 0 && planFinishCount >= planCount);
const taskId = item.id ? String(item.id) : '';
return {
activeId: taskId ? `task-engine-${taskId}` : `task-engine-${course.courseId}-${item.name || ''}`,
taskId,
title: item.name || '未命名任务引擎任务',
type: '任务引擎',
status: isFinished ? '已结束' : '进行中',
time: item.lastStudyDateStr || item.createDate || '',
endTime: '',
courseName: course.courseName,
course: course.courseName,
courseId: course.courseId,
clazzId: course.clazzId,
cpi: course.cpi,
finished: isFinished,
ongoing: !isFinished,
activeType: 'task-engine',
taskEngine: true,
taskEnginePlan: false,
taskLink: getTaskEngineLink(taskId, course),
progressText: planCount > 0 ? `${planFinishCount}/${planCount}` : '',
isActivity: true
};
};
const extractTaskEngineUserId = (response) => {
const html = `${response?.responseText || ''}`;
const htmlMatch = html.match(/(?:const|let|var)\s+eTaskUserId\s*=\s*["']([^"']+)["']/);
if (htmlMatch) return htmlMatch[1];
try {
return new URL(response?.finalUrl || '').searchParams.get('encryTaskUserId') || '';
} catch {
return '';
}
};
const parseTaskEngineDate = (value) => {
if (value === null || value === undefined || value === '') return NaN;
if (typeof value === 'number') return Number.isFinite(value) ? value : NaN;
const text = normalizeTaskEngineDateText(value);
// 平台详情页常返回“09-20 20:00”这种省略年份的日期。
// Date.parse 会把它误解析为 2001 年,进而把当前年度的任务判为已过期。
const shortDateMatch = text.match(/^(\d{1,2})-(\d{1,2})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/);
if (shortDateMatch) {
const [, monthText, dayText, hourText = '0', minuteText = '0', secondText = '0'] = shortDateMatch;
const now = new Date();
const year = now.getFullYear();
const parsed = new Date(
year,
Number(monthText) - 1,
Number(dayText),
Number(hourText),
Number(minuteText),
Number(secondText)
);
if (
parsed.getFullYear() === year
&& parsed.getMonth() === Number(monthText) - 1
&& parsed.getDate() === Number(dayText)
) return parsed.getTime();
}
return Date.parse(text.replace(/-/g, '/'));
};
const parseTaskDeadlineText = (value) => {
if (typeof value === 'number') {
if (!Number.isFinite(value) || value <= 0) return NaN;
return value < 1e12 ? value * 1000 : value;
}
const text = `${value || ''}`.trim();
if (!text) return NaN;
if (/^\d{13}$/.test(text)) return Number(text);
if (/^\d{10}$/.test(text)) return Number(text) * 1000;
if (/^\d{4}-\d{2}-\d{2}T/i.test(text)) {
const isoTimestamp = Date.parse(text);
if (Number.isFinite(isoTimestamp)) return isoTimestamp;
}
const datePattern = '(?:\\d{4}[-/.年]\\d{1,2}[-/.月]\\d{1,2}日?|\\d{1,2}[-/.月]\\d{1,2}日?)';
const timePattern = '\\d{1,2}:\\d{2}(?::\\d{2})?';
const rangeMatch = text.match(new RegExp(`(${datePattern})\\s+(${timePattern})\\s*(?:至|到|[-–—~~])\\s*(?:(${datePattern})\\s*)?(${timePattern})`));
if (rangeMatch) {
return parseTaskEngineDate(`${rangeMatch[3] || rangeMatch[1]} ${rangeMatch[4]}`);
}
const dateTimePattern = new RegExp(`${datePattern}(?:\\s+${timePattern})?`, 'g');
const dateMatches = Array.from(text.matchAll(dateTimePattern), match => match[0]);
if (!dateMatches.length) return NaN;
const lastDate = dateMatches[dateMatches.length - 1].trim();
const hasTime = new RegExp(`${timePattern}`).test(lastDate);
return parseTaskEngineDate(hasTime ? lastDate : `${lastDate} 23:59:59`);
};
const getTaskDeadlineTimestamp = (item) => {
// info 是展示字段,课程任务可能在这里写“进度 1/2”,不能当作截止日期解析。
const candidates = [item?.endTimeTimestamp, item?.deadlineAt, item?.deadline, item?.endTime, item?.timeRange, item?.timeLeft, item?.leftTime];
for (const candidate of candidates) {
const timestamp = parseTaskDeadlineText(candidate);
if (Number.isFinite(timestamp)) return timestamp;
}
return NaN;
};
const parseTaskRemainingMinutes = (value) => {
const text = `${value || ''}`;
if (!text) return Infinity;
if (/过期|已结束|已截止/.test(text)) return -1;
let minutes = 0;
let matched = false;
const dayMatch = text.match(/(\d+)\s*天/);
const hourMatch = text.match(/(\d+)\s*小时/);
const minuteMatch = text.match(/(\d+)\s*分/);
const secondMatch = text.match(/(\d+)\s*秒/);
if (dayMatch) { minutes += Number(dayMatch[1]) * 24 * 60; matched = true; }
if (hourMatch) { minutes += Number(hourMatch[1]) * 60; matched = true; }
if (minuteMatch) { minutes += Number(minuteMatch[1]); matched = true; }
if (secondMatch) { minutes += Number(secondMatch[1]) / 60; matched = true; }
return matched ? minutes : Infinity;
};
const getTaskRemainingMinutes = (item, now = Date.now()) => {
const deadlineAt = getTaskDeadlineTimestamp(item);
if (Number.isFinite(deadlineAt)) return (deadlineAt - now) / 60000;
return parseTaskRemainingMinutes(item?.leftTime || item?.timeLeft || item?.info || '');
};
const compareTodoItemsByDeadline = (a, b, direction = 1) => {
const remainingA = getTaskRemainingMinutes(a);
const remainingB = getTaskRemainingMinutes(b);
if (remainingA === remainingB) return 0;
if (!Number.isFinite(remainingA)) return 1;
if (!Number.isFinite(remainingB)) return -1;
return (remainingA - remainingB) * direction;
};
const getTaskReminderKey = (item) => {
const identity = [item?.workId, item?.examId, item?.planId, item?.taskId, item?.activeId]
.filter(value => value !== null && value !== undefined && value !== '')
.join(':');
const classId = item?.clazzId || item?.classId || '';
const fallback = `${item?.course || item?.courseName || ''}|${item?.title || ''}`;
return [item?.type || '任务', item?.courseId || '', classId, identity || fallback].join('|');
};
const isTaskEnginePlanFinished = (plan) => plan.isFinish === true
|| Number(plan.isFinish) === 1
|| Number(plan.planUser?.finish) === 1
|| Number(plan.score?.completed) === 1;
const taskEngineDetailCache = new Map();
const TASK_ENGINE_DEADLINE_TYPES = new Set([
'作业', '考试', '测验', '随堂练习', '分组任务', '分组讨论',
'签到', '问卷', '抢答', '投票', '直播', 'AI实践'
]);
const TASK_ENGINE_DETAIL_HOSTS = new Set([
'mooc1.chaoxing.com', 'mooc2-ans.chaoxing.com', 'mobilelearn.chaoxing.com',
'i.chaoxing.com', 'task.chaoxing.com'
]);
const htmlToTaskEngineText = (html) => {
const source = `${html || ''}`;
if (typeof DOMParser !== 'undefined') {
const doc = new DOMParser().parseFromString(source, 'text/html');
return `${doc.body?.textContent || ''}`.replace(/\s+/g, ' ').trim();
}
return source
.replace(/