// ==UserScript== // @name 南理工教务增强助手 V2 | 支持自动评教 // @namespace http://tampermonkey.net/ // @version 2.0.3.0 // @description 在合适的地方显示课程大纲、选修课类别及选修课学分情况,并自动刷新登录状态。同时支持自动评教与批量提交。 // @match *://202.119.81.112/* // @match *://202.119.81.112:8080/* // @match *://202.119.81.112:9080/* // @match *://202.119.81.113/* // @match *://202.119.81.113:8080/* // @match *://202.119.81.113:9080/* // @match *://bkjw.njust.edu.cn/* // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect jsdelivr.net // @connect njust.wiki // @connect njust.store // @connect raw.githubusercontent.com // @author Light // @license MIT // @supportURL https://github.com/NJUST-OpenLib/NJUST-JWC-Enhance // ==/UserScript== /** * ⚠️ 本文件由 build.js 自动生成,请勿直接修改。 * 源码位于 src/ 目录,修改后请执行:npm run build */ // ===== 以下内容由 src/**/*.css 自动注入 ===== (function () { const njustCssText = "/* =============================================================\n 设计变量(Design Tokens)\n 全脚本统一的色彩 / 圆角 / 阴影 / 字号 / 层级体系。\n 组件样式一律通过 var() 引用,禁止再硬编码色值。\n ============================================================= */\n:root {\n /* ── 语义色 ── */\n --nju-primary: #007AFF;\n --nju-primary-hover: #0A6EDC;\n --nju-primary-soft: rgba(0, 122, 255, 0.12);\n --nju-success: #34C759;\n --nju-success-soft: rgba(52, 199, 89, 0.12);\n --nju-warning: #FF9500;\n --nju-warning-soft: rgba(255, 149, 0, 0.12);\n --nju-danger: #FF3B30;\n --nju-danger-soft: rgba(255, 59, 48, 0.12);\n\n /* ── 中性色 ── */\n --nju-bg: #ffffff;\n --nju-bg-subtle: #f5f6f8;\n --nju-bg-hover: #eef0f3;\n --nju-border: #e3e5e8;\n --nju-border-strong: #d2d2d7;\n --nju-text: #1d1d1f;\n --nju-text-2: #5f6368;\n --nju-text-3: #9aa0a6;\n\n /* ── 圆角 ── */\n --nju-radius-sm: 6px;\n --nju-radius-md: 10px;\n --nju-radius-lg: 14px;\n --nju-radius-full: 999px;\n\n /* ── 阴影 ── */\n --nju-shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);\n --nju-shadow-md: 0 8px 28px rgba(0, 0, 0, 0.13);\n --nju-shadow-lg: 0 20px 60px rgba(0, 0, 0, 0.18);\n\n /* ── 字体 ── */\n --nju-font: -apple-system, BlinkMacSystemFont, \"SF Pro Text\", \"Segoe UI\",\n Roboto, \"Helvetica Neue\", Arial, \"Microsoft YaHei\", sans-serif;\n --nju-font-mono: \"SFMono-Regular\", Consolas, \"Lucida Console\", monospace;\n\n /* ── 字号 ── */\n --nju-fs-xs: 11px;\n --nju-fs-sm: 12px;\n --nju-fs-md: 13px;\n --nju-fs-lg: 15px;\n --nju-fs-xl: 17px;\n\n /* ── 层级:统一分档,避免各面板自行定义 ── */\n --nju-z-float: 9000; /* 常驻浮层(日志抽屉等) */\n --nju-z-panel: 10000; /* 功能面板(学分统计、评教面板) */\n --nju-z-modal: 11000; /* 模态弹窗 */\n --nju-z-topbar: 12000; /* 页面顶栏(评教自动条) */\n}\n\n\n/* =============================================================\n 基础原子类\n 依赖 theme.css 中定义的设计变量;所有面板共用同一套控件外观。\n ============================================================= */\n\n/* ── 按钮 ── */\n.nju-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 4px;\n padding: 5px 12px;\n border: 1px solid var(--nju-border);\n border-radius: var(--nju-radius-sm);\n background: var(--nju-bg);\n color: var(--nju-text-2);\n font-family: var(--nju-font);\n font-size: var(--nju-fs-sm);\n line-height: 1.4;\n cursor: pointer;\n transition: background-color .15s ease, border-color .15s ease, color .15s ease;\n}\n\n.nju-btn:hover { background: var(--nju-bg-hover); color: var(--nju-text); }\n.nju-btn:focus-visible { outline: 2px solid var(--nju-primary); outline-offset: 2px; }\n.nju-btn:disabled, .nju-btn[disabled] { opacity: .5; cursor: not-allowed; }\n\n.nju-btn-primary {\n background: var(--nju-primary);\n border-color: var(--nju-primary);\n color: #fff;\n}\n.nju-btn-primary:hover { background: var(--nju-primary-hover); border-color: var(--nju-primary-hover); color: #fff; }\n\n.nju-btn-danger {\n background: var(--nju-danger);\n border-color: var(--nju-danger);\n color: #fff;\n}\n.nju-btn-danger:hover { filter: brightness(.94); color: #fff; }\n\n.nju-btn-ghost { background: transparent; border-color: transparent; }\n.nju-btn-ghost:hover { background: var(--nju-bg-hover); }\n\n.nju-btn-mini { padding: 2px 8px; font-size: var(--nju-fs-xs); }\n\n/* 兼容评教模块的既有按钮类名,统一补齐交互态 */\n.vb:hover { filter: brightness(.96); }\n.vb:focus-visible { outline: 2px solid var(--nju-primary); outline-offset: 2px; }\n.vb:disabled, .vb[disabled] { opacity: .5; cursor: not-allowed; }\n\n/* ── 关闭按钮 ── */\n.nju-close {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 24px;\n height: 24px;\n padding: 0;\n border: none;\n border-radius: var(--nju-radius-full);\n background: transparent;\n color: var(--nju-text-3);\n font-size: 15px;\n line-height: 1;\n cursor: pointer;\n transition: background-color .15s ease, color .15s ease;\n}\n.nju-close:hover { background: var(--nju-bg-hover); color: var(--nju-text); }\n.nju-close:focus-visible { outline: 2px solid var(--nju-primary); outline-offset: 2px; }\n\n/* ── 面板骨架 ── */\n.nju-panel {\n background: var(--nju-bg);\n border: 1px solid var(--nju-border);\n border-radius: var(--nju-radius-lg);\n box-shadow: var(--nju-shadow-md);\n font-family: var(--nju-font);\n color: var(--nju-text);\n}\n\n.nju-panel-hd {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 18px;\n border-bottom: 1px solid var(--nju-border);\n background: var(--nju-bg-subtle);\n border-radius: var(--nju-radius-lg) var(--nju-radius-lg) 0 0;\n font-size: var(--nju-fs-xl);\n font-weight: 600;\n color: var(--nju-text);\n}\n\n.nju-panel-bd { padding: 16px 18px; font-size: var(--nju-fs-md); }\n\n/* ── 徽章 ── */\n.nju-badge {\n display: inline-flex;\n align-items: center;\n padding: 1px 8px;\n border-radius: var(--nju-radius-full);\n background: var(--nju-bg-subtle);\n color: var(--nju-text-2);\n font-size: var(--nju-fs-xs);\n line-height: 1.6;\n}\n.nju-badge-primary { background: var(--nju-primary-soft); color: var(--nju-primary); }\n.nju-badge-success { background: var(--nju-success-soft); color: #248A3D; }\n.nju-badge-warning { background: var(--nju-warning-soft); color: #B25000; }\n.nju-badge-danger { background: var(--nju-danger-soft); color: #C0291D; }\n\n/* ── 提示条 ── */\n.nju-note {\n padding: 9px 12px;\n border: 1px solid var(--nju-border);\n border-radius: var(--nju-radius-md);\n background: var(--nju-primary-soft);\n color: var(--nju-text-2);\n font-size: var(--nju-fs-sm);\n}\n\n/* =============================================================\n 统一窗口框架\n ============================================================= */\n.nju-window {\n position: fixed;\n display: flex;\n flex-direction: column;\n background: var(--nju-bg);\n border: 1px solid var(--nju-border);\n border-radius: var(--nju-radius-lg);\n box-shadow: var(--nju-shadow-md);\n font-family: var(--nju-font);\n color: var(--nju-text);\n overflow: hidden;\n box-sizing: border-box;\n}\n\n.nju-window-hd {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 11px 16px;\n background: var(--nju-bg-subtle);\n border-bottom: 1px solid var(--nju-border);\n cursor: move;\n user-select: none;\n flex-shrink: 0;\n}\n\n.nju-window-title {\n font-size: var(--nju-fs-md);\n font-weight: 600;\n color: var(--nju-text);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nju-window-sub {\n flex: 1;\n min-width: 0;\n font-size: var(--nju-fs-sm);\n color: var(--nju-text-3);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nju-window-actions {\n margin-left: auto;\n display: flex;\n align-items: center;\n gap: 2px;\n flex-shrink: 0;\n}\n\n.nju-window-bd {\n flex: 1;\n min-height: 0;\n overflow: auto;\n padding: 16px 18px;\n font-size: var(--nju-fs-md);\n box-sizing: border-box;\n}\n\n.nju-window-ft {\n flex-shrink: 0;\n border-top: 1px solid var(--nju-border);\n padding: 10px 18px;\n font-size: var(--nju-fs-sm);\n color: var(--nju-text-3);\n line-height: 1.6;\n}\n\n/* ── 八方向缩放手柄 ── */\n.nju-resize-layer {\n position: absolute;\n inset: 0;\n pointer-events: none;\n z-index: 5;\n}\n\n.nju-resize-handle {\n position: absolute;\n pointer-events: auto;\n touch-action: none;\n}\n\n.nju-resize-n, .nju-resize-s { left: 12px; right: 12px; height: 6px; cursor: ns-resize; }\n.nju-resize-e, .nju-resize-w { top: 12px; bottom: 12px; width: 6px; cursor: ew-resize; }\n.nju-resize-n { top: 0; }\n.nju-resize-s { bottom: 0; }\n.nju-resize-e { right: 0; }\n.nju-resize-w { left: 0; }\n.nju-resize-ne, .nju-resize-nw, .nju-resize-se, .nju-resize-sw { width: 14px; height: 14px; }\n.nju-resize-ne { top: 0; right: 0; cursor: nesw-resize; }\n.nju-resize-nw { top: 0; left: 0; cursor: nwse-resize; }\n.nju-resize-se { bottom: 0; right: 0; cursor: nwse-resize; }\n.nju-resize-sw { bottom: 0; left: 0; cursor: nesw-resize; }\n"; const styleEl = document.createElement("style"); styleEl.id = "njust-injected-style"; styleEl.textContent = njustCssText; (document.head || document.documentElement).appendChild(styleEl); })(); // ===== src/core/config.js ============================================== // ================================================================ // 【模块一】核心增强功能模块 // 职责:数据抓取、课程信息增强(大纲/类别)、学分统计、登录保活 // 设计模式:单例对象(Singleton)组织各子系统 // ================================================================ (function () { 'use strict'; /** * ── 数据源镜像配置 ───────────────────────────────────────────── * 采用多节点冗余设计,解决部分节点在大规模访问时的稳定性问题。 * 优先级顺序:官方主站 > jsDelivr 加速 > jsDelivr 备用 > GitHub Raw。 */ // 选修课类别数据源(JSON 格式) const CATEGORY_URL_TEMPLATES = [ 'https://enhance.njust.store/data/xxk.json', 'https://enhance.njust.wiki/data/xxk.json', // 官方主节点 'https://fastly.jsdelivr.net/gh/NJUST-OpenLib/NJUST-JWC-Enhance@latest/data/xxk.json', // jsDelivr 全球加速 'https://testingcf.jsdelivr.net/gh/NJUST-OpenLib/NJUST-JWC-Enhance@latest/data/xxk.json', // jsDelivr Cloudflare 'https://raw.githubusercontent.com/NJUST-OpenLib/NJUST-JWC-Enhance/refs/heads/main/data/xxk.json' // GitHub 原始文件(备用) ]; /** * ── 多版本培养方案支持 ─────────────────────────────────────────── * 教务处每 4 年更新一次通识课分类口径,各年级需按入学当年的方案统计类别学分。 * 脚本依据学号自动判断入学年份,加载对应版本的数据文件;也支持手动指定。 */ // 培养方案版本 → 数据文件名(2026 版即默认的 xxk.json) const XXK_VERSION_FILES = { '2018': 'xxk_2018.json', '2022': 'xxk_2022.json', '2026': 'xxk.json' }; // 入学年份 → 培养方案版本(倒序匹配;学校若调整适用口径请修改此处) const PLAN_VERSION_RULES = [ { since: 2026, version: '2026' }, { since: 2022, version: '2022' }, { since: 0, version: '2018' } ]; const KEY_XXK_VERSION = 'njust_xxk_version'; // 手动指定的口径版本(优先级最高) const KEY_XXK_YEAR = 'njust_xxk_enroll_year'; // 缓存的入学年份 const KEY_XXK_STUDENT = 'njust_xxk_student_mask'; // 缓存的脱敏学号 /** * 识别当前登录者的学号与入学年份 * 学号规则(如 922110800724):9=本科生,22=2022 级,108=自动化学院,其后为院内流水号 * 主框架页顶部节点 [id$="divLoginName"] 形如「张三(922110800724)」 */ function detectEnrollment() { try { const cachedYear = parseInt(localStorage.getItem(KEY_XXK_YEAR) || '', 10); if (cachedYear) { return { year: cachedYear, student: localStorage.getItem(KEY_XXK_STUDENT) || '' }; } const nameNodes = document.querySelectorAll('[id$="divLoginName"], .Nsb_top_menu_nc'); let idNumber = ''; for (const node of nameNodes) { const matched = (node.textContent || '').match(/(\d{9,15})/); if (matched) { idNumber = matched[1]; break; } } if (!idNumber) return null; // 第 2-3 位为入学年份后两位 const yearPart = idNumber.length >= 10 ? idNumber.slice(1, 3) : ''; const year = parseInt(yearPart, 10) + 2000; if (!yearPart || year < 2008 || year > new Date().getFullYear() + 1) return null; // 脱敏:保留前 6 位 const masked = idNumber.slice(0, 6) + '*'.repeat(Math.max(idNumber.length - 6, 0)); localStorage.setItem(KEY_XXK_YEAR, String(year)); localStorage.setItem(KEY_XXK_STUDENT, masked); Logger.info(`识别到学号 ${masked},推断入学年份 ${year}`); return { year, student: masked }; } catch (e) { Logger.warn('学号识别失败:', e); return null; } } /** * 解析当前应使用的分类口径 * 优先级:手动指定 > 学号自动识别 > 默认 2026 版 */ function resolveCategoryVersion() { try { const manual = localStorage.getItem(KEY_XXK_VERSION); if (manual && XXK_VERSION_FILES[manual]) { return { version: manual, source: 'manual' }; } const info = detectEnrollment(); if (info) { const rule = PLAN_VERSION_RULES.find(r => info.year >= r.since); if (rule) return { version: rule.version, source: 'auto', year: info.year, student: info.student }; } } catch (e) { Logger.warn('解析分类口径失败:', e); } return { version: '2026', source: 'default' }; } /** 按指定口径生成分类数据源地址列表 */ function getCategoryURLs(version) { const file = XXK_VERSION_FILES[version] || XXK_VERSION_FILES['2026']; return CATEGORY_URL_TEMPLATES.map(url => url.replace('xxk.json', file)); } /** 口径来源的中文描述,供日志与界面显示 */ function describeVersionSource(info) { if (info.source === 'manual') return '手动指定'; if (info.source === 'auto') return `学号自动识别 · ${info.year} 级`; return '默认 · 最新方案'; } // 课程大纲索引数据源(包含课程代码到 jx02id 的映射) const OUTLINE_URLS = [ 'https://enhance.njust.store/data/kcdg.json', 'https://enhance.njust.wiki/data/kcdg.json', // 官方主节点 'https://fastly.jsdelivr.net/gh/NJUST-OpenLib/NJUST-JWC-Enhance@latest/data/kcdg.json', // jsDelivr 全球加速 'https://testingcf.jsdelivr.net/gh/NJUST-OpenLib/NJUST-JWC-Enhance@latest/data/kcdg.json', // jsDelivr Cloudflare 'https://raw.githubusercontent.com/NJUST-OpenLib/NJUST-JWC-Enhance/refs/heads/main/data/kcdg.json' // GitHub 原始文件(备用) ]; /** * ── 全局配置选项 ─────────────────────────────────────────────── */ const UI_CONFIG = { showNotifications: true // 是否允许弹出系统级通知(目前主要通过 LogPanel 反馈) }; /** * ── 调试系统配置 ─────────────────────────────────────────────── * enabled: 开启后会向控制台和日志面板输出详细过程 * level: 4(DEBUG), 3(INFO), 2(WARN), 1(ERROR) */ const DEBUG_CONFIG = { enabled: true, level: 2, // 默认仅记录 WARN 及以上,避免切页时缓存日志刷屏 showCache: false // 是否在日志中详细记录缓存的存取动作 }; /** * 大纲链接显示模式 * both = 课程大纲 + 大纲镜像(默认) * original = 仅官方课程大纲 * mirror = 仅大纲镜像 * none = 不显示 */ const KEY_OUTLINE_MODE = 'njust_outline_mode'; function getOutlineMode() { const mode = localStorage.getItem(KEY_OUTLINE_MODE); return ['both', 'original', 'mirror', 'none'].indexOf(mode) !== -1 ? mode : 'both'; } function setOutlineMode(mode) { localStorage.setItem(KEY_OUTLINE_MODE, mode); } /** * ── 缓存系统配置 ─────────────────────────────────────────────── * 使用 localStorage 存储远程 JSON 数据,减少重复的网络请求,提升页面加载速度。 */ const CACHE_CONFIG = { enabled: true, ttl: 86400, // 缓存有效期:(单位:秒) prefix: 'njust_jwc_enhance_' // 本脚本专用的缓存键名前缀 }; /** * ── 日志面板 UI 系统 ──────────────────────────────────────────── * 这是一个右下角的悬浮面板,用于实时展示脚本运行状态,取代了侵入式的 Toast 弹窗。 * 特性: * 1. 队列化处理:确保在 DOM 准备好之前产生的日志不会丢失。 * 2. 标题栏滚动:标题栏会循环展示最新的日志摘要,5秒后自动复位。 * 3. 级别过滤:支持在展开状态下通过下拉菜单过滤日志级别。 */ // ===== src/core/logging.js ============================================= const LogPanelUI = { container: null, // 外部容器 DOM body: null, // 日志行容器 DOM initialized: false, // 初始化状态标志 queue: [], // 预初始化消息队列 _statusQueue: [], // 标题栏待播放队列 _statusPlaying: false, // 标题栏是否正在播放动画 /** * 初始化面板 DOM 并注入样式 */ init() { if (this.initialized || !document.body) return; const style = document.createElement('style'); style.textContent = ` /* 面板主样式 */ #njust-enhance-log { position: fixed; bottom: 0; right: 20px; width: 380px; background: var(--nju-bg); border: 1px solid var(--nju-border); border-bottom: none; border-radius: var(--nju-radius-md) var(--nju-radius-md) 0 0; box-shadow: var(--nju-shadow-sm); z-index: var(--nju-z-float); font-family: var(--nju-font-mono); display: flex; flex-direction: column; transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); } #njust-enhance-log.minimized { transform: translateY(calc(100% - 38px)); } /* 标题栏样式 */ #njust-enhance-log-hd { padding: 10px 15px; background: var(--nju-bg-subtle); border-bottom: 1px solid var(--nju-border); cursor: pointer; display: flex; align-items: center; justify-content: space-between; border-radius: var(--nju-radius-md) var(--nju-radius-md) 0 0; user-select: none; gap: 10px; } #njust-enhance-log-hd b { font-size: var(--nju-fs-md); color: var(--nju-text); display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; } #nel-status-text { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1; } /* 日志列表样式 */ #njust-enhance-log-body { height: 220px; overflow-y: auto; background: var(--nju-bg); font-size: var(--nju-fs-xs); padding: 4px 0; scroll-behavior: smooth; } .nel-btn { font-size: var(--nju-fs-xs); color: var(--nju-text-2); background: var(--nju-bg-subtle); padding: 2px 8px; border-radius: var(--nju-radius-sm); cursor: pointer; transition: all 0.2s; white-space: nowrap; } .nel-btn:hover { background: var(--nju-bg-hover); color: var(--nju-text); } .nel-clear { background: var(--nju-danger-soft); color: var(--nju-danger); } .nel-clear:hover { background: rgba(255, 59, 48, 0.18); color: var(--nju-danger); } /* 日志行与分级颜色 */ .nel-line { padding: 3px 12px; border-bottom: 1px solid var(--nju-border); display: flex; gap: 8px; align-items: flex-start; } .nel-line:hover { background: var(--nju-bg-subtle); } .nel-ts { color: var(--nju-text-3); flex-shrink: 0; min-width: 55px; user-select: none; } .nel-lvl { font-weight: bold; flex-shrink: 0; min-width: 42px; text-align: center; font-size: 10px; } .nel-msg { color: var(--nju-text-2); word-break: break-all; flex: 1; line-height: 1.5; } .nel-error { border-left: 3px solid #e53e3e; background: rgba(229, 62, 62, 0.02); } .nel-error .nel-lvl { color: #e53e3e; } .nel-warn { border-left: 3px solid #dd6b20; background: rgba(221, 107, 32, 0.02); } .nel-warn .nel-lvl { color: #dd6b20; } .nel-success { border-left: 3px solid #38a169; background: rgba(56, 161, 105, 0.02); } .nel-success .nel-lvl { color: #38a169; } .nel-info { border-left: 3px solid #3182ce; } .nel-info .nel-lvl { color: #3182ce; } .nel-debug { border-left: 3px solid #9f7aea; color: #718096; } .nel-debug .nel-lvl { color: #9f7aea; } `; document.head.appendChild(style); this.container = document.createElement('div'); this.container.id = 'njust-enhance-log'; this.container.className = 'nju-window minimized'; this.container.innerHTML = `
南理工教务增强助手 V2 清空 隐藏 展开
`; document.body.appendChild(this.container); this.body = this.container.querySelector('#njust-enhance-log-body'); this.initialized = true; // 统一窗口能力:拖动 + 缩放 + 位置/尺寸记忆(底部贴边,禁用向下拉伸) enableWindow({ id: 'log', target: this.container, handle: this.container.querySelector('#njust-enhance-log-hd'), minWidth: 320, minHeight: 160, edges: ['n', 'e', 'w', 'ne', 'nw'] }); // 绑定交互事件 this.container.querySelector('#njust-enhance-log-hd').onclick = (e) => { if (e.target.id === 'nel-clear-btn' || e.target.id === 'njust-log-hide') return; const isMin = this.container.classList.toggle('minimized'); this.container.querySelector('#njust-log-toggle').textContent = isMin ? '展开' : '折叠'; }; // 隐藏日志面板(持久化,右下角保留极简恢复入口) this.container.querySelector('#njust-log-hide').onclick = (e) => { e.stopPropagation(); localStorage.setItem('njust_log_hidden', '1'); this.container.style.display = 'none'; this._createRestoreButton(); }; this.container.querySelector('#nel-clear-btn').onclick = (e) => { e.stopPropagation(); if (this.body) this.body.innerHTML = ''; const statusText = this.container.querySelector('#nel-status-text'); if (statusText) statusText.textContent = '日志已清空'; // 清空时也清空标题栏队列 this._statusQueue = []; this._statusPlaying = false; }; // 用户曾隐藏日志面板:保持隐藏,仅保留右下角恢复入口 if (localStorage.getItem('njust_log_hidden') === '1') { this.container.style.display = 'none'; this._createRestoreButton(); } // 处理初始化前的缓存消息 if (this.queue.length > 0) { this.queue.forEach(item => this.add(item.level, item.msg)); this.queue = []; } }, /** * 向面板添加一条新日志 * @param {string} level - 级别: error, warn, success, info, debug * @param {string} msg - 日志内容 */ add(level, msg) { if (!this.initialized) { this.init(); if (!this.initialized) { this.queue.push({ level, msg }); return; } } if (!this.body) return; const labels = { error: '[ERR]', warn: '[WRN]', success: '[OK ]', info: '[INF]', debug: '[DBG]' }; const lvlLabel = labels[level] || '[INF]'; const ts = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' }); const line = document.createElement('div'); line.className = `nel-line nel-${level}`; line.innerHTML = `[${ts}]${lvlLabel}${this.esc(msg)}`; this.body.appendChild(line); // 限制最大行数,防止页面过重 if (this.body.children.length > 200) this.body.removeChild(this.body.firstChild); this.body.scrollTop = this.body.scrollHeight; // 加入标题栏滚动显示队列 this._statusQueue.push({ msg, level }); if (!this._statusPlaying) { this._playStatusQueue(); } }, /** * 标题栏消息队列播放器 */ _playStatusQueue() { // 折叠状态下不播放标题栏滚动,避免切页时频繁跳动干扰阅读 if (this.container && this.container.classList.contains('minimized')) { this._statusQueue = []; this._statusPlaying = false; return; } if (this._statusQueue.length === 0) { this._statusPlaying = false; // 恢复默认状态文字 const statusText = this.container && this.container.querySelector('#nel-status-text'); if (statusText) { statusText.textContent = '南理工教务增强助手 V2'; statusText.style.color = '#2d3748'; } return; } this._statusPlaying = true; const { msg, level } = this._statusQueue.shift(); const statusText = this.container && this.container.querySelector('#nel-status-text'); if (statusText) { const colors = { error: '#e53e3e', warn: '#dd6b20', success: '#38a169', info: '#3182ce', debug: '#718096' }; statusText.textContent = msg; statusText.style.color = colors[level] || '#2d3748'; } // 每 300ms 切换下一条,形成滚动感 setTimeout(() => { this._playStatusQueue(); }, 300); }, /** * 右下角的极简恢复入口(隐藏日志后仍可找回) */ _createRestoreButton() { if (document.getElementById('njust-log-restore')) return; const btn = document.createElement('button'); btn.id = 'njust-log-restore'; btn.type = 'button'; btn.textContent = '日志'; btn.title = '显示日志面板'; btn.style.cssText = ` position: fixed; right: 18px; bottom: 6px; z-index: var(--nju-z-float); padding: 2px 6px; border: none; border-radius: 4px; background: transparent; color: var(--nju-text-3); font-family: var(--nju-font); font-size: 11px; opacity: 0.4; cursor: pointer; transition: opacity .15s ease; `; btn.addEventListener('mouseenter', () => { btn.style.opacity = '0.9'; }); btn.addEventListener('mouseleave', () => { btn.style.opacity = '0.4'; }); btn.addEventListener('click', () => { localStorage.removeItem('njust_log_hidden'); if (this.container) this.container.style.display = ''; btn.remove(); }); document.body.appendChild(btn); }, esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>'); } }; /** * ── 调试系统 ──────────────────────────────────────────────────── * 统一的日志入口,负责格式化输出并同步到 LogPanelUI。 */ const Logger = { LEVELS: { ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 }, log(level, message, ...args) { if (!DEBUG_CONFIG.enabled || level > DEBUG_CONFIG.level) return; const timestamp = new Date().toLocaleTimeString(); const levelNames = ['', 'error', 'warn', 'info', 'debug']; const lvlName = levelNames[level] || 'info'; // 控制台原生输出 console.log(`[${timestamp}] [南理工教务助手]`, message, ...args); // 格式化对象参数,使其在 UI 面板中可见 let displayMessage = message; if (args.length > 0) { const formattedArgs = args.map(arg => { if (typeof arg === 'object' && arg !== null) { try { return JSON.stringify(arg, null, 1) .replace(/^{|}$/g, '') .replace(/"/g, '') .replace(/\n/g, ' '); } catch (e) { return '[Object]'; } } return String(arg); }).join(' '); displayMessage += ' ' + formattedArgs; } // 同步到 UI 面板 LogPanelUI.add(lvlName, displayMessage); }, error(message, ...args) { this.log(this.LEVELS.ERROR, message, ...args); }, warn(message, ...args) { this.log(this.LEVELS.WARN, message, ...args); }, info(message, ...args) { this.log(this.LEVELS.INFO, message, ...args); }, debug(message, ...args) { this.log(this.LEVELS.DEBUG, message, ...args); } }; /** * ── 缓存系统 ──────────────────────────────────────────────────── * 负责远程 JSON 数据在本地 localStorage 的存取、过期判断及统计。 */ // ===== src/core/cache.js =============================================== const CacheManager = { /** * 生成 URL 对应的哈希键名 */ getKey(url) { return CACHE_CONFIG.prefix + btoa(unescape(encodeURIComponent(url))).replace(/[^a-zA-Z0-9]/g, ''); }, /** * 存入缓存 */ set(url, data) { if (!CACHE_CONFIG.enabled) return false; try { const cacheData = { data, timestamp: Date.now(), ttl: CACHE_CONFIG.ttl * 1000, url }; localStorage.setItem(this.getKey(url), JSON.stringify(cacheData)); if (DEBUG_CONFIG.showCache) Logger.info(`缓存已保存: ${url}`); return true; } catch (e) { Logger.error('缓存保存失败: ', e); return false; } }, /** * 读取缓存(包含过期校验) */ get(url) { if (!CACHE_CONFIG.enabled) return null; try { const key = this.getKey(url); const cached = localStorage.getItem(key); if (!cached) { if (DEBUG_CONFIG.showCache) Logger.debug(`缓存未命中: ${url}`); return null; } const cacheData = JSON.parse(cached); const now = Date.now(); // 过期判断 if (now - cacheData.timestamp > cacheData.ttl) { localStorage.removeItem(key); if (DEBUG_CONFIG.showCache) Logger.warn(`⏰ 缓存已过期: ${url}`); return null; } const age = ((now - cacheData.timestamp) / 1000).toFixed(1); const remaining = ((cacheData.ttl - (now - cacheData.timestamp)) / 1000).toFixed(1); if (DEBUG_CONFIG.showCache) Logger.info(`缓存命中: ${url} (已缓存${age}s,剩余${remaining}s)`); return cacheData.data; } catch (e) { Logger.error('缓存读取失败: ', e); return null; } }, /** * 清空本脚本产生的所有缓存 */ clear() { try { const keys = Object.keys(localStorage).filter(k => k.startsWith(CACHE_CONFIG.prefix)); keys.forEach(k => localStorage.removeItem(k)); Logger.info(`已清除 ${keys.length} 个缓存项`); return keys.length; } catch (e) { Logger.error('清除缓存失败: ', e); return 0; } }, /** * 获取缓存占用情况统计 */ getStats() { try { const keys = Object.keys(localStorage).filter(k => k.startsWith(CACHE_CONFIG.prefix)); let totalSize = 0, validCount = 0, expiredCount = 0; const now = Date.now(); keys.forEach(k => { try { const cached = localStorage.getItem(k); totalSize += cached.length; const d = JSON.parse(cached); (now - d.timestamp > d.ttl) ? expiredCount++ : validCount++; } catch (e) { expiredCount++; } }); return { total: keys.length, valid: validCount, expired: expiredCount, size: totalSize }; } catch (e) { Logger.error('获取缓存统计失败: ', e); return { total: 0, valid: 0, expired: 0, size: 0 }; } } }; // fix④: 彻底移除与 LogPanelUI 职责重叠的 StatusNotifier, // 原代码中该系统的调用已被注释,直接删除其定义以消除冗余。 // ===== src/core/bootstrap.js =========================================== // ==================== 延迟初始化日志 ==================== function initializeLogging() { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initializeLogging); return; } setTimeout(() => { try { Logger.info('南理工教务增强助手已启动', { debug: DEBUG_CONFIG.enabled ? `Level ${DEBUG_CONFIG.level}` : '关闭', cache: CACHE_CONFIG.enabled ? `TTL ${CACHE_CONFIG.ttl}s` : '关闭' }); if (DEBUG_CONFIG.enabled && DEBUG_CONFIG.showCache) { const stats = CacheManager.getStats(); Logger.info(`缓存统计: 总${stats.total} 有效${stats.valid} 过期${stats.expired} ${(stats.size / 1024).toFixed(1)}KB`); } } catch (e) { console.error('初始化日志失败: ', e); } }, 100); } initializeLogging(); // 早期初始化推广信息(在数据加载之前显示) function initializePromoBanner() { const tryShow = () => { // 检查是否已存在 if (document.getElementById('njust-promo-line')) return true; // 检查两种版权信息结构 const footer = document.getElementById('Footer1_divCopyright'); const copyrightLink = document.querySelector('a.copyright[href*="qzdatasoft"]'); if (footer || (copyrightLink && copyrightLink.parentElement)) { showPromoBanner(); return true; } return false; }; // 隐藏无法使用的二维码图片 const hideUnusedElements = () => { const uselessImg = document.querySelector('img[src*="appewm.png"]'); if (uselessImg) { uselessImg.style.display = 'none'; } }; // 尝试立即显示和隐藏 if (tryShow()) { hideUnusedElements(); return; } // 如果目标元素还不存在,监听 DOM 变化 const observer = new MutationObserver(() => { if (tryShow()) { hideUnusedElements(); observer.disconnect(); } }); observer.observe(document.documentElement, { childList: true, subtree: true }); // 5 秒后停止监听(防止内存泄漏) setTimeout(() => observer.disconnect(), 5000); } initializePromoBanner(); let courseCategoryMap = {}; let courseOutlineMap = {}; // ===== src/ui/modal.js ================================================= // ==================== 统一弹窗 ==================== function createUnifiedModal(title, content, type = 'info') { const existingModal = document.getElementById('njustAssistantModal'); if (existingModal) existingModal.remove(); const container = document.createElement('div'); container.id = 'njustAssistantModal'; // 主题色彩统一取自设计变量(src/ui/theme.css) const themeConfig = { warning: { accent: 'var(--nju-warning)', accentLight: 'var(--nju-warning-soft)' }, success: { accent: 'var(--nju-success)', accentLight: 'var(--nju-success-soft)' }, info: { accent: 'var(--nju-primary)', accentLight: 'var(--nju-primary-soft)' } }; const theme = themeConfig[type] || themeConfig.info; container.className = 'nju-window'; container.style.cssText = ` top: 50%; left: 50%; transform: translate(-50%, -50%); width: 420px; min-width: 320px; max-width: 90vw; z-index: var(--nju-z-modal); animation: njustFadeIn 0.25s cubic-bezier(0.4, 0, 0.2, 1); `; container.innerHTML = `
${title}
${content}
查看使用说明
免责声明 — 本工具仅供学习交流,数据仅供参考。请以教务处官网信息为准,使用本工具产生的任何后果由用户自行承担。
`; if (!document.getElementById('njustAssistantStyles')) { const style = document.createElement('style'); style.id = 'njustAssistantStyles'; style.textContent = ` @keyframes njustFadeIn { from { opacity: 0; transform: translate(-50%, -50%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } } /* 关闭按钮交互态由 base.css 的 .nju-close 统一提供 */ `; document.head.appendChild(style); } enableWindow({ id: 'modal', target: container, handle: container.querySelector('#dragHandle'), minWidth: 320, minHeight: 220 }); document.body.appendChild(container); // 绑定关闭按钮事件 const closeBtn = container.querySelector('#closeModalBtn'); if (closeBtn) { closeBtn.addEventListener('click', () => container.remove()); } return container; } // ===== src/ui/drag.js ================================================== // ==================== 拖动功能 ==================== /** * 统一拖拽实现 —— 全脚本唯一的拖拽入口 * * 说明: * - 使用 getBoundingClientRect 读取视觉位置,避免折叠/动画 transform 造成的坐标跳变 * - 同时支持鼠标与触摸事件 * - 只使用 addEventListener,不会覆盖页面上的其它监听器 * * @param {HTMLElement} handle 拖拽句柄 * @param {HTMLElement} target 被移动的元素(通常为句柄所属容器) * @param {Object} [options] * @param {(e: Event) => boolean} [options.shouldIgnore] 返回 true 时忽略本次拖拽 */ function makeDraggable(handle, target, options = {}) { if (!handle || !target) return; let isDragging = false; let mouseStartX = 0, mouseStartY = 0, elemStartX = 0, elemStartY = 0; const getPoint = (e) => (e.touches && e.touches[0]) ? { x: e.touches[0].clientX, y: e.touches[0].clientY } : { x: e.clientX, y: e.clientY }; const dragStart = (e) => { if (options.shouldIgnore && options.shouldIgnore(e)) return; const point = getPoint(e); const rect = target.getBoundingClientRect(); elemStartX = rect.left; elemStartY = rect.top; mouseStartX = point.x; mouseStartY = point.y; isDragging = true; e.preventDefault(); }; const drag = (e) => { if (!isDragging) return; e.preventDefault(); const point = getPoint(e); // 清除动画 transform 与原有定位,改用绝对坐标 target.style.transform = 'none'; target.style.margin = '0'; target.style.right = 'auto'; target.style.left = (elemStartX + point.x - mouseStartX) + 'px'; target.style.top = (elemStartY + point.y - mouseStartY) + 'px'; }; const dragEnd = () => { isDragging = false; }; handle.addEventListener('mousedown', dragStart); document.addEventListener('mousemove', drag); document.addEventListener('mouseup', dragEnd); handle.addEventListener('touchstart', dragStart, { passive: false }); document.addEventListener('touchmove', drag, { passive: false }); document.addEventListener('touchend', dragEnd, { passive: false }); } /** 兼容旧调用:句柄默认为容器内的 #dragHandle */ function addDragFunctionality(container) { makeDraggable(container && container.querySelector('#dragHandle'), container); } // 挂载到公共 UI 层:模块一与模块二是相互隔离的作用域, // 模块二(自动评教)通过 window.NJUI.makeDraggable 复用同一份拖拽实现 window.NJUI = window.NJUI || {}; window.NJUI.makeDraggable = makeDraggable; // ===== src/ui/window.js ================================================ // ==================== 窗口能力(拖动 / 缩放 / 记忆) ==================== /** * 为元素添加八方向缩放 * @param {HTMLElement} target 目标窗口 * @param {Object} [options] * @param {number} [options.minWidth] * @param {number} [options.minHeight] * @param {string[]} [options.edges] 需要启用的方向,默认八向全开 * @param {Function} [options.onEnd] 缩放结束回调 */ function makeResizable(target, options = {}) { if (!target) return; const minWidth = options.minWidth || 280; const minHeight = options.minHeight || 160; const edges = options.edges || ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']; // 避免重复挂载 if (target.querySelector('.nju-resize-layer')) return; let active = null; const onMove = (e) => { if (!active) return; const dx = e.clientX - active.startX; const dy = e.clientY - active.startY; let { left, top, width, height } = active; const edge = active.edge; if (edge.indexOf('e') !== -1) width = Math.max(minWidth, active.width + dx); if (edge.indexOf('s') !== -1) height = Math.max(minHeight, active.height + dy); if (edge.indexOf('w') !== -1) { width = Math.max(minWidth, active.width - dx); left = active.left + (active.width - width); } if (edge.indexOf('n') !== -1) { height = Math.max(minHeight, active.height - dy); top = active.top + (active.height - height); } // 视口边界约束 const pad = 6; if (left < pad) { width += left - pad; left = pad; } if (top < pad) { height += top - pad; top = pad; } const maxRight = window.innerWidth - pad; const maxBottom = window.innerHeight - pad; if (left + width > maxRight) width = maxRight - left; if (top + height > maxBottom) height = maxBottom - top; target.style.left = left + 'px'; target.style.top = top + 'px'; target.style.width = Math.max(minWidth, width) + 'px'; target.style.height = Math.max(minHeight, height) + 'px'; target.style.right = 'auto'; target.style.bottom = 'auto'; target.style.maxWidth = 'none'; target.style.maxHeight = 'none'; e.preventDefault(); }; const onUp = () => { if (!active) return; active = null; document.removeEventListener('pointermove', onMove); document.removeEventListener('pointerup', onUp); if (options.onEnd) options.onEnd(); }; const onDown = (edge) => (e) => { if (e.button !== undefined && e.button !== 0) return; const rect = target.getBoundingClientRect(); active = { edge, startX: e.clientX, startY: e.clientY, left: rect.left, top: rect.top, width: rect.width, height: rect.height }; target.style.transform = 'none'; target.style.right = 'auto'; target.style.bottom = 'auto'; target.style.margin = '0'; e.preventDefault(); e.stopPropagation(); document.addEventListener('pointermove', onMove); document.addEventListener('pointerup', onUp); }; const layer = document.createElement('div'); layer.className = 'nju-resize-layer'; edges.forEach((edge) => { const handle = document.createElement('div'); handle.className = 'nju-resize-handle nju-resize-' + edge; handle.addEventListener('pointerdown', onDown(edge)); layer.appendChild(handle); }); target.appendChild(layer); } /** * 启用完整窗口行为:拖动、八向缩放、视口约束、位置/尺寸记忆、双击标题栏最大化 * @param {Object} config * @param {string} config.id 用于记忆位置与尺寸 * @param {HTMLElement} config.target 窗口容器 * @param {HTMLElement} config.handle 拖动句柄(标题栏) * @param {number} [config.minWidth] * @param {number} [config.minHeight] * @param {string[]} [config.edges] */ function enableWindow(config) { const { id, target, handle } = config || {}; if (!target || !handle) return null; const minWidth = config.minWidth || 280; const minHeight = config.minHeight || 160; const storageKey = id ? ('njust_win_' + id) : null; // 恢复位置与尺寸 if (storageKey) { try { const saved = JSON.parse(localStorage.getItem(storageKey) || 'null'); const inViewport = saved && saved.left >= 0 && saved.left < window.innerWidth - 60 && saved.top >= 0 && saved.top < window.innerHeight - 40 && saved.width >= minWidth && saved.height >= minHeight; if (inViewport) { target.style.left = saved.left + 'px'; target.style.top = saved.top + 'px'; target.style.width = saved.width + 'px'; target.style.height = saved.height + 'px'; target.style.right = 'auto'; target.style.bottom = 'auto'; } } catch (e) { /* 忽略损坏的缓存 */ } } const persist = () => { if (!storageKey) return; const rect = target.getBoundingClientRect(); try { localStorage.setItem(storageKey, JSON.stringify({ left: Math.round(rect.left), top: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) })); } catch (e) { /* 忽略配额错误 */ } }; let pressing = false; let dragging = false; let justDragged = false; let startX = 0, startY = 0, startLeft = 0, startTop = 0; const onMove = (e) => { if (!pressing) return; const dx = e.clientX - startX; const dy = e.clientY - startY; // 移动超过阈值才判定为拖动,避免吞掉标题栏上的点击(如折叠) if (!dragging && Math.abs(dx) < 3 && Math.abs(dy) < 3) return; dragging = true; const rect = target.getBoundingClientRect(); const pad = 4; const maxLeft = Math.max(pad, window.innerWidth - rect.width - pad); const maxTop = Math.max(pad, window.innerHeight - 40); const left = Math.min(Math.max(pad, startLeft + dx), maxLeft); const top = Math.min(Math.max(pad, startTop + dy), maxTop); target.style.left = left + 'px'; target.style.top = top + 'px'; e.preventDefault(); }; const onUp = () => { if (!pressing) return; pressing = false; if (dragging) { justDragged = true; setTimeout(() => { justDragged = false; }, 0); persist(); } dragging = false; document.removeEventListener('pointermove', onMove); document.removeEventListener('pointerup', onUp); }; const onDown = (e) => { // 交互控件不触发拖动 if (e.target.closest('.nju-close, .nju-window-actions, .nju-resize-handle, select, input, button, a')) return; if (e.button !== undefined && e.button !== 0) return; const rect = target.getBoundingClientRect(); startX = e.clientX; startY = e.clientY; startLeft = rect.left; startTop = rect.top; pressing = true; target.style.right = 'auto'; target.style.bottom = 'auto'; target.style.margin = '0'; document.addEventListener('pointermove', onMove); document.addEventListener('pointerup', onUp); }; // 拖动结束后抑制本次 click,避免误触标题栏的折叠/切换 handle.addEventListener('click', (e) => { if (!justDragged) return; e.stopPropagation(); e.preventDefault(); }, true); handle.addEventListener('pointerdown', onDown); // 双击标题栏:最大化 / 还原 let maximized = false; let restoreRect = null; handle.addEventListener('dblclick', () => { const rect = target.getBoundingClientRect(); if (!maximized) { restoreRect = { left: rect.left, top: rect.top, width: rect.width, height: rect.height }; target.style.transform = 'none'; target.style.left = '8px'; target.style.top = '8px'; target.style.width = (window.innerWidth - 16) + 'px'; target.style.height = (window.innerHeight - 16) + 'px'; maximized = true; } else { const r = restoreRect || { left: 40, top: 40, width: 480, height: 420 }; target.style.left = r.left + 'px'; target.style.top = r.top + 'px'; target.style.width = r.width + 'px'; target.style.height = r.height + 'px'; maximized = false; } persist(); }); makeResizable(target, { minWidth, minHeight, edges: config.edges, onEnd: persist }); // 视口尺寸变化时把窗口拉回可见区域 window.addEventListener('resize', () => { const rect = target.getBoundingClientRect(); if (rect.left > window.innerWidth - 60 || rect.top > window.innerHeight - 40) { target.style.left = Math.max(4, Math.min(rect.left, window.innerWidth - 80)) + 'px'; target.style.top = Math.max(4, Math.min(rect.top, window.innerHeight - 60)) + 'px'; } }); return { persist }; } window.NJUI = window.NJUI || {}; window.NJUI.makeResizable = makeResizable; window.NJUI.enableWindow = enableWindow; // ===== src/core/qiangzhi.js ============================================ // ==================== 检测强智科技页面 ==================== function checkQiangzhiPage() { try { const pageTitle = document.title || ''; if (pageTitle.includes('强智科技教务系统概念版')) { Logger.warn('检测到强智科技概念版页面,显示登录引导'); const content = `
当前页面无法登录
这是强智科技教务系统概念版,仅供展示,不提供登录功能。请前往以下入口登录教务系统。
智慧理工门户登录 校外可用 · 推荐 教务处登录入口 仅限校园网
温馨提示
教务处直连入口(202.119.81.112 / 113)已限制为仅校园网可访问, 校外请优先使用智慧理工门户登录。
验证码区分大小写,通常为小写字母。
`; try { createUnifiedModal('南理工教务增强助手 V2', content, 'warning'); } catch (e) { Logger.error('创建强智科技页面提示弹窗失败:', e); } return true; } return false; } catch (e) { Logger.error('检测强智科技页面失败:', e); return false; } } // ===== src/core/networkNotice.js ======================================= // ==================== 校园网访问限制提示 ==================== /** * 教务处直连入口(202.119.81.112 / 202.119.81.113)已调整为仅校园网可访问。 * 在校内访问成功时给出一次轻量提示,引导校外用户改用智慧理工门户登录。 * 提示每天最多出现一次,关闭后当天不再显示。 */ const SMART_CAMPUS_LOGIN_URL = 'https://bkjw.njust.edu.cn/njlgdx/indexsso.jsp'; function showCampusNetworkNotice() { try { const host = window.location.hostname; const isDirectJwc = (host === '202.119.81.112' || host === '202.119.81.113'); if (!isDirectJwc) return; const KEY = 'njust_campus_notice_date'; const today = new Date().toISOString().slice(0, 10); if (localStorage.getItem(KEY) === today) return; // 当天已提示过 if (document.getElementById('njust-network-notice')) return; const bar = document.createElement('div'); bar.id = 'njust-network-notice'; bar.style.cssText = ` position: fixed; top: 0; left: 0; right: 0; z-index: var(--nju-z-topbar); background: var(--nju-warning-soft); color: var(--nju-text); border-bottom: 1px solid rgba(255, 149, 0, 0.35); padding: 9px 16px; font-family: var(--nju-font); font-size: var(--nju-fs-md); display: flex; align-items: center; justify-content: center; gap: 10px; box-shadow: var(--nju-shadow-sm); `; bar.innerHTML = ` 教务处直连入口(202.119.81.112 / 113)仅限校园网访问,校外请使用 智慧理工门户 登录教务系统。 `; (document.body || document.documentElement).appendChild(bar); const closeBtn = bar.querySelector('#njust-network-notice-close'); if (closeBtn) { closeBtn.addEventListener('click', () => { localStorage.setItem(KEY, today); bar.remove(); }); } Logger.info('已显示校园网访问限制提示'); } catch (e) { Logger.warn('显示校园网访问限制提示失败:', e); } } // ===== src/ui/promoBanner.js =========================================== // ==================== 梨课程推荐提示 ==================== function showPromoBanner() { // 检查是否已存在 if (document.getElementById('njust-promo-line')) return; // 查找底部版权信息区域(支持两种页面结构) let insertTarget = null; let isLoginPage = false; // 1. 登录后的页面:Footer1_divCopyright const footer = document.getElementById('Footer1_divCopyright'); if (footer) { insertTarget = footer; } // 2. 登录页面:包含 class="copyright" 的 td 元素 if (!insertTarget) { const copyrightLink = document.querySelector('a.copyright[href*="qzdatasoft"]'); if (copyrightLink && copyrightLink.parentElement && copyrightLink.parentElement.tagName === 'TD') { insertTarget = copyrightLink.parentElement; isLoginPage = true; } } if (!insertTarget) return; // 创建推荐文本行(纯文本样式,与页面风格融合) const promoLine = document.createElement('div'); promoLine.id = 'njust-promo-line'; if (!isLoginPage) { promoLine.className = 'Nsb_pw'; } promoLine.style.cssText = ` padding: 8px 20px; text-align: center; font-size: 12px; color: var(--nju-text-2); `; promoLine.innerHTML = ` 推荐:尝试最新开发,支持本科生/研究生的 梨课程。 前往 m.njust.store (支持 Android / HarmonyOS / iOS / PC) `; // 在目标元素上方插入 insertTarget.parentNode.insertBefore(promoLine, insertTarget); } // ===== src/core/dataSource.js ========================================== // ==================== 数据加载(智能切源)==================== // fix⑤: 无论第几个数据源成功,均进行缓存;缓存读取也遍历所有 URL function loadJSONWithFallback(urls) { return new Promise((resolve, reject) => { const urlArray = Array.isArray(urls) ? urls : [urls]; const fileName = urlArray[0].includes('xxk') ? '选修课分类' : '课程大纲'; Logger.info(`开始加载 ${fileName},共 ${urlArray.length} 个数据源`); // fix⑤: 先遍历所有 URL,尝试从缓存中命中任意一个 for (const url of urlArray) { const cachedData = CacheManager.get(url); if (cachedData) { Logger.info(`从缓存读取 ${fileName} 成功 (${url})`); resolve(cachedData); return; } } // 缓存全部未命中,依次请求网络 let currentIndex = 0; function tryNextUrl() { if (currentIndex >= urlArray.length) { Logger.error(`${fileName} 所有数据源均不可用`); reject(new Error(`所有数据源都不可用: ${fileName}`)); return; } const currentUrl = urlArray[currentIndex++]; Logger.info(`尝试数据源 ${currentIndex}/${urlArray.length}: ${currentUrl}`); const startTime = Date.now(); GM_xmlhttpRequest({ method: 'GET', url: currentUrl, timeout: 10000, onload(response) { const loadTime = Date.now() - startTime; try { const json = JSON.parse(response.responseText); // fix⑤: 无论哪个数据源成功,均以该 URL 为键进行缓存 const cached = CacheManager.set(currentUrl, json); Logger.info( `数据源 ${currentIndex} 请求成功 (${loadTime}ms, ${response.responseText.length}B, 缓存${cached ? '已保存' : '失败'})` ); resolve(json); } catch (e) { Logger.error(`JSON 解析失败: ${currentUrl}`, e); tryNextUrl(); } }, onerror() { Logger.warn(`数据源 ${currentIndex} 请求失败 (${Date.now() - startTime}ms): ${currentUrl}`); tryNextUrl(); }, ontimeout() { Logger.warn(`数据源 ${currentIndex} 请求超时: ${currentUrl}`); tryNextUrl(); } }); } tryNextUrl(); }); } function loadJSON(url) { return loadJSONWithFallback(Array.isArray(url) ? url : [url]); } // ==================== 构建课程映射 ==================== function buildCourseMaps(categoryList, outlineList) { try { let categoryCount = 0, outlineCount = 0; if (Array.isArray(categoryList)) { categoryList.forEach(item => { try { if (item && item.course_code && item.category) { courseCategoryMap[item.course_code.trim()] = item.category; categoryCount++; } } catch (e) { Logger.warn('处理分类数据项时出错:', e); } }); } else { Logger.warn('分类数据不是数组格式:', typeof categoryList); } if (Array.isArray(outlineList)) { outlineList.forEach(item => { try { if (item && item.course_code && item.id) { courseOutlineMap[item.course_code.trim()] = item.id; outlineCount++; } } catch (e) { Logger.warn('处理大纲数据项时出错:', e); } }); } else { Logger.warn('大纲数据不是数组格式:', typeof outlineList); } Logger.info(`课程映射构建完成: 选修课类别 ${categoryCount} 条,课程大纲 ${outlineCount} 条`); } catch (e) { Logger.error('构建课程映射表失败:', e); if (typeof courseCategoryMap !== 'object') courseCategoryMap = {}; if (typeof courseOutlineMap !== 'object') courseOutlineMap = {}; } } // ===== src/ui/creditsPanel.js ========================================== // ==================== 学分统计悬浮窗 ==================== function createCreditSummaryWindow() { try { const container = document.createElement('div'); container.id = 'creditSummaryWindow'; container.className = 'nju-window'; container.style.cssText = ` top: 40px; right: 40px; width: 460px; height: 520px; z-index: var(--nju-z-panel); `; container.innerHTML = `
南理工教务增强助手 V2
✕
分类口径:加载中…
大纲链接
  • 对照个人培养方案核实具体修课要求
  • 选修课类别统计仅包含已知分类的通识教育选修课
  • 课程分类信息可能随时更新,请以教务处最新通知为准
  • 请查看 增强助手官网 获取使用说明
    `; // 统一使用公共拖拽实现(句柄为本窗体的 creditDragHandle) enableWindow({ id: 'credits', target: container, handle: container.querySelector('#creditDragHandle'), minWidth: 360, minHeight: 240 }); document.body.appendChild(container); // 绑定关闭按钮事件 const creditCloseBtn = container.querySelector('#creditCloseBtn'); if (creditCloseBtn) { creditCloseBtn.addEventListener('click', () => container.remove()); // hover 样式由 base.css 的 .nju-close 统一提供 } // 培养方案口径显示与手动切换 try { const versionText = container.querySelector('#xxkVersionText'); const versionSelect = container.querySelector('#xxkVersionSelect'); const info = resolveCategoryVersion(); if (versionText) { versionText.textContent = `分类口径:${info.version} 版(${describeVersionSource(info)})`; } if (versionSelect) { versionSelect.value = localStorage.getItem(KEY_XXK_VERSION) || ''; versionSelect.addEventListener('change', () => { const value = versionSelect.value; if (value) localStorage.setItem(KEY_XXK_VERSION, value); else localStorage.removeItem(KEY_XXK_VERSION); CacheManager.clear(); Logger.info(`分类口径已切换为「${value || '按学号自动'}」,正在重新加载数据`); setTimeout(() => location.reload(), 300); }); } const outlineSelect = container.querySelector('#outlineModeSelect'); if (outlineSelect) { outlineSelect.value = getOutlineMode(); outlineSelect.addEventListener('change', () => { setOutlineMode(outlineSelect.value); Logger.info(`大纲链接显示方式已切换为「${outlineSelect.options[outlineSelect.selectedIndex].text}」`); setTimeout(() => location.reload(), 200); }); } } catch (e) { Logger.warn('渲染分类口径控件失败:', e); } Logger.debug('学分统计弹窗创建完成'); return container; } catch (e) { Logger.error('创建学分统计弹窗失败:', e); return null; } } // ==================== 学分统计更新 ==================== function updateCreditSummary() { try { const creditSummaryDiv = document.getElementById('creditSummary'); if (!creditSummaryDiv) { Logger.warn('未找到学分统计容器'); return; } const creditsByType = {}; const creditsByCategory = {}; const tables = document.querySelectorAll('table'); tables.forEach(table => { table.querySelectorAll('tr').forEach(row => { const tds = row.querySelectorAll('td'); if (tds.length < 11) return; const courseCode = tds[2].textContent.trim(); const credit = parseFloat(tds[6].textContent) || 0; const courseType = tds[10].textContent.trim(); const categoryDiv = tds[2].querySelector('[data-category-inserted]'); let category = null; if (categoryDiv) { category = categoryDiv.textContent.trim() || null; } if (courseType) { if (!creditsByType[courseType]) creditsByType[courseType] = { credits: 0, count: 0 }; creditsByType[courseType].credits += credit; creditsByType[courseType].count++; } if (category) { if (!creditsByCategory[category]) creditsByCategory[category] = { credits: 0, count: 0 }; creditsByCategory[category].credits += credit; creditsByCategory[category].count++; } }); }); const totalCreditsByType = Object.values(creditsByType).reduce((s, d) => s + d.credits, 0); const totalCountByType = Object.values(creditsByType).reduce((s, d) => s + d.count, 0); const totalCreditsByCategory = Object.values(creditsByCategory).reduce((s, d) => s + d.credits, 0); const totalCountByCategory = Object.values(creditsByCategory).reduce((s, d) => s + d.count, 0); let summaryHTML = `
    `; summaryHTML += `
    按课程性质统计
    `; summaryHTML += `
    总计 ${totalCreditsByType.toFixed(1)} 学分 ${totalCountByType} 门
    `; for (const [type, data] of Object.entries(creditsByType)) { summaryHTML += `
    ${type} ${data.credits.toFixed(1)} 学分 ${data.count} 门
    `; } summaryHTML += `
    `; if (Object.keys(creditsByCategory).length > 0) { summaryHTML += `
    `; summaryHTML += `
    按选修课类别统计
    `; summaryHTML += `
    总计 ${totalCreditsByCategory.toFixed(1)} 学分 ${totalCountByCategory} 门
    `; for (const [category, data] of Object.entries(creditsByCategory)) { summaryHTML += `
    ${category} ${data.credits.toFixed(1)} 学分 ${data.count} 门
    `; } summaryHTML += `
    `; } creditSummaryDiv.innerHTML = summaryHTML || '暂无数据'; Logger.debug('学分统计更新完成'); } catch (e) { Logger.error('更新学分统计失败:', e); const el = document.getElementById('creditSummary'); if (el) el.innerHTML = '
    学分统计更新失败
    '; } } /** * ── 课程信息增强核心逻辑 ─────────────────────────────────────── * 负责解析教务系统的表格 DOM,并根据映射表插入大纲链接、选修课类别等信息。 */ // ===== src/core/courseEnhance.js ======================================= function processAllTables() { try { const tables = document.querySelectorAll('table'); // 页面类型识别 const isGradePage = window.location.pathname.includes('/njlgdx/kscj/cjcx_list'); const isSchedulePage = window.location.pathname.includes('xskb_list.do') && document.title.includes('学期理论课表'); const isSmartCampus = window.location.href.includes('bkjw.njust.edu.cn'); let processedTables = 0, processedRows = 0, enhancedCourses = 0; tables.forEach(table => { try { // 课表页面只处理 id 为 dataList 的主表格 if (isSchedulePage && table.id !== 'dataList') return; const rows = table.querySelectorAll('tr'); processedTables++; rows.forEach(row => { try { const tds = row.querySelectorAll('td'); if (tds.length < 3) return; // 略过非数据行 processedRows++; let courseCodeTd, courseCode; // 不同页面的课程代码提取逻辑差异化处理 if (isGradePage) { courseCodeTd = tds[2]; courseCode = courseCodeTd ? courseCodeTd.textContent.trim() : ''; } else if (isSchedulePage) { courseCodeTd = tds[1]; courseCode = courseCodeTd ? courseCodeTd.textContent.trim() : ''; } else { // 通用逻辑:提取形如 "课程名
    课程代码" 的结构 courseCodeTd = tds[1]; if (courseCodeTd && courseCodeTd.innerHTML) { const parts = courseCodeTd.innerHTML.split('
    '); if (parts.length === 2) courseCode = parts[1].trim(); else return; } else return; } if (!courseCode) return; let courseEnhanced = false; // 1. 插入选修课类别(如:人文素养、自然科学等) try { if (courseCodeTd && !courseCodeTd.querySelector('[data-category-inserted]')) { const category = courseCategoryMap[courseCode]; if (category) { const catDiv = document.createElement('div'); catDiv.setAttribute('data-category-inserted', '1'); catDiv.style.color = '#28a745'; catDiv.style.fontWeight = 'bold'; catDiv.style.marginTop = '4px'; catDiv.textContent = category; courseCodeTd.appendChild(catDiv); courseEnhanced = true; } } } catch (e) { Logger.warn('添加课程类别时出错:', e); } // 2. 插入老师说明(将 的 title 属性显性化) try { if (!isGradePage && !isSchedulePage && courseCodeTd && courseCodeTd.title && !courseCodeTd.querySelector('[data-title-inserted]')) { const titleDiv = document.createElement('div'); titleDiv.setAttribute('data-title-inserted', '1'); titleDiv.style.color = '#666'; titleDiv.style.fontSize = '13px'; titleDiv.style.marginTop = '4px'; titleDiv.style.fontStyle = 'italic'; titleDiv.textContent = `老师说明: ${courseCodeTd.title}`; courseCodeTd.appendChild(titleDiv); courseEnhanced = true; } } catch (e) { Logger.warn('添加老师说明时出错:', e); } // 3. 插入教学大纲链接(原始 + 镜像) try { if (courseCodeTd && !courseCodeTd.querySelector('[data-outline-inserted]')) { const outlineDiv = document.createElement('div'); outlineDiv.setAttribute('data-outline-inserted', '1'); outlineDiv.style.marginTop = '4px'; outlineDiv.style.fontSize = '13px'; // 三个链接可能较长,允许自动换行 outlineDiv.style.display = 'flex'; outlineDiv.style.flexWrap = 'wrap'; outlineDiv.style.gap = '2px'; const realId = courseOutlineMap[courseCode]; const makeOutlineLink = (href, text, title) => { const link = document.createElement('a'); link.href = href; link.textContent = text; link.target = '_blank'; link.rel = 'noopener noreferrer'; link.style.color = 'var(--nju-primary)'; link.style.textDecoration = 'none'; link.style.marginLeft = '2px'; if (title) link.title = title; return link; }; const outlineMode = getOutlineMode(); if (outlineMode !== 'none') { const showOriginal = (outlineMode === 'both' || outlineMode === 'original') && !!realId; const showMirror = (outlineMode === 'both' || outlineMode === 'mirror'); if (showOriginal) { // 智慧理工平台大纲:内容与教务处一致,页面标题显示为 2018 版本,校内外均可访问 outlineDiv.appendChild(makeOutlineLink( `https://bkjw.njust.edu.cn/njlgdx/view/pyfa/kcdg_View.jsp?jx02id=${realId}`, '[课程大纲1]', '智慧理工平台大纲:页面标题显示为 2018 版本,内容与教务处一致,校内外均可访问' )); // 老教务网站大纲:页面标题显示为 2022 版本,仅校园网可访问 outlineDiv.appendChild(makeOutlineLink( `//202.119.81.112:8080/kcxxAction.do?method=kcdgView&jx02id=${realId}&isentering=0`, '[课程大纲2]', '老教务网站大纲:页面标题显示为 2022 版本,仅校园网可访问(内容与智慧理工版本基本一致)' )); } if (showMirror) { // 镜像站已收录全部课程(以课程号为唯一 key),不依赖 kcdg.json 映射, // 即使该课程未上传大纲,链接依然可以访问 // 未收录官方大纲时,把入口称为「课程详情」更贴切 outlineDiv.appendChild(makeOutlineLink( `https://kcdg.njust.store/html/${encodeURIComponent(courseCode)}.html`, realId ? '[大纲镜像]' : '[课程详情]', realId ? '课程大纲镜像站(校内外均可访问)' : '课程详情:该课程未收录官方大纲,可在镜像站查看课程信息(校内外均可访问)' )); } courseCodeTd.appendChild(outlineDiv); courseEnhanced = true; } } } catch (e) { Logger.warn('添加课程大纲链接时出错:', e); } if (courseEnhanced) enhancedCourses++; } catch (e) { Logger.warn('处理表格行时出错:', e); } }); } catch (e) { Logger.warn('处理表格时出错:', e); } }); Logger.info(`表格处理完成: ${processedTables}个表格, ${processedRows}行, 增强${enhancedCourses}门课程`); // 成绩页面额外执行学分实时汇总 if (isGradePage) updateCreditSummary(); } catch (e) { Logger.error('处理页面表格失败:', e); } } /** * ── 登录保活与自动修复系统 ─────────────────────────────────────── * 解决教务系统频繁掉线、重复登录导致的报错页面。 */ // ===== src/core/loginKeepAlive.js ====================================== function checkLoginErrorAndRefresh() { try { const pageTitle = document.title || ''; const pageContent = document.body ? document.body.textContent : ''; // 匹配典型的教务处报错关键词 const isLoginError = pageTitle.includes('出错页面') && (pageContent.includes('您登录后过长时间没有操作') || pageContent.includes('您的用户名已经在别处登录') || pageContent.includes('请重新输入帐号,密码后,继续操作')); if (isLoginError) { Logger.warn('检测到登录超时或重复登录错误页面,正在自动刷新...'); performLoginRefresh(true); return true; } return false; } catch (e) { Logger.error('检测登录错误页面失败:', e); return false; } } /** * 执行静默登录刷新 * 原理:通过一个隐藏的 iframe 请求教务系统的一个轻量级页面,利用浏览器自动携带的 Cookie 维持/刷新 Session。 */ function performLoginRefresh(forceRefresh = false) { const currentUrl = window.location.href; try { let baseUrl; if (currentUrl.includes('njlgdx/')) { baseUrl = currentUrl.substring(0, currentUrl.indexOf('njlgdx/')); } else { const urlObj = new URL(currentUrl); baseUrl = `${urlObj.protocol}//${urlObj.host}/`; } // 使用“课程大纲查询”作为刷新页面(权限要求低且加载快) const refreshUrl = baseUrl + 'njlgdx/pyfa/kcdgxz'; Logger.info('使用隐藏 iframe 刷新登录状态:', refreshUrl); const iframe = document.createElement('iframe'); iframe.style.cssText = 'position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0;visibility:hidden;border:none;'; iframe.src = refreshUrl; iframe.onload = () => { Logger.info('登录状态刷新请求完成'); setTimeout(() => { if (iframe.parentNode) iframe.parentNode.removeChild(iframe); }, 1000); }; iframe.onerror = () => { Logger.warn('登录状态刷新请求失败'); if (iframe.parentNode) iframe.parentNode.removeChild(iframe); if (forceRefresh) Logger.error('登录状态刷新失败,请手动重新点击选课中心 - 课程总库'); }; document.body.appendChild(iframe); // 10秒兜底清理,防止网络挂起 setTimeout(() => { if (iframe.parentNode) iframe.parentNode.removeChild(iframe); }, 10000); } catch (e) { Logger.error('自动刷新登录状态失败:', e); } } /** * 定时自动保活逻辑 * 策略:仅在主框架页面执行,且 5 分钟内不重复触发。 */ function autoRefreshLoginStatus() { try { const currentUrl = window.location.href; if (!currentUrl.includes('njlgdx/framework/main.jsp')) return; const lastRefreshKey = 'njust_last_login_refresh'; const lastRefreshTime = localStorage.getItem(lastRefreshKey); const now = Date.now(); const refreshInterval = 5 * 60 * 1000; // 5分钟间隔 if (lastRefreshTime && (now - parseInt(lastRefreshTime)) < refreshInterval) { Logger.debug('距上次刷新不足5分钟,跳过'); return; } // 更新最后刷新时间戳 localStorage.setItem(lastRefreshKey, now.toString()); // fix⑦: 使用 BroadcastChannel 通知其他同源标签页同步刷新时间,避免多标签页并发请求 if (typeof BroadcastChannel !== 'undefined') { const bc = new BroadcastChannel('njust_login_refresh'); bc.postMessage({ type: 'refreshing', ts: now }); bc.close(); } Logger.info('检测到主框架页面,开始刷新登录状态'); performLoginRefresh(false); } catch (e) { Logger.error('自动刷新登录状态检查失败:', e); } } /** * ── 脚本入口初始化 ────────────────────────────────────────────── */ // ===== src/core/main.js ================================================ async function init() { try { Logger.info('开始执行主要逻辑'); // 强智概念版拦截 if (checkQiangzhiPage()) { Logger.info('强智科技页面检测完成,脚本退出'); return; } const currentUrl = window.location.href; const isSmartCampus = currentUrl.includes('bkjw.njust.edu.cn'); if (isSmartCampus) { Logger.warn('检测到智慧理工平台,课程大纲功能将受限'); } // 教务处直连入口仅限校园网,提示校外改走智慧理工门户 showCampusNetworkNotice(); // 1. 登录保活与状态检查 autoRefreshLoginStatus(); checkLoginErrorAndRefresh(); // 2. 加载远程配置数据(按学号对应的入学年份自适应培养方案口径) Logger.info('开始加载数据'); const versionInfo = resolveCategoryVersion(); Logger.info(`选修课分类口径:${versionInfo.version} 版(${describeVersionSource(versionInfo)})`); const [categoryData, outlineData] = await Promise.all([ loadJSON(getCategoryURLs(versionInfo.version)), loadJSON(OUTLINE_URLS) ]); // 3. 构建索引并执行初次处理 Logger.info('数据加载完成,构建映射表'); buildCourseMaps(categoryData, outlineData); if (window.location.pathname.includes('/njlgdx/kscj/cjcx_list')) { createCreditSummaryWindow(); } processAllTables(); /** * 4. 动态监听系统 * 解决教务系统通过 AJAX 异步切换页面(如点击菜单)导致脚本失效的问题。 */ let isProcessing = false; const observer = new MutationObserver((mutations) => { try { if (isProcessing) return; const hasRelevantChanges = mutations.some(mutation => { try { if (mutation.type !== 'childList') return false; for (const node of mutation.addedNodes) { if (node.nodeType !== Node.ELEMENT_NODE) continue; // 忽略脚本自己插入的 DOM if (node.hasAttribute && (node.hasAttribute('data-category-inserted') || node.hasAttribute('data-title-inserted') || node.hasAttribute('data-outline-inserted'))) { return false; } // 只关注表格类变更 if (node.tagName === 'TABLE' || node.tagName === 'TR' || node.tagName === 'TD') { return true; } } return false; } catch (e) { Logger.warn('检查页面变化时出错:', e); return false; } }); if (hasRelevantChanges && !checkQiangzhiPage()) { isProcessing = true; try { processAllTables(); } catch (e) { Logger.error('重新处理表格失败:', e); } finally { // 节流处理,防止频繁触发 setTimeout(() => { isProcessing = false; }, 100); } } } catch (e) { Logger.error('MutationObserver 回调执行失败:', e); isProcessing = false; } }); try { observer.observe(document.body, { childList: true, subtree: true }); } catch (e) { Logger.error('启动页面变化监听器失败:', e); } Logger.info('南理工教务增强助手加载成功!'); } catch (err) { Logger.error('初始化失败:', err); } } // 延迟 1 秒执行初始化,确保教务系统原始 JS 框架加载完成 setTimeout(init, 1000); // 暴露 Logger 到全局,供模块二使用 window.__NJUST_LOGGER__ = Logger; })(); // ===== src/evaluate/consts.js ========================================== // ================================================================ // 【模块二】自动评教助手 V1 // 功能:自动填分、批量保存、批量提交、分值实时预览 // 适用页面:学生评教入口 (xspj_find.do)、课程列表 (xspj_list.do)、评价详情 (xspj_edit.do) // ================================================================ (function () { 'use strict'; // ── 常量定义 ───────────────────────────────────────────────────── // 存储键名,用于跨页面同步状态 const KEY_STORE = 'njust_eval_v1_store'; // 核心存储:课程状态、评分选项等 const KEY_RUNNING = 'njust_eval_running'; // 全局标志:是否处于“开始评价并保存”流水线中 const KEY_BUSY = 'njust_eval_busy'; // 互斥锁:防止多个窗口同时执行保存操作 const KEY_CURLIST = 'njust_eval_curlist'; // 当前正在处理的类别 URL const KEY_LOG = 'njust_eval_log'; // 日志存储 const KEY_LOGLVL = 'njust_eval_loglvl'; // 日志显示等级过滤 const KEY_SUBQUEUE = 'njust_eval_subqueue'; // 待提交课程的 URL 队列 const KEY_SUBRUN = 'njust_eval_subrun'; // 全局标志:是否处于“提交已评课程”流水线中 const KEY_SUBBSY = 'njust_eval_subbsy'; // 互斥锁:防止多个窗口同时执行提交操作 const KEY_BUSY_TS = 'njust_eval_busy_ts'; // 保存锁的时间戳(用于超时自动恢复) const KEY_SUBBSY_TS = 'njust_eval_subbsy_ts'; // 提交锁的时间戳(用于超时自动恢复) const LOCK_TIMEOUT = 90 * 1000; // 锁的存活上限,超过视为流程已中断 // URL 参数,用于传递指令给详情页 const PARAM_AUTO = 'isAutoEval'; // 详情页接收后执行自动填分+保存 const PARAM_SUBMIT = 'isAutoSubmit'; // 详情页接收后执行自动提交 const MAX_LOG = 300; // 日志最大保留条数 // ── 日志系统 ───────────────────────────────────────────────────── // 日志级别与 UI 映射 const LOG_LEVELS = { debug: 0, info: 1, success: 2, warn: 3, error: 4 }; const LOG_LABELS = { debug: 'DBG', info: 'INF', success: 'OK ', warn: 'WRN', error: 'ERR' }; const LOG_ICONS = { debug: 'DBG', info: 'INF', success: 'OK', warn: 'WRN', error: 'ERR' }; // 日志持久化与读取 const loadLogs = () => JSON.parse(localStorage.getItem(KEY_LOG) || '[]'); const clearLogs = () => { localStorage.removeItem(KEY_LOG); renderLogPanel(); }; const getMinLevel = () => { const s = localStorage.getItem(KEY_LOGLVL); return (s && LOG_LEVELS[s] !== undefined) ? s : 'info'; }; const setMinLevel = (l) => { localStorage.setItem(KEY_LOGLVL, l); renderLogPanel(); }; /** * 推送新日志并更新面板 * 同时输出到模块一的 LogPanelUI(如果存在) */ const pushLog = (msg, level = 'info') => { const logs = loadLogs(); logs.push({ ts: new Date().toTimeString().slice(0, 8), msg, level }); if (logs.length > MAX_LOG) logs.splice(0, logs.length - MAX_LOG); localStorage.setItem(KEY_LOG, JSON.stringify(logs)); renderLogPanel(); // 同步输出到模块一的日志面板 if (window.__NJUST_LOGGER__) { const levelMap = { debug: 4, info: 3, success: 3, warn: 2, error: 1 }; const loggerLevel = levelMap[level] || 3; window.__NJUST_LOGGER__.log(loggerLevel, `[评教] ${msg}`); } }; const logInfo = (m) => pushLog(m, 'info'); const logSuccess = (m) => pushLog(m, 'success'); const logError = (m) => pushLog(m, 'error'); /** * 渲染控制面板底部的日志区域(已简化,日志现在显示在模块一的面板中) */ const renderLogPanel = () => { // 日志现在统一显示在模块一的 LogPanelUI 中 // 此函数仅用于内部状态更新,不再渲染独立的日志区块 }; // ── 通用工具函数 ────────────────────────────────────────────────── // HTML 转义防止 XSS const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>'); // 解析 URL 参数 const qp = (url, key) => { try { return new URL(url, location.origin).searchParams.get(key) || ''; } catch { return url.match(new RegExp(`[?&]${key}=([^&]+)`))?.[1] || ''; } }; // 生成课程唯一 Key (课程ID + 教师ID) const courseKey = (url) => { const cid = qp(url, 'jx02id'), tid = qp(url, 'jg0101id'); return cid && tid ? `${cid}__${tid}` : null; }; const appendParam = (url, key, val) => url + (url.includes('?') ? '&' : '?') + key + '=' + val; const withAuto = (url, val) => appendParam(url, PARAM_AUTO, val); const withSubmit = (url) => appendParam(url, PARAM_SUBMIT, 'true'); const roundFloat = (n) => Math.round(n * 1e9) / 1e9; // 解决浮点数精度误差 // 快捷访问 LocalStorage const loadStore = () => JSON.parse(localStorage.getItem(KEY_STORE) || '{}'); const saveStore = (v) => localStorage.setItem(KEY_STORE, JSON.stringify(v)); const loadSubQueue = () => JSON.parse(localStorage.getItem(KEY_SUBQUEUE) || '[]'); const saveSubQueue = (q) => localStorage.setItem(KEY_SUBQUEUE, JSON.stringify(q)); /** * 在控制面板预览当前存储的课程状态 */ const renderStoragePanel = () => { const el = document.getElementById('v80-storage-pre'); if (el) el.textContent = JSON.stringify(loadStore(), null, 2); }; // ===== src/evaluate/evaluateCore.js ==================================== // ── 评价页面核心逻辑 ────────────────────────────────────────────── /** * 收集当前评价页面的所有评分组 (Radio) 及其对应的分值 */ const collectGroups = () => { const groups = {}; document.querySelectorAll('input[type="radio"]').forEach(r => { if (!groups[r.name]) groups[r.name] = []; const idx = r.id.split('_')[1]; // 查找隐藏域中的分值 (pj0601fz_...) const fzEl = document.getElementsByName(`pj0601fz_${idx}_${r.value}`)[0]; groups[r.name].push({ el: r, score: fzEl ? parseFloat(fzEl.value) || 0 : 0 }); }); const gkeys = Object.keys(groups); // 按分值从高到低排序,方便策略选择 gkeys.forEach(k => groups[k].sort((a, b) => b.score - a.score)); return { gkeys, groups }; }; /** * 寻找最适合进行分值扰动的题目索引 * 原则:分值差距最小的题目,扰动对总分影响最小 */ const findPerturbIdx = (gkeys, groups) => { let minDelta = Infinity, perturbIdx = -1; gkeys.forEach((k, i) => { const opts = groups[k]; if (opts.length < 2) return; const delta = roundFloat(opts[0].score - opts[1].score); if (delta < minDelta) { minDelta = delta; perturbIdx = i; } }); return perturbIdx; }; /** * 计算当前页面已勾选选项的总分 */ const calcCurrentTotal = (gkeys, groups) => { let total = 0; gkeys.forEach(k => { const chosen = groups[k].find(o => o.el.checked); if (chosen) total += chosen.score; }); return roundFloat(total); }; /** * 在详情页每个选项后标注具体分值,方便人工微调 */ const ensureValueFields = () => { const { gkeys, groups } = collectGroups(); gkeys.forEach(k => { groups[k].forEach(({ el, score }) => { const idx = el.id.split('_')[1]; const fzEl = document.getElementsByName(`pj0601fz_${idx}_${el.value}`)[0]; if (!fzEl) return; let next = fzEl.nextElementSibling; if (next && next.classList && next.classList.contains('v80-value-chip')) return; const chip = document.createElement('span'); chip.className = 'v80-value-chip'; chip.textContent = `[${score}分]`; fzEl.insertAdjacentElement('afterend', chip); }); }); }; /** * 应用评分策略并勾选 Radio * strategy: highest (最高分), high (次高), mid (中分), low (低分) * 策略中包含“选项去重”逻辑:即在保证总分尽量高的前提下,在某一道题上选择非最高分,避免全满分被系统拦截 */ const applyStrategy = (strategy, gkeys, groups) => { const perturbIdx = findPerturbIdx(gkeys, groups); let total = 0; gkeys.forEach((k, i) => { const opts = groups[k], len = opts.length; let pick = 0; // 默认选最高分,避免策略名异常时不勾选任何项 if (strategy === 'highest') { // 最高分策略:在扰动项选次高,其余全选最高 pick = (i === perturbIdx && len >= 2) ? 1 : 0; } else if (strategy === 'high') { pick = len < 2 ? 0 : (i === perturbIdx) ? 0 : 1; } else if (strategy === 'mid') { const midIdx = Math.floor((len - 1) / 2); pick = (i === perturbIdx && len >= 2) ? (midIdx > 0 ? midIdx - 1 : midIdx + 1) : midIdx; } else if (strategy === 'low') { pick = (i === perturbIdx && len >= 2) ? len - 2 : len - 1; } const chosen = opts[Math.min(pick, len - 1)]; if (chosen) { chosen.el.checked = true; total += chosen.score; } }); return roundFloat(total); }; // ===== src/evaluate/style.js =========================================== // ── 样式注入 ────────────────────────────────────────────────────── const injectCSS = () => { if (document.getElementById('v80-style')) return; const style = document.createElement('style'); style.id = 'v80-style'; style.textContent = ` /* 控制面板主容器 */ #v80-panel { position: fixed; top: 20px; right: 20px; width: 490px; background: var(--nju-bg); border-radius: var(--nju-radius-md); box-shadow: var(--nju-shadow-md); z-index: var(--nju-z-panel); font-family: var(--nju-font); display: flex; flex-direction: column; border: 1px solid var(--nju-border); max-height: 90vh; overflow: hidden; transition: transform 0.25s ease; font-size: var(--nju-fs-md); color: var(--nju-text); } #v80-panel.wide { width: 640px; } #v80-header { padding: 11px 14px; background: var(--nju-bg-subtle); border-bottom: 1px solid var(--nju-border); cursor: move; display: flex; align-items: center; gap: 8px; user-select: none; flex-shrink: 0; } #v80-header b { flex: 1; font-size: 14px; color: var(--nju-text); } #v80-action-bar { padding: 10px 14px 8px; border-bottom: 1px solid var(--nju-border); background: var(--nju-bg); flex-shrink: 0; } #v80-submit-hint { font-size: 11px; padding: 6px 10px; border-radius: 6px; margin-bottom: 8px; background: #f0fff4; color: #276749; border: 1px solid #c6f6d5; display: none; line-height: 1.6; } #v80-submit-hint.visible { display: block; } .btn-row { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 7px; } #v80-body { padding: 10px 14px; overflow-y: auto; flex: 1; } /* 列表项卡片样式 */ .entry-card, .ci { display: flex; align-items: center; gap: 8px; padding: 9px 12px; border-radius: var(--nju-radius-sm); border: 1px solid var(--nju-border); margin-bottom: 7px; background: var(--nju-bg-subtle); } .ci { padding: 8px 10px; margin-bottom: 6px; border-color: var(--nju-border); } .entry-label, .ci-name { flex: 1; font-weight: 500; color: var(--nju-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* 入口数量统计(此前缺少对应规则) */ .entry-count { font-size: var(--nju-fs-xs); color: var(--nju-text-3); } .ci-teacher { color: #718096; white-space: nowrap; } .ci-zpf { color: #276749; font-size: 11px; background: #f0fff4; padding: 1px 7px; border-radius: 8px; border: 1px solid #c6f6d5; white-space: nowrap; } /* 状态标签 */ .entry-st-done, .st-submitted { font-size: 11px; padding: 1px 8px; border-radius: 8px; background: #f0fff4; color: #276749; border: 1px solid #c6f6d5; white-space: nowrap; } .entry-st-wait, .st-wait { font-size: 11px; padding: 1px 8px; border-radius: 8px; background: #fffaf0; color: #c05621; border: 1px solid #feebc8; white-space: nowrap; } .entry-st-run { font-size: 11px; padding: 1px 8px; border-radius: 8px; background: #ebf4ff; color: #2b6cb0; border: 1px solid #bee3f8; } .st-can-submit { font-size: 11px; padding: 1px 8px; border-radius: 8px; background: #fefcbf; color: #744210; border: 1px solid #f6e05e; white-space: nowrap; } .st-none { font-size: 11px; padding: 1px 8px; border-radius: 8px; background: #edf2f7; color: #718096; border: 1px solid #e2e8f0; white-space: nowrap; } /* 按钮 */ .vb { padding: 6px 13px; border-radius: 6px; border: none; font-size: 12px; font-weight: 600; cursor: pointer; transition: background 0.15s; white-space: nowrap; } .vb-primary { background: #ebf4ff; color: #2b6cb0; border: 1px solid #bee3f8; } .vb-green { background: #f0fff4; color: #276749; border: 1px solid #c6f6d5; } .vb-yellow { background: #fefcbf; color: #744210; border: 1px solid #f6e05e; } .vb-outline { background: #fff; color: #4a5568; border: 1px solid #cbd5e0; } .vb-danger { background: #fff; color: #c53030; border: 1px solid #fed7d7; } .vb-mini { padding: 3px 9px; font-size: 11px; } .vb:disabled { opacity: 0.45; cursor: not-allowed; } /* 可折叠区块样式 */ .v80-section { flex-shrink: 0; border-top: 1px solid var(--nju-border); } .v80-sec-hd { padding: 7px 14px; display: flex; align-items: center; gap: 8px; cursor: pointer; user-select: none; background: var(--nju-bg-subtle); } .v80-sec-hd .lbl { font-size: var(--nju-fs-xs); color: var(--nju-text-2); font-weight: 600; flex: 1; } .v80-sec-hd .arr { font-size: var(--nju-fs-md); color: var(--nju-text-3); } .v80-sec-body { display: none; } .v80-sec-body.open { display: block; } /* Storage 预览样式 */ #v80-storage-pre { max-height: 200px; overflow-y: auto; padding: 4px 10px; font-size: var(--nju-fs-xs); line-height: 1.6; font-family: var(--nju-font-mono); background: var(--nju-bg-subtle); } .v80-value-chip { display: inline-block; margin-left: 6px; font-size: var(--nju-fs-xs); color: var(--nju-text-2); } `; document.head.appendChild(style); }; // ===== src/evaluate/panel.js =========================================== // ── 面板构建 ────────────────────────────────────────────────────── /** * 创建并注入控制面板 DOM */ const buildPanel = (titleHtml, actionBarHtml, bodyHtml) => { injectCSS(); const panel = document.createElement('div'); panel.id = 'v80-panel'; panel.className = 'nju-window'; panel.innerHTML = `
    ${titleHtml} ✕
    ${actionBarHtml}
    ${bodyHtml}
    Storage 原始数据 ▾
    
                    
    `; document.body.appendChild(panel); // 关闭按钮 const closeBtn = document.getElementById('v80-close-btn'); if (closeBtn) { closeBtn.addEventListener('click', (e) => { e.stopPropagation(); panel.remove(); }); // hover 样式由 base.css 的 .nju-close 统一提供 } // 存储预览区块折叠 const storeBody = document.getElementById('store-body'), storeArr = document.getElementById('store-arr'); document.getElementById('store-hd').onclick = () => { storeBody.classList.toggle('open'); storeArr.textContent = storeBody.classList.contains('open') ? '▴' : '▾'; if (storeBody.classList.contains('open')) renderStoragePanel(); }; // 复用公共窗口能力:拖动 + 八向缩放 + 位置记忆 window.NJUI.enableWindow({ id: 'evaluate', target: panel, handle: document.getElementById('v80-header'), minWidth: 380, minHeight: 260 }); return panel; }; // ===== src/evaluate/findPage.js ======================================== // ── FIND 页面 (评教类别入口页) ──────────────────────────────────── if (location.href.includes('xspj_find.do')) { /** * 扫描页面中所有的评价入口(如理论课程、实验课程等) */ const scanEntries = () => { const anchors = document.querySelectorAll('a[href*="xspj_list.do"]'); const found = []; anchors.forEach(a => { const href = a.getAttribute('href'); const label = a.textContent.trim() || a.title || href; // 完整 URL、协议相对(//host/...)均保持原样,其余按当前站点补全 const abs = /^(https?:)?\/\//.test(href) ? href : location.origin + href; found.push({ label, url: abs }); }); return found; }; buildPanel( '南理工教务增强助手 V2', `
    新手使用指南
    ① 点击下方任一入口,进入该"类别"的课程列表页。
    ② 在课程列表页,勾选要自动处理的课程(默认全部勾选)。
    ③ 点击"开始评价并保存",系统会依次打开勾选课程的评价页,自动填分并保存。
    ④ 保存后课程显示"待提交",点击"提交已评课程"可批量提交。
    ⑤ "是否提交=是"的课程视为已完成,不会再进行任何自动操作。
    重要:用户必须自行点击"确认"弹窗确认!
    出现问题可使用“重置缓存(清除状态)”按钮重置进度
    查看更多使用说明请点击>>>>> 增强助手官网
    `, `
    ` ); // 初始化布局调整 (function () { const p = document.getElementById('v80-panel'); if (p) p.classList.add('wide'); })(); /** * 渲染各类别入口的卡片及完成进度 */ const renderEntries = () => { const entries = scanEntries(), store = loadStore(); const curList = localStorage.getItem(KEY_CURLIST) || ''; const running = localStorage.getItem(KEY_RUNNING) === 'true'; const box = document.getElementById('entry-list'); if (!box) return; box.innerHTML = ''; entries.forEach(entry => { const pj01 = qp(entry.url, 'pj01id'); // 从存储中筛选属于该类别的课程 const related = Object.values(store).filter(c => c.url && qp(c.url, 'pj01id') === pj01); const doneN = related.filter(c => c.done).length; const totalN = related.length; const curPj01 = curList ? qp(curList, 'pj01id') : ''; const isCur = running && curPj01 && entry.url.includes(curPj01); const allDone = totalN > 0 && doneN === totalN; const card = document.createElement('div'); card.className = 'entry-card'; card.innerHTML = `${esc(entry.label)}` + (totalN ? `${doneN}/${totalN}` : '') + `${isCur ? '运行中' : allDone ? '已完成' : '等待中'}` + ``; box.appendChild(card); }); // 绑定"进入"按钮点击事件 box.querySelectorAll('.entry-enter-btn').forEach(btn => { btn.addEventListener('click', () => { const url = btn.getAttribute('data-url'); if (url) window.location.href = url; }); }); }; window.addEventListener('storage', () => { renderEntries(); }); renderEntries(); } // ===== src/evaluate/listPage.js ======================================== // ── LIST 页面 (课程列表页) ──────────────────────────────────────── if (location.href.includes('xspj_list.do')) { buildPanel( '南理工教务增强助手 V2', `
    前往增强助手官网
    `, `
    ` ); /** * 解析当前页面的课程表格,提取课程信息和状态 */ const parseRows = () => { const rows = document.querySelectorAll('#dataList tr:not(:first-child)'), result = []; rows.forEach(row => { if (row.cells.length < 7) return; const a = row.querySelector('a[href*="openWindow"]'); if (!a) return; const rawUrl = a.getAttribute('href').match(/'([^']+)'/)?.[1]; if (!rawUrl) return; result.push({ key: courseKey(rawUrl), rawUrl, name: row.cells[2]?.innerText.trim() || '', teacher: row.cells[3]?.innerText.trim() || '', zpf: qp(rawUrl, 'zpf'), evaluated: row.cells[5]?.innerText.trim() === '是', submitted: row.cells[6]?.innerText.trim() === '是' }); }); return result; }; /** * 更新“批量提交”按钮的状态和提示文字 */ const updateSubmitBtn = () => { const btn = document.getElementById('submit-all-btn'), hint = document.getElementById('v80-submit-hint'); if (!btn) return; const store = loadStore(); const canSubmit = parseRows().filter(c => { const info = store[c.key]; return (c.evaluated || (info && info.done)) && !c.submitted && (info ? info.auto !== false : true); }); if (canSubmit.length > 0) { btn.disabled = false; hint.className = 'visible'; hint.innerHTML = `${canSubmit.length} 门课程可提交(已评价且未提交且选中):` + canSubmit.map(c => `
     · ${esc(c.name)}`).join(''); } else { btn.disabled = true; hint.className = ''; hint.innerHTML = ''; } }; /** * 渲染课程列表,包含勾选框和实时状态标签 */ const renderList = () => { const store = loadStore(), courses = parseRows(), box = document.getElementById('course-list'); if (!box) return; box.innerHTML = ''; courses.forEach(c => { // 初始化存储项 if (!store[c.key]) store[c.key] = { auto: true, done: false, name: c.name, teacher: c.teacher, zpf: c.zpf, url: c.rawUrl, pj01id: qp(c.rawUrl, 'pj01id') }; // 已评价或已提交都视为完成,避免重复打开同一门课 if (c.submitted || c.evaluated) store[c.key].done = true; const info = store[c.key]; let stClass, stLabel; if (c.submitted) { stClass = 'st-submitted'; stLabel = '已提交'; } else if (info.auto !== false) { if (c.evaluated || info.done) { stClass = 'st-can-submit'; stLabel = '待提交'; } else { stClass = 'st-wait'; stLabel = '待评价'; } } else { stClass = 'st-none'; stLabel = '不操作'; } const el = document.createElement('div'); el.className = 'ci'; el.innerHTML = `` + `${esc(c.name)}` + `${esc(c.teacher)}` + (c.zpf ? `${esc(c.zpf)}分` : '') + `${stLabel}` + ``; box.appendChild(el); }); // 绑定勾选框事件,更新存储 document.querySelectorAll('.course-ck').forEach(ck => { ck.onchange = (e) => { const k = e.target.getAttribute('data-key'); store[k].auto = e.target.checked; saveStore(store); updateSubmitBtn(); setTimeout(() => renderList(), 0); }; }); // 绑定"查看"按钮点击事件 box.querySelectorAll('.course-view-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.stopPropagation(); const url = btn.getAttribute('data-url'); if (url) window.open(url, '_blank', 'width=1200,height=800'); }); }); saveStore(store); updateSubmitBtn(); }; /** * “自动评价并保存”流水线的调度器 */ const execNext = () => { if (localStorage.getItem(KEY_RUNNING) !== 'true') return; // 互斥锁:等待当前课程处理完毕;超过阈值视为流程中断并自动恢复 if (localStorage.getItem(KEY_BUSY) === 'true') { const ts = parseInt(localStorage.getItem(KEY_BUSY_TS) || '0', 10); if (ts && Date.now() - ts < LOCK_TIMEOUT) return; localStorage.setItem(KEY_BUSY, 'false'); logInfo('上一次操作已超时,已自动恢复流程'); } const store = loadStore(), curPj01 = qp(location.href, 'pj01id'); // 查找属于当前类别且未完成的待评价课程 const pending = Object.keys(store).filter(k => { const c = store[k]; return c.auto && !c.done && (!curPj01 || qp(c.url, 'pj01id') === curPj01); }); if (pending.length > 0) { const c = store[pending[0]]; localStorage.setItem(KEY_BUSY, 'true'); localStorage.setItem(KEY_BUSY_TS, String(Date.now())); logInfo(`正在保存:${c.name}(本类别剩余 ${pending.length} 门)`); // 记录列表页地址,供评价页完成后返回 sessionStorage.setItem('njust_eval_list_url', location.href); // 同页跳转,避免异步 window.open 被浏览器拦截 setTimeout(() => { location.href = withAuto(c.url, 'true'); }, 300); } else { localStorage.setItem(KEY_RUNNING, 'false'); localStorage.setItem(KEY_BUSY, 'false'); logSuccess('当前类别的课程已全部处理完成'); renderList(); } }; /** * “自动提交”流水线的调度器 */ const execNextSubmit = () => { if (localStorage.getItem(KEY_SUBRUN) !== 'true') return; if (localStorage.getItem(KEY_SUBBSY) === 'true') { const ts = parseInt(localStorage.getItem(KEY_SUBBSY_TS) || '0', 10); if (ts && Date.now() - ts < LOCK_TIMEOUT) return; localStorage.setItem(KEY_SUBBSY, 'false'); logInfo('上一次提交已超时,已自动恢复流程'); } const queue = loadSubQueue(); if (queue.length === 0) { localStorage.setItem(KEY_SUBRUN, 'false'); localStorage.setItem(KEY_SUBBSY, 'false'); logSuccess('所有勾选课程提交完毕'); setTimeout(() => location.reload(), 800); return; } const nextUrl = queue.shift(); saveSubQueue(queue); localStorage.setItem(KEY_SUBBSY, 'true'); localStorage.setItem(KEY_SUBBSY_TS, String(Date.now())); const submitStore = loadStore(), submitKey = courseKey(nextUrl), submitInfo = submitKey ? submitStore[submitKey] : null; logInfo(`正在提交:${submitInfo ? submitInfo.name + '(' + submitInfo.teacher + ')' : nextUrl}`); sessionStorage.setItem('njust_eval_list_url', location.href); // 同页跳转,避免被浏览器拦截 setTimeout(() => { location.href = nextUrl; }, 300); }; // 按钮点击事件绑定 document.getElementById('start-btn').onclick = () => { localStorage.setItem(KEY_RUNNING, 'true'); localStorage.setItem(KEY_BUSY, 'false'); localStorage.setItem(KEY_CURLIST, location.href); renderList(); execNext(); }; document.getElementById('submit-all-btn').onclick = () => { const store = loadStore(), toSubmit = parseRows().filter(c => { const info = store[c.key]; return (c.evaluated || (info && info.done)) && !c.submitted && (info ? info.auto !== false : true); }); if (toSubmit.length === 0) return; if (!confirm(`即将提交以下 ${toSubmit.length} 门课程:\n` + toSubmit.map(c => `· ${c.name}(${c.teacher})`).join('\n') + '\n\n确认继续?')) return; const queue = toSubmit.map(c => withSubmit(c.rawUrl)); saveSubQueue(queue); localStorage.setItem(KEY_SUBRUN, 'true'); localStorage.setItem(KEY_SUBBSY, 'false'); execNextSubmit(); }; document.getElementById('reset-btn').onclick = () => { if (!confirm('重置所有缓存?')) return; [KEY_STORE, KEY_RUNNING, KEY_BUSY, KEY_BUSY_TS, KEY_CURLIST, KEY_SUBQUEUE, KEY_SUBRUN, KEY_SUBBSY, KEY_SUBBSY_TS].forEach(k => localStorage.removeItem(k)); location.reload(); }; document.getElementById('clear-log-btn').onclick = () => clearLogs(); // 跨页面状态监听:当其他窗口修改了 busy 标志或完成状态时,本页面及时响应并触发下一步 window.addEventListener('storage', (e) => { if ([KEY_STORE, KEY_BUSY, KEY_RUNNING].includes(e.key)) { renderList(); if (e.key === KEY_BUSY && e.newValue === 'false' && localStorage.getItem(KEY_RUNNING) === 'true') setTimeout(execNext, 800); } if (e.key === KEY_SUBBSY && e.newValue === 'false' && localStorage.getItem(KEY_SUBRUN) === 'true') setTimeout(execNextSubmit, 800); }); renderList(); // 自动恢复执行:若页面刷新时流水线正在运行,则继续 if (localStorage.getItem(KEY_RUNNING) === 'true' && localStorage.getItem(KEY_BUSY) !== 'true') setTimeout(execNext, 1200); if (localStorage.getItem(KEY_SUBRUN) === 'true' && localStorage.getItem(KEY_SUBBSY) !== 'true') setTimeout(execNextSubmit, 1200); } // ===== src/evaluate/editPage.js ======================================== // ── EDIT 页面 (具体课程评价页) ──────────────────────────────────── if (location.href.includes('xspj_edit.do')) { const params = new URLSearchParams(location.search); const isAutoSave = params.get(PARAM_AUTO) === 'true'; const isAutoSub = params.get(PARAM_SUBMIT) === 'true'; const isManual = !isAutoSave && !isAutoSub; // 完成后退回课程列表页(同页跳转模式) // 优先使用列表页在跳转前记录的地址,确保返回时是完整加载、脚本会重新执行 const goBack = () => { const listUrl = sessionStorage.getItem('njust_eval_list_url'); if (listUrl) location.href = listUrl; else if (history.length > 1) history.back(); else window.close(); }; // 手动模式:注入顶栏快捷填分工具 if (isManual) { const initManual = () => { injectCSS(); const { gkeys, groups } = collectGroups(); if (gkeys.length === 0) return; ensureValueFields(); const bar = document.createElement('div'); bar.id = 'v80-manual-bar'; bar.style.cssText = 'position:sticky;top:0;left:0;width:100%;z-index:var(--nju-z-topbar);box-sizing:border-box;background:#ebf8ff;border-bottom:2px solid #90cdf4;color:#2c5282;padding:10px 18px;font-family:var(--nju-font);box-shadow:var(--nju-shadow-sm);'; bar.innerHTML = `
    南理工教务增强助手 V2 手动模式 快捷填分: 未填写
    `; document.body.prepend(bar); const scoreDisplay = document.getElementById('v8-score-display'); const manualHint = document.getElementById('v8-manual-hint'); const refreshScore = () => { const { gkeys: gk2, groups: gr2 } = collectGroups(); const total = calcCurrentTotal(gk2, gr2); const answered = gk2.filter(k => gr2[k].some(o => o.el.checked)).length; scoreDisplay.textContent = answered === 0 ? '未填写' : `总分 ${total} (${answered}/${gk2.length}题)`; scoreDisplay.style.color = '#276749'; }; const strategies = [ { id: 'v8-fill-highest', s: 'highest', label: '最高分' }, { id: 'v8-fill-high', s: 'high', label: '中高分' }, { id: 'v8-fill-mid', s: 'mid', label: '中分' }, { id: 'v8-fill-low', s: 'low', label: '低分' } ]; strategies.forEach(({ id, s, label }) => { document.getElementById(id).addEventListener('click', () => { const { gkeys: gk2, groups: gr2 } = collectGroups(); const total = applyStrategy(s, gk2, gr2); scoreDisplay.textContent = `当前 ${total} 分(${label})`; scoreDisplay.style.color = '#276749'; manualHint.style.display = 'block'; }); }); document.querySelectorAll('input[type="radio"]').forEach(r => r.addEventListener('change', refreshScore)); refreshScore(); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => setTimeout(initManual, 300)); else setTimeout(initManual, 300); return; } // 自动模式(保存或提交) injectCSS(); const bgColor = isAutoSub ? '#f0fff4' : '#ebf8ff'; const bdColor = isAutoSub ? '#9ae6b4' : '#90cdf4'; const textColor = isAutoSub ? '#276749' : '#2c5282'; const modeName = isAutoSub ? '提交模式' : '保存模式'; const bar = document.createElement('div'); bar.style.cssText = `position:sticky;top:0;left:0;width:100%;z-index:var(--nju-z-topbar);box-sizing:border-box;background:${bgColor};color:${textColor};border-bottom:2px solid ${bdColor};box-shadow:var(--nju-shadow-sm);font-family:var(--nju-font);`; bar.innerHTML = `
    南理工教务增强助手 V2 ${modeName} 初始化... 总分 0
    请确认评分无误后,手动点击浏览器弹出的「确认」按钮
    `; document.body.prepend(bar); const tag = document.getElementById('edit-tag'); const editLog = (msg, level = 'info') => { tag.textContent = msg; pushLog(msg, level); }; let stopped = false; document.getElementById('stop-btn').onclick = () => { stopped = true; editLog('已停止'); // 停止时主动释放锁,避免流水线卡死 localStorage.setItem(KEY_BUSY, 'false'); localStorage.setItem(KEY_SUBBSY, 'false'); document.getElementById('stop-btn').style.display = 'none'; }; // 执行自动提交逻辑 if (isAutoSub) { setTimeout(() => { const key = courseKey(location.href); editLog('准备提交'); if (stopped) return; // 提交模式下也要计算并显示当前总分 const { gkeys, groups } = collectGroups(); const total = calcCurrentTotal(gkeys, groups); const totalDisplay = document.getElementById('v8-total-display'); if (totalDisplay) totalDisplay.textContent = `总分 ${total}`; ensureValueFields(); const releaseLock = () => localStorage.setItem(KEY_SUBBSY, 'false'); const doSubmit = () => { if (stopped) { releaseLock(); return; } const tj = document.getElementById('tj'); if (!tj) { editLog('未找到提交按钮,请手动提交', 'error'); releaseLock(); return; } try { // 调用教务系统原生的提交函数 unsafeWindow.saveData(tj, '1'); } catch (err) { editLog('提交出错,请手动处理:' + err.message, 'error'); releaseLock(); return; } // 提交成功后再标记完成,避免失败却被跳过 const fresh = loadStore(); if (key && fresh[key]) { fresh[key].done = true; saveStore(fresh); } editLog('已提交,返回列表', 'success'); setTimeout(() => { releaseLock(); setTimeout(goBack, 300); }, 800); }; let tries = 0; const poll = setInterval(() => { tries++; if (document.getElementById('tj') || tries > 10) { clearInterval(poll); doSubmit(); } }, 500); }, 800); } else { // 执行自动填分并保存逻辑 setTimeout(() => { if (stopped) return; const key = courseKey(location.href); const { gkeys, groups } = collectGroups(); ensureValueFields(); // 分值解析校验:解析不到任何分值时停止,避免误选全部 0 分 const hasValidScore = gkeys.some(k => groups[k].some(o => o.score > 0)); if (!gkeys.length || !hasValidScore) { editLog('未能解析评分项或分值,已停止自动保存', 'error'); localStorage.setItem(KEY_BUSY, 'false'); return; } const total = applyStrategy('highest', gkeys, groups); const totalDisplay = document.getElementById('v8-total-display'); if (totalDisplay) totalDisplay.textContent = `总分 ${total}`; if (stopped) return; editLog('填写完成,正在保存'); setTimeout(() => { if (stopped) return; const bc = document.getElementById('bc'); // 保存按钮 if (!bc) { editLog('未找到保存按钮,请手动保存', 'error'); localStorage.setItem(KEY_BUSY, 'false'); return; } try { unsafeWindow.saveData(bc, '0'); } catch (err) { editLog('保存出错,请手动处理:' + err.message, 'error'); localStorage.setItem(KEY_BUSY, 'false'); return; } // 保存无异常后再标记完成,避免失败却被跳过 const fresh = loadStore(); if (key && fresh[key]) { fresh[key].done = true; saveStore(fresh); } editLog('已保存,返回列表', 'success'); setTimeout(() => { localStorage.setItem(KEY_BUSY, 'false'); setTimeout(goBack, 300); }, 800); }, 800); }, 800); } } })();