ソースを参照

Merge pull request #894 from ShiGuangSchedule/pending

星河欲转 1 週間 前
親
コミット
e15c6274ac

+ 11 - 0
index/root_index.yaml

@@ -1332,3 +1332,14 @@ schools:
     name: "贵州机电职业技术学院"
     initial: "G"
     resource_folder: "GZTCME"
+
+  - id: "GZHMU"
+    name: "广州医科大学"
+    initial: "G"
+    resource_folder: "GZHMU"
+
+  - id: "XSYU"
+    name: "西安石油大学"
+    initial: "X"
+    resource_folder: "XSYU"
+    

+ 9 - 1
resources/GDOU/adapters.yaml

@@ -6,7 +6,15 @@ adapters:
     asset_js_path: "gdou.js"
     import_url: "https://jw.gdou.edu.cn/"
     maintainer: "Mccurtain"
-    description: "广东海洋大学教务适配,如有误请提交 issues"
+    description: "广东海洋大学教务适配,校园网内优先使用此通道,如有误请提交 issues"
+
+  - adapter_id: "GDOU_02"
+    adapter_name: "广东海洋大学教务(校外通道)"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "gdou2.js"
+    import_url: "https://wfw.gdou.edu.cn/https://jw.gdou.edu.cn/"
+    maintainer: "Mccurtain"
+    description: "广东海洋大学教务适配,校园网外使用(经学校零信任通道访问教务系统,校内外均可),登录前,请点右上角菜单,选择“电脑模式”。如有误请提交 issues"
 
   - adapter_id: "GDOUYJ_01"
     adapter_name: "广东海洋大学阳江校区教务"

+ 91 - 36
resources/GDOU/gdou.js

@@ -2,17 +2,24 @@
  * 广东海洋大学教务课表导入适配
  * @date 2026-08-27
  * @author Mccurtain
- * @version 2.0
+ * @version 2.2
+ * 
+ * 特别鸣谢 @mei-iem 提供真机实测
+ * 
  */
 
 (function () {
 
 // ==================== 常量 ====================
 
-// venues 为整栋楼使用特殊作息的楼名(包含匹配,如 "实验楼" 会命中 "实验楼301"、"网球场(实验楼东面)");
-// venuePatterns 为楼名简写正则(如海滨 "实"+房间号 = 实验楼简写,实506-1计算机(2)室);
-// outdoorKeywords 为特殊作息的室外场地关键词。
-
+// 特殊作息(指定楼/室外场地作息)匹配规则:
+// 前提:节次处于特殊时间段(3-4、7-8 节,见 SPECIAL_TIME_BLOCKS);
+// 上课地点命中以下任意一种情况即打标特殊时间:
+//   1. 楼名包含匹配(venues,如 "实验楼" 命中 "实验楼301"、"网球场(实验楼东面)"),
+//      另支持简写正则(venuePatterns,如海滨 "实"+房间号 = 实验楼简写,实506-1计算机(2)室);
+//   2. 含方位词(东面/南面/西面/北面,如 "XX(实验楼东面)");
+//   3. 含运动场("场"字,覆盖 网球场/匹克场/足球场/篮球场/田径场 等各类场地)。
+// 均未命中的其他教室(教学楼等)使用 TimeSlots 全校统一作息。
 const CAMPUS_CONFIGS = [
     {
         id: "huguang",
@@ -26,7 +33,9 @@ const CAMPUS_CONFIGS = [
         label: "海滨校区",
         venues: ["实验楼"],
         venuePatterns: [{ name: "实验楼简写", pattern: /^实\d/ }],
-        outdoorKeywords: ["球场", "东面", "南面", "西面", "北面"]
+        // 室外场地关键词:"场"通用覆盖 网球场/篮球场/排球场/匹克场/田径场 等各类场地(含简写);
+        // 方向词覆盖 "XX(实验楼东面)" 这类括号方位写法
+        outdoorKeywords: ["场", "东面", "南面", "西面", "北面"]
     }
 ];
 
@@ -376,15 +385,73 @@ function findSemesterStartDate(value) {
     return null;
 }
 
+// ==================== 接口地址推导 ====================
+
+/**
+ * 推导教务系统接口前缀,兼容两条入口通道:
+ *   GDOU_01 内网直连:pathname 形如 /kbcx/xskbcx_cxXsgrkb.html                    → 前缀为 ""
+ *   反代·拼接态:      pathname 形如 /https://jw.gdou.edu.cn/kbcx/xskbcx_...html   → 前缀为 "/https://jw.gdou.edu.cn"
+ *   反代·哈希态:      pathname 形如 /http/<hash>/kbcx/xskbcx_...html              → 前缀为 "/http/<hash>"
+ * 以 "/kbcx/" 为锚点即可同时覆盖以上三种情况。
+ */
+function getScheduleBase() {
+    const path = (window.location && window.location.pathname) || "";
+
+    const kbIndex = path.indexOf("/kbcx/");
+    if (kbIndex >= 0) return path.slice(0, kbIndex);
+
+    // 兜底:停留在教务系统非课表页(例如首页)时,直接识别反代前缀。
+    const proxyPrefix = path.match(/^\/(?:https?:\/\/[^/]+|(?:http|https|https-443)\/[^/]+)/i);
+    return proxyPrefix ? proxyPrefix[0] : "";
+}
+
+/**
+ * 拼接教务系统接口地址,自动带上直连/反代前缀
+ * @param {string} modulePath 接口文件名,例如 "xskbcx_cxXsgrkb.html"
+ * @param {string} query 可选查询串,例如 "gnmkdm=N2151"
+ */
+function buildScheduleUrl(modulePath, query) {
+    const base = getScheduleBase();
+    const queryString = query ? `?${query}` : "";
+    return `${window.location.origin}${base}/kbcx/${modulePath}${queryString}`;
+}
+
 // ==================== 教务接口 ====================
 
+/**
+ * 从 select 元素解析学年和学期选项。
+ * 默认索引优先使用当前 select.value,确保跟随用户在页面上的实际选择。
+ */
+function parseSelectOptions(selectElement) {
+    if (!selectElement || typeof selectElement.querySelectorAll !== "function") {
+        return { options: [], defaultIndex: 0 };
+    }
+
+    const options = [];
+    let defaultIndex = 0;
+    Array.from(selectElement.querySelectorAll("option")).forEach(option => {
+        const value = String(option.value || "").trim();
+        if (!value) return;
+
+        const text = String(option.textContent || "").trim() || value;
+        if (option.selected) defaultIndex = options.length;
+        options.push({ value, text });
+    });
+
+    const currentValue = String(selectElement.value || "").trim();
+    const currentIndex = options.findIndex(option => option.value === currentValue);
+    if (currentIndex !== -1) defaultIndex = currentIndex;
+
+    return { options, defaultIndex };
+}
+
 /**
  * 读取课表查询页里的学年/学期下拉选项
  * 成功返回 { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex };
  * 读取失败返回 null,由调用方回退到默认值
  */
 async function fetchAcademicOptions() {
-    const url = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
+    const url = buildScheduleUrl("xskbcx_cxXskbcxIndex.html", "gnmkdm=N2151&layout=default");
 
     try {
         const response = await fetch(url, { method: "GET", credentials: "include" });
@@ -392,21 +459,9 @@ async function fetchAcademicOptions() {
 
         const doc = new DOMParser().parseFromString(await response.text(), "text/html");
 
-        // 解析单个下拉框;默认选中项优先跟随 select 当前值,其次取 selected 属性
-        const readSelect = (select) => {
-            if (!select) return null;
-            const options = Array.from(select.querySelectorAll("option"))
-                .map(opt => ({ value: opt.value, text: opt.textContent.trim() || opt.value }))
-                .filter(opt => opt.value !== "");
-            if (options.length === 0) return null;
-            const valueIndex = options.findIndex(opt => opt.value === select.value);
-            const selectedIndex = options.findIndex(opt => opt.selected);
-            return { options, defaultIndex: valueIndex !== -1 ? valueIndex : Math.max(0, selectedIndex) };
-        };
-
-        const yearData = readSelect(doc.querySelector("#xnm"));
-        const semesterData = readSelect(doc.querySelector("#xqm"));
-        if (!yearData || !semesterData) return null;
+        const yearData = parseSelectOptions(doc.querySelector("#xnm"));
+        const semesterData = parseSelectOptions(doc.querySelector("#xqm"));
+        if (yearData.options.length === 0 || semesterData.options.length === 0) return null;
 
         return {
             yearOptions: yearData.options,
@@ -424,7 +479,7 @@ async function fetchAcademicOptions() {
  * 接口失败时返回 null,不影响主流程
  */
 async function fetchSemesterInfo(academicYear, semesterCode) {
-    const url = "https://jw.gdou.edu.cn/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
+    const url = buildScheduleUrl("xskbcxZccx_cxZcByXnxq.html", "gnmkdm=N2154");
     const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
 
     try {
@@ -459,21 +514,21 @@ async function fetchSemesterInfo(academicYear, semesterCode) {
  */
 async function fetchAndParseCourses(academicYear, semesterCode, campusConfig) {
     const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
-    const courseUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
-
-    const [courseResponse, semesterInfo] = await Promise.all([
-        fetch(courseUrl, {
-            method: "POST",
-            headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
-            body,
-            credentials: "include"
-        }),
-        fetchSemesterInfo(academicYear, semesterCode)
-    ]);
+    const courseUrl = buildScheduleUrl("xskbcx_cxXsgrkb.html", "gnmkdm=N2151");
 
     try {
+        const [courseResponse, semesterInfo] = await Promise.all([
+            fetch(courseUrl, {
+                method: "POST",
+                headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
+                body,
+                credentials: "include"
+            }),
+            fetchSemesterInfo(academicYear, semesterCode)
+        ]);
+
         if (!courseResponse.ok) {
-            window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}`);
+            window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}。如当前不在校园网内,请返回选择“广东海洋大学教务(校外通道)”重试。`);
             return null;
         }
 
@@ -495,7 +550,7 @@ async function fetchAndParseCourses(academicYear, semesterCode, campusConfig) {
             }
         };
     } catch (e) {
-        window.shiguangBridge.showToast("获取课表失败,请确认已登录且网络可访问 jw.gdou.edu.cn。");
+        window.shiguangBridge.showToast("获取课表失败,请确认已登录且网络可访问 jw.gdou.edu.cn;如当前不在校园网内,请返回选择“广东海洋大学教务(校外通道)”重试。");
         return null;
     }
 }

+ 880 - 0
resources/GDOU/gdou2.js

@@ -0,0 +1,880 @@
+/**
+ * 广东海洋大学教务课表导入适配(校外通道)
+ * @date 2026-08-27
+ * @author Mccurtain
+ * @version 1.0
+ *
+ * 特别鸣谢 @Yihe-ng 提供的校外通道反代方案
+ * 
+ * 本文件为"校园网外"专用通道:入口经学校零信任反代
+ *(https://wfw.gdou.edu.cn/https://jw.gdou.edu.cn/),
+ * 接口地址按当前页 pathname 自动推导反代前缀;
+ * 登录后落在 wfw 移动门户首页时,以 iframe 打开代理课表页(移植自 gdouyj.js,已实测)。
+ * 与 gdou.js(校园网内直连通道)逻辑一致,
+ * 修改作息/接口逻辑时请与 gdou.js 保持同步。
+ */
+
+(function () {
+
+// ==================== 常量 ====================
+
+// 特殊作息(指定楼/室外场地作息)匹配规则:
+// 前提:节次处于特殊时间段(3-4、7-8 节,见 SPECIAL_TIME_BLOCKS);
+// 上课地点命中以下任意一种情况即打标特殊时间:
+//   1. 楼名包含匹配(venues,如 "实验楼" 命中 "实验楼301"、"网球场(实验楼东面)"),
+//      另支持简写正则(venuePatterns,如海滨 "实"+房间号 = 实验楼简写,实506-1计算机(2)室);
+//   2. 含方位词(东面/南面/西面/北面,如 "XX(实验楼东面)");
+//   3. 含运动场("场"字,覆盖 网球场/匹克场/足球场/篮球场/田径场 等各类场地)。
+// 均未命中的其他教室(教学楼等)使用 TimeSlots 全校统一作息。
+const CAMPUS_CONFIGS = [
+    {
+        id: "huguang",
+        label: "湖光校区",
+        venues: ["广学楼", "明德楼"],
+        venuePatterns: [],
+        outdoorKeywords: []
+    },
+    {
+        id: "haibin",
+        label: "海滨校区",
+        venues: ["实验楼"],
+        venuePatterns: [{ name: "实验楼简写", pattern: /^实\d/ }],
+        // 室外场地关键词:"场"通用覆盖 网球场/篮球场/排球场/匹克场/田径场 等各类场地(含简写);
+        // 方向词覆盖 "XX(实验楼东面)" 这类括号方位写法
+        outdoorKeywords: ["场", "东面", "南面", "西面", "北面"]
+    }
+];
+
+// 全校统一作息时间(1-10 节),未指定特殊作息的教室使用
+const TimeSlots = [
+    { number: 1, startTime: "08:10", endTime: "08:55" },
+    { number: 2, startTime: "09:00", endTime: "09:45" },
+    { number: 3, startTime: "10:15", endTime: "11:00" },
+    { number: 4, startTime: "11:05", endTime: "11:50" },
+    { number: 5, startTime: "14:30", endTime: "15:15" },
+    { number: 6, startTime: "15:20", endTime: "16:05" },
+    { number: 7, startTime: "16:30", endTime: "17:15" },
+    { number: 8, startTime: "17:20", endTime: "18:05" },
+    { number: 9, startTime: "19:30", endTime: "20:15" },
+    { number: 10, startTime: "20:25", endTime: "21:10" }
+];
+
+// 指定楼/室外场地的特殊作息时间块(连堂)
+const SPECIAL_TIME_BLOCKS = [
+    { startSection: 3, endSection: 4, startTime: "10:05", endTime: "11:35" },
+    { startSection: 7, endSection: 8, startTime: "16:25", endTime: "17:50" }
+];
+
+// ==================== 解析函数 ====================
+
+/**
+ * 将周次字符串展开为具体周次数组
+ * 支持范围(如 1-16周)、单周(如 6周)、单双周(如 1-8周(单))、
+ * 以及逗号分隔的多种写法混合,全角逗号也会被兼容
+ */
+function parseWeeks(weekStr) {
+    if (!weekStr) return [];
+
+    const groups = String(weekStr).replace(/,/g, ',').split(',');
+    const weeks = [];
+
+    for (const group of groups) {
+        const item = group.trim();
+
+        // 先尝试匹配 "起-止周",再尝试匹配单个周次
+        // 兼容"第1-8周"、"1-8周"、"第3周"、"3周"格式
+        const rangeMatch = item.match(/第?(\d+)\s*-\s*(\d+)\s*周?/);
+        const singleMatch = item.match(/第?(\d+)\s*周?/);
+
+        let start = 0;
+        let end = 0;
+        let matched = false;
+
+        if (rangeMatch) {
+            start = Number(rangeMatch[1]);
+            end = Number(rangeMatch[2]);
+            matched = true;
+        } else if (singleMatch) {
+            start = end = Number(singleMatch[1]);
+            matched = true;
+        }
+
+        if (matched && start >= 1 && end >= start) {
+            const isOddOnly = item.includes('(单)');
+            const isEvenOnly = item.includes('(双)');
+
+            for (let w = start; w <= end; w++) {
+                if (isOddOnly && w % 2 === 0) continue; // 单周:跳过偶数周
+                if (isEvenOnly && w % 2 !== 0) continue; // 双周:跳过奇数周
+                weeks.push(w);
+            }
+        }
+    }
+
+    return [...new Set(weeks)].sort((a, b) => a - b);
+}
+
+/**
+ * 解析节次字段,如 "1-2"、"3"、"1-2节",得到起止节次
+ * 格式无法识别或数值不合法时返回 null
+ */
+function parseSectionRange(sectionStr) {
+    const text = sectionStr == null ? '' : String(sectionStr);
+    const match = text.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
+
+    if (!match) return null;
+
+    const startSection = Number(match[1]);
+    const endSection = Number(match[2] || match[1]);
+
+    if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
+        startSection < 1 || endSection < startSection) {
+        return null;
+    }
+
+    return { startSection, endSection };
+}
+
+// 提前公选课课程名
+function normalizeCourseName(rawName) {
+    const name = String(rawName).trim();
+    if (!name) return name;
+
+    const match = name.match(/^[((]([^()()]+)[))]\s*/);
+    if (!match) return name;
+
+    const rest = name.slice(match[0].length);
+    if (!rest) return name;
+
+    return `${rest}(${match[1]})`;
+}
+
+/**
+ * 节次与周次合并去重函数
+ * @param {Array<Object>} courses 原始解析课程数组
+ * @returns {Array<Object>} 合并去重后的课程数组
+ */
+function mergeAndDistinctCourses(courses) {
+    if (!Array.isArray(courses) || courses.length <= 1) return courses;
+
+    // 规范化数据,周次统一排序,便于比较
+    const list = courses.map(c => ({
+        ...c,
+        name: c.name || '',
+        teacher: c.teacher || '',
+        position: c.position || '',
+        weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
+    }));
+
+    // 第一步:按课程、周次排序后合并连续节次,同时剔除完全重复项
+    list.sort((a, b) =>
+        a.name.localeCompare(b.name) ||
+        a.teacher.localeCompare(b.teacher) ||
+        a.position.localeCompare(b.position) ||
+        (a.day || 0) - (b.day || 0) ||
+        a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
+        (a.startSection || 0) - (b.startSection || 0)
+    );
+
+    const step1 = [];
+    let current = list[0];
+
+    for (let i = 1; i < list.length; i++) {
+        const next = list[i];
+
+        const isSameCourse =
+            current.name === next.name &&
+            current.teacher === next.teacher &&
+            current.position === next.position &&
+            current.day === next.day &&
+            current.weeks.join(',') === next.weeks.join(',');
+
+        if (isSameCourse && current.endSection + 1 === next.startSection) {
+            // 节次紧邻,延长结束节次:1-2 节 + 3-4 节 -> 1-4 节
+            current.endSection = next.endSection;
+        } else if (isSameCourse && current.startSection === next.startSection && current.endSection === next.endSection) {
+            // 完全重复的记录,跳过
+            continue;
+        } else {
+            step1.push(current);
+            current = next;
+        }
+    }
+    step1.push(current);
+
+    // 第二步:按课程、节次排序后合并相同节次的周次
+    step1.sort((a, b) =>
+        a.name.localeCompare(b.name) ||
+        a.teacher.localeCompare(b.teacher) ||
+        a.position.localeCompare(b.position) ||
+        (a.day || 0) - (b.day || 0) ||
+        (a.startSection || 0) - (b.startSection || 0) ||
+        (a.endSection || 0) - (b.endSection || 0)
+    );
+
+    const step2 = [];
+    let cur = step1[0];
+
+    for (let i = 1; i < step1.length; i++) {
+        const nxt = step1[i];
+
+        const isSameSection =
+            cur.name === nxt.name &&
+            cur.teacher === nxt.teacher &&
+            cur.position === nxt.position &&
+            cur.day === nxt.day &&
+            cur.startSection === nxt.startSection &&
+            cur.endSection === nxt.endSection;
+
+        if (isSameSection) {
+            // 周次取并集:1-8 周 + 9-16 周 -> 1-16 周
+            cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
+        } else {
+            step2.push(cur);
+            cur = nxt;
+        }
+    }
+    step2.push(cur);
+
+    return step2;
+}
+
+// ==================== 特殊作息处理 ====================
+
+/**
+ * 判断位置是否命中特殊场地(指定楼或室外场地),返回命中的类型与关键词
+ * 楼名与室外关键词取并集,包含任一即可;命中者打标特殊作息
+ * @returns {{type: 'venue'|'outdoor', key: string}|null}
+ */
+function matchesSpecialVenue(positionText, campusConfig) {
+    const venueHit = campusConfig.venues.find(venue => positionText.includes(venue));
+    if (venueHit) return { type: 'venue', key: venueHit };
+    const patternHit = (campusConfig.venuePatterns || []).find(p => p.pattern.test(positionText));
+    if (patternHit) return { type: 'venue', key: patternHit.name };
+    const outdoorHit = campusConfig.outdoorKeywords.find(keyword => positionText.includes(keyword));
+    if (outdoorHit) return { type: 'outdoor', key: outdoorHit };
+    return null;
+}
+
+/**
+ * 判断课程是否命中特殊作息(正向策略)
+ * 命中指定楼/室外场地的课程,在节次恰为特殊时间块(3-4/7-8 节)时打标特殊时间;
+ * 其他普通教室不打标,使用 TimeSlots 全校统一作息。
+ * 返回对象附带 reason 判定原因,供内部诊断与本地验证脚本使用(不写入导出课程)。
+ */
+function getCustomTime(position, startSection, endSection, campusConfig) {
+    const positionText = position == null ? '' : String(position);
+    const hit = matchesSpecialVenue(positionText, campusConfig);
+    if (!hit) return { marked: false, reason: 'no-block' };
+
+    const block = SPECIAL_TIME_BLOCKS.find(
+        b => b.startSection === startSection && b.endSection === endSection
+    );
+    if (block) return { marked: true, startTime: block.startTime, endTime: block.endTime, reason: `special-${hit.type}:${hit.key}` };
+    return { marked: false, reason: `special-${hit.type}:${hit.key}-no-block` };
+}
+
+// ==================== 数据解析 ====================
+
+/**
+ * 解析正方 v9 课表接口返回的 JSON,提取有效课程
+ * 数据位于 kbList 字段;课程名/星期/节次/周次缺失或不合法的记录会被跳过,
+ * 教师、教室允许为空
+ */
+function parseJsonData(jsonData, campusConfig) {
+    if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
+
+    const courses = [];
+
+    for (const raw of jsonData.kbList) {
+        if (!raw || typeof raw !== 'object') continue;
+        if (!raw.kcmc || raw.xqj == null || raw.jcs == null || raw.zcd == null) continue;
+
+        const weeks = parseWeeks(raw.zcd);
+        if (weeks.length === 0) continue;
+
+        const sectionRange = parseSectionRange(raw.jcs);
+        if (!sectionRange) continue;
+
+        const day = Number(raw.xqj); // 1=周一 ... 7=周日
+        if (isNaN(day) || day < 1 || day > 7) continue;
+
+        // 直接基于原始接口字段 cdmc 构造课程位置
+        const position = raw.cdmc == null ? '' : String(raw.cdmc).trim();
+
+        const course = {
+            name: normalizeCourseName(raw.kcmc),
+            teacher: raw.xm == null ? '' : String(raw.xm).trim(),
+            position,
+            day,
+            startSection: sectionRange.startSection,
+            endSection: sectionRange.endSection,
+            weeks
+        };
+
+        // 边解析边判断:直接对原始教室字段 cdmc 判断是否命中特殊作息,
+        // 命中则在写入课程对象的同时打好 isCustomTime 标记,App 将优先显示自定义时间
+        const customTime = getCustomTime(position, course.startSection, course.endSection, campusConfig);
+        if (customTime.marked) {
+            course.isCustomTime = true;
+            course.customStartTime = customTime.startTime;
+            course.customEndTime = customTime.endTime;
+        }
+
+        courses.push(course);
+    }
+
+    const mergedCourses = mergeAndDistinctCourses(courses);
+
+    // 合并可能改变节次区间(如 1-2 节 + 3-4 节 -> 1-4 节),对已打标课程做最终校验:
+    // 合并后的区间不再精确命中特殊时间块时,撤销打标,避免特殊时间被错误扩散
+    return mergedCourses.map(course => {
+        if (!course.isCustomTime) return course;
+        const customTime = getCustomTime(course.position, course.startSection, course.endSection, campusConfig);
+        if (!customTime.marked) {
+            const plain = { ...course };
+            delete plain.isCustomTime;
+            delete plain.customStartTime;
+            delete plain.customEndTime;
+            return plain;
+        }
+        return course;
+    });
+}
+
+// ==================== 日期工具 ====================
+
+/**
+ * 把教务返回的日期字段规范为 yyyy-MM-dd
+ * 兼容 "-"、"."、"/" 以及中文"年月日"等分隔写法
+ */
+function normalizeStartDate(value) {
+    const match = String(value || "").match(/(\d{4})[-\/.年](\d{1,2})[-\/.月](\d{1,2})/);
+    if (!match) return null;
+    return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
+}
+
+/**
+ * 在校历响应中查找第 1 周开学日期
+ * 兼容顶层数组、data/list/rows 等包装对象,以及 zrq/zcrq/rq/ksrq 字段
+ */
+function findSemesterStartDate(value) {
+    if (value == null) return null;
+
+    if (typeof value !== "object") return normalizeStartDate(value);
+
+    if (Array.isArray(value)) {
+        const firstWeek = value.find(item =>
+            item && typeof item === "object" &&
+            (String(item.zs) === "1" || String(item.zsmc) === "1")
+        ) || value[0];
+        const found = findSemesterStartDate(firstWeek);
+        if (found) return found;
+
+        for (const item of value) {
+            const date = findSemesterStartDate(item);
+            if (date) return date;
+        }
+        return null;
+    }
+
+    for (const field of ["zrq", "zcrq", "rq", "ksrq"]) {
+        const date = normalizeStartDate(value[field]);
+        if (date) return date;
+    }
+
+    for (const item of Object.values(value)) {
+        const date = findSemesterStartDate(item);
+        if (date) return date;
+    }
+
+    return null;
+}
+
+// ==================== 接口地址推导 ====================
+
+/**
+ * 推导教务系统接口前缀,兼容两条入口通道:
+ *   GDOU_01 内网直连:pathname 形如 /kbcx/xskbcx_cxXsgrkb.html                    → 前缀为 ""
+ *   反代·拼接态:      pathname 形如 /https://jw.gdou.edu.cn/kbcx/xskbcx_...html   → 前缀为 "/https://jw.gdou.edu.cn"
+ *   反代·哈希态:      pathname 形如 /http/<hash>/kbcx/xskbcx_...html              → 前缀为 "/http/<hash>"
+ * 以 "/kbcx/" 为锚点即可同时覆盖以上三种情况。
+ */
+function getScheduleBase() {
+    const path = (window.location && window.location.pathname) || "";
+
+    const kbIndex = path.indexOf("/kbcx/");
+    if (kbIndex >= 0) return path.slice(0, kbIndex);
+
+    // 兜底:停留在教务系统非课表页(例如首页)时,直接识别反代前缀。
+    const proxyPrefix = path.match(/^\/(?:https?:\/\/[^/]+|(?:http|https|https-443)\/[^/]+)/i);
+    return proxyPrefix ? proxyPrefix[0] : "";
+}
+
+/**
+ * 拼接教务系统接口地址,自动带上直连/反代前缀
+ * @param {string} modulePath 接口文件名,例如 "xskbcx_cxXsgrkb.html"
+ * @param {string} query 可选查询串,例如 "gnmkdm=N2151"
+ */
+function buildScheduleUrl(modulePath, query) {
+    const base = getScheduleBase();
+    const queryString = query ? `?${query}` : "";
+    return `${window.location.origin}${base}/kbcx/${modulePath}${queryString}`;
+}
+
+// ==================== 零信任门户处理 ====================
+// 以下逻辑移植自 gdouyj.js:当用户经零信任入口登录后
+// 落在 wfw 移动门户首页而非课表页时,用内嵌 iframe 打开代理课表页,
+// 保证接口地址可推导、学年学期选项可读取。
+
+/**
+ * 从 select 元素解析学年和学期选项。
+ * 默认索引优先使用当前 select.value,确保跟随用户在页面上的实际选择。
+ */
+function parseSelectOptions(selectElement) {
+    if (!selectElement || typeof selectElement.querySelectorAll !== "function") {
+        return { options: [], defaultIndex: 0 };
+    }
+
+    const options = [];
+    let defaultIndex = 0;
+    Array.from(selectElement.querySelectorAll("option")).forEach(option => {
+        const value = String(option.value || "").trim();
+        if (!value) return;
+
+        const text = String(option.textContent || "").trim() || value;
+        if (option.selected) defaultIndex = options.length;
+        options.push({ value, text });
+    });
+
+    const currentValue = String(selectElement.value || "").trim();
+    const currentIndex = options.findIndex(option => option.value === currentValue);
+    if (currentIndex !== -1) defaultIndex = currentIndex;
+
+    return { options, defaultIndex };
+}
+
+function parseAcademicOptionsFromDocument(doc) {
+    if (!doc || typeof doc.querySelector !== "function") return null;
+
+    const yearData = parseSelectOptions(doc.querySelector("#xnm"));
+    const semesterData = parseSelectOptions(doc.querySelector("#xqm"));
+    if (yearData.options.length === 0 || semesterData.options.length === 0) return null;
+
+    return {
+        yearOptions: yearData.options,
+        semesterOptions: semesterData.options,
+        defaultYearIndex: yearData.defaultIndex,
+        defaultSemesterIndex: semesterData.defaultIndex
+    };
+}
+
+function isOnTimetablePage() {
+    const pathname = typeof window !== "undefined" && window.location
+        ? window.location.pathname
+        : "";
+    return typeof pathname === "string" && pathname.includes("xskbcx_cxXskbcxIndex.html");
+}
+
+function getCurrentPageAcademicOptions() {
+    const frame = typeof document !== "undefined"
+        ? /** @type {HTMLIFrameElement | null} */ (document.getElementById("gdouyj-timetable-frame"))
+        : null;
+    if (frame) {
+        try {
+            return parseAcademicOptionsFromDocument(frame.contentDocument);
+        } catch (error) {
+            return null;
+        }
+    }
+    if (!isOnTimetablePage() || typeof document === "undefined" || !document.querySelector) {
+        return null;
+    }
+
+    return parseAcademicOptionsFromDocument(document);
+}
+
+/**
+ * WFW 移动门户生成的代理前缀会使页面资源跳转到登录页。
+ * 只修正本校 WFW 前缀,保留学校原页面和原查询逻辑。
+ */
+function normalizeWfwPageHtml(html, origin) {
+    const prefix = `${origin}/https://jw.gdou.edu.cn`;
+    const escapedPrefix = prefix.replace(/\//g, "\\/");
+    const escapedOrigin = origin.replace(/\//g, "\\/");
+    return html.split(prefix).join(origin).split(escapedPrefix).join(escapedOrigin);
+}
+
+async function prepareWfwTimetableHtml(html, origin) {
+    const page = new DOMParser().parseFromString(normalizeWfwPageHtml(html, origin), "text/html");
+    for (const existing of Array.from(page.querySelectorAll("base"))) existing.remove();
+    const base = page.createElement("base");
+    base.href = `${origin}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
+    page.head.prepend(base);
+    // 顺序获取原站依赖,避免 WFW 同时加载大量资源时返回 503 后留下半成品页面。
+    for (const script of Array.from(page.querySelectorAll("script[src]"))) {
+        const url = new URL(script.getAttribute("src"), `${origin}/`);
+        if (url.origin !== origin) throw new Error("课表页包含非同源脚本,已停止打开");
+        let response;
+        for (let attempt = 0; attempt < 3; attempt++) {
+            response = await fetch(url.href, { credentials: "include", cache: "no-store" });
+            if (response.status !== 503) break;
+            if (attempt < 2) await new Promise(resolve => setTimeout(resolve, 500));
+        }
+        if (!response.ok) throw new Error(`页面资源加载失败:${url.pathname},HTTP ${response.status}`);
+        const type = response.headers.get("content-type") || "";
+        if (!/(?:javascript|ecmascript)/i.test(type)) {
+            throw new Error("页面资源未返回脚本,请重新登录");
+        }
+        const code = normalizeWfwPageHtml(await response.text(), origin);
+        script.removeAttribute("src");
+        script.removeAttribute("async");
+        script.removeAttribute("defer");
+        script.textContent = code.replace(/<\/script/gi, "<\\/script");
+    }
+    return `<!doctype html>\n${page.documentElement.outerHTML}`;
+}
+
+async function openTimetableFromMobilePortal() {
+    if (window.location.hostname !== "wfw.gdou.edu.cn" ||
+        window.location.pathname !== "/xtgl/index_cxAllApp.html" ||
+        document.getElementById("gdouyj-timetable-frame")) {
+        return false;
+    }
+
+    const confirmed = await window.shiguangBridgePromise.showAlert(
+        "打开课表",
+        "这里暂时看不到课表。点“打开课表”后,请确认页面上的学年和学期,再点一次拾光的“导入”按钮保存课程。",
+        "打开课表"
+    );
+    if (!confirmed) return true;
+
+    try {
+        const url = buildScheduleUrl("xskbcx_cxXskbcxIndex.html", "gnmkdm=N2151&layout=default");
+        const response = await fetch(url, { credentials: "include" });
+        if (!response.ok) throw new Error(`HTTP ${response.status}`);
+        const html = await response.text();
+        const parsed = new DOMParser().parseFromString(html, "text/html");
+        if (!parseAcademicOptionsFromDocument(parsed)) {
+            throw new Error("未取得个人课表页面,请重新登录;必要时在登录前切换电脑模式");
+        }
+        window.shiguangBridge.showToast("正在加载个人课表页面,请稍候...");
+        const preparedHtml = await prepareWfwTimetableHtml(html, window.location.origin);
+
+        const panel = document.createElement("div");
+        panel.id = "gdouyj-timetable-panel";
+        panel.style.cssText = "position:fixed;inset:0;z-index:2147483647;display:flex;flex-direction:column;background:white";
+        const toolbar = document.createElement("div");
+        toolbar.style.cssText = "display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:#087ebc;color:white;font:16px sans-serif";
+        const label = document.createElement("span");
+        label.textContent = "确认学年学期后,再点“导入”";
+        const close = document.createElement("button");
+        close.textContent = "返回";
+        close.type = "button";
+        const previousTitle = document.title;
+        close.onclick = () => {
+            panel.remove();
+            document.title = previousTitle;
+        };
+        toolbar.append(label, close);
+        const frame = document.createElement("iframe");
+        frame.id = "gdouyj-timetable-frame";
+        frame.title = "广东海洋大学个人课表查询";
+        frame.style.cssText = "flex:1;min-height:0;width:100%;border:0;background:white";
+        frame.srcdoc = preparedHtml;
+        panel.append(toolbar, frame);
+        document.body.appendChild(panel);
+        document.title = "个人课表查询";
+    } catch (error) {
+        window.shiguangBridge.showToast(`打开课表页面失败:${error.message}`);
+    }
+    return true;
+}
+
+// ==================== 教务接口 ====================
+
+/**
+ * 读取课表查询页里的学年/学期下拉选项
+ * 成功返回 { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex };
+ * 读取失败返回 null,由调用方回退到默认值
+ */
+async function fetchAcademicOptions() {
+    const currentPageOptions = getCurrentPageAcademicOptions();
+    if (currentPageOptions) {
+        console.log("JS: 使用当前课表页的学年学期选项。");
+        return currentPageOptions;
+    }
+
+    const url = buildScheduleUrl("xskbcx_cxXskbcxIndex.html", "gnmkdm=N2151&layout=default");
+
+    try {
+        const response = await fetch(url, { method: "GET", credentials: "include" });
+        if (!response.ok) return null;
+
+        const doc = new DOMParser().parseFromString(await response.text(), "text/html");
+        const optionsData = parseAcademicOptionsFromDocument(doc);
+        if (!optionsData) return null;
+
+        // 学年下拉只保留默认学年附近的范围,避免选项过多
+        const selectedYearIndex = optionsData.defaultYearIndex;
+        const start = Math.max(0, selectedYearIndex - 2);
+        const end = Math.min(optionsData.yearOptions.length, selectedYearIndex + 3);
+
+        return {
+            ...optionsData,
+            yearOptions: optionsData.yearOptions.slice(start, end),
+            defaultYearIndex: selectedYearIndex - start
+        };
+    } catch (error) {
+        return null;
+    }
+}
+
+/**
+ * 查询指定学期的周次安排,取出第 1 周的日期作为开学日期,并返回该学期总周数
+ * 接口失败时返回 null,不影响主流程
+ */
+async function fetchSemesterInfo(academicYear, semesterCode) {
+    const url = buildScheduleUrl("xskbcxZccx_cxZcByXnxq.html", "gnmkdm=N2154");
+    const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
+
+    try {
+        const response = await fetch(url, {
+            method: "POST",
+            headers: {
+                "accept": "application/json, text/javascript, */*; q=0.01",
+                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
+                "x-requested-with": "XMLHttpRequest"
+            },
+            body,
+            credentials: "include"
+        });
+
+        if (!response.ok) return null;
+
+        const weeks = await response.json();
+        if (!Array.isArray(weeks) || weeks.length === 0) return null;
+
+        return {
+            startDate: findSemesterStartDate(weeks),
+            totalWeeks: weeks.length
+        };
+    } catch (e) {
+        return null;
+    }
+}
+
+/**
+ * 请求课表接口并解析课程,同时并行获取学期信息
+ * 成功返回 { courses, config },失败返回 null
+ */
+async function fetchAndParseCourses(academicYear, semesterCode, campusConfig) {
+    const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
+    const courseUrl = buildScheduleUrl("xskbcx_cxXsgrkb.html", "gnmkdm=N2151");
+
+    try {
+        const [courseResponse, semesterInfo] = await Promise.all([
+            fetch(courseUrl, {
+                method: "POST",
+                headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
+                body,
+                credentials: "include"
+            }),
+            fetchSemesterInfo(academicYear, semesterCode)
+        ]);
+
+        if (!courseResponse.ok) {
+            window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}。如当前不在校园网内,请返回选择“广东海洋大学教务(校外通道)”重试。`);
+            return null;
+        }
+
+        const courses = parseJsonData(JSON.parse(await courseResponse.text()), campusConfig);
+
+        if (courses.length === 0) {
+            window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期选择或登录状态。");
+            return null;
+        }
+
+        // 总周数取接口返回值与课程最大周次中的较大者,保证不截断课表
+        const maxCourseWeek = courses.reduce((max, c) => Math.max(max, ...c.weeks), 0);
+
+        return {
+            courses,
+            config: {
+                semesterStartDate: semesterInfo ? semesterInfo.startDate : null,
+                semesterTotalWeeks: Math.max(maxCourseWeek, semesterInfo ? semesterInfo.totalWeeks : 20)
+            }
+        };
+    } catch (e) {
+        window.shiguangBridge.showToast("获取课表失败,请确认已登录且网络可访问 jw.gdou.edu.cn;如当前不在校园网内,请返回选择“广东海洋大学教务(校外通道)”重试。");
+        return null;
+    }
+}
+
+// ==================== 交互 ====================
+
+/**
+ * 按当前月份推断学年起始年份:9 月及以后属于新学年,其余月份沿用上一学年
+ */
+function getDefaultAcademicYear(date = new Date()) {
+    const currentYear = date.getFullYear();
+    return (date.getMonth() >= 8 ? currentYear : currentYear - 1).toString();
+}
+
+/**
+ * 弹出导入确认提示,说明使用前提
+ */
+async function promptUserToStart() {
+    return await window.shiguangBridgePromise.showAlert(
+        "广东海洋大学教务系统课表导入",
+        "导入前请确认已在浏览器中登录教务系统(jw.gdou.edu.cn)。\n脚本将通过接口直接获取课表,无需停留在特定页面。",
+        "好的,开始导入"
+    );
+}
+
+/**
+ * 弹出校区选择框,决定使用哪套特殊作息规则
+ * 取消返回 null,由调用方终止流程
+ */
+async function selectCampus() {
+    const campusIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择校区",
+        JSON.stringify(CAMPUS_CONFIGS.map(item => item.label)),
+        0
+    );
+    if (campusIndex === null || campusIndex === -1) return null;
+    return CAMPUS_CONFIGS[campusIndex];
+}
+
+/**
+ * 依次弹出学年、学期选择框
+ * 选项优先来自教务系统;若读取失败,则按当前月份给出默认学年,
+ * 学期码(3=第一学期,12=第二学期)
+ */
+async function selectAcademicYearAndSemester() {
+    const options = await fetchAcademicOptions();
+
+    let yearOptions;
+    let semesterOptions;
+    let defaultYearIndex;
+    let defaultSemesterIndex;
+
+    if (options) {
+        ({ yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = options);
+    } else {
+        const year = getDefaultAcademicYear();
+        const isFirstSemester = new Date().getMonth() >= 8;
+        yearOptions = [{ value: year, text: `${year}-${Number(year) + 1}` }];
+        semesterOptions = [
+            { value: "3", text: "第一学期" },
+            { value: "12", text: "第二学期" }
+        ];
+        defaultYearIndex = 0;
+        defaultSemesterIndex = isFirstSemester ? 0 : 1;
+        window.shiguangBridge.showToast("未读取到教务系统学年学期选项,已使用默认值,请核对。");
+    }
+
+    const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择学年",
+        JSON.stringify(yearOptions.map(item => item.text)),
+        defaultYearIndex
+    );
+    if (yearIndex === null || yearIndex === -1) return null;
+
+    const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择学期",
+        JSON.stringify(semesterOptions.map(item => item.text)),
+        defaultSemesterIndex
+    );
+    if (semesterIndex === null || semesterIndex === -1) return null;
+
+    return {
+        academicYear: yearOptions[yearIndex].value,
+        semesterCode: semesterOptions[semesterIndex].value
+    };
+}
+
+// ==================== 保存 ====================
+
+async function saveCourses(courses) {
+    try {
+        await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
+        return true;
+    } catch (error) {
+        window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
+        return false;
+    }
+}
+
+/**
+ * 将预设作息时间导入 App
+ */
+async function importPresetTimeSlots(timeSlots) {
+    if (timeSlots.length === 0) {
+        window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
+        return;
+    }
+
+    try {
+        await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
+        window.shiguangBridge.showToast("预设时间段导入成功!");
+    } catch (error) {
+        window.shiguangBridge.showToast("导入时间段失败: " + error.message);
+    }
+}
+
+// ==================== 主流程 ====================
+
+async function runImportFlow() {
+    // 0. 零信任移动门户落地时,先引导打开课表页(移植自 gdouyj.js,仅门户首页触发)
+    if (await openTimetableFromMobilePortal()) return;
+
+    // 1. 确认导入
+    const confirmed = await promptUserToStart();
+    if (!confirmed) {
+        window.shiguangBridge.showToast("用户取消了导入。");
+        return;
+    }
+
+    // 2. 选择学年学期
+    const selection = await selectAcademicYearAndSemester();
+    if (!selection) {
+        window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
+        return;
+    }
+
+    // 3. 选择校区(决定特殊作息规则)
+    const campusConfig = await selectCampus();
+    if (!campusConfig) {
+        window.shiguangBridge.showToast("未选择校区,导入流程终止。");
+        return;
+    }
+
+    // 4. 拉取并解析课程
+    const result = await fetchAndParseCourses(selection.academicYear, selection.semesterCode, campusConfig);
+    if (result === null) return;
+    const { courses, config } = result;
+
+    // 5. 保存课程
+    if (!(await saveCourses(courses))) return;
+
+    // 6. 保存课表配置(开学日期、总周数)
+    try {
+        await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
+        let msg = `课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`;
+        if (config.semesterStartDate) msg += ` 开学日期:${config.semesterStartDate}`;
+        window.shiguangBridge.showToast(msg);
+    } catch (error) {
+        window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
+    }
+
+    // 7. 导入预设作息时间
+    await importPresetTimeSlots(TimeSlots);
+
+    window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
+    window.shiguangBridge.showToast(`若课程时间有误,请提交issue或联系开发者!`);
+    window.shiguangBridge.notifyTaskCompletion();
+}
+
+runImportFlow();
+})();

+ 8 - 0
resources/GZHMU/adapters.yaml

@@ -0,0 +1,8 @@
+adapters:
+  - adapter_id: "GZHMU_01"
+    adapter_name: "广州医科大学强智教务"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "gzhmu_01.js"
+    import_url: "https://webvpn.gzhmu.edu.cn/"
+    maintainer: "小漫君"
+    description: "校外请先登录学校 WebVPN,进入教务系统后点击导入。没有教务入口时用快速跳转打开 https://jwgl.gzhmu.edu.cn/jsxsd/framework/xsMainV.htmlx。支持选择学期,采用教务处公布的 16 节作息,医院见习时间请另行核对。"

+ 295 - 0
resources/GZHMU/gzhmu_01.js

@@ -0,0 +1,295 @@
+/**
+ * 广州医科大学强智教务,适配作者:小漫君。
+ * 请求和课表字段解析参考拾光仓库 GDCP/gdcp_01.js,周历参考
+ * ZHKU/zhku_lc6464.js(lc6464);保留原作者贡献及仓库 MIT License。
+ * GDCP 所记载的 HNIU、HHTC、NJFU、QFNU(Yumu-banxia)贡献一并保留。
+ * Copyright (c) 2025 星河欲转;上述文件的贡献历史保留在仓库中。
+ * 作息:https://jwc.gzhmu.edu.cn/info/1118/5748.htm(2018-2019-2 起执行)。
+ * 不保存账号密码;所有响应先校验,再通过官方 bridge 提交。
+ */
+
+function gzhmuText(value) {
+    return String(value == null ? '' : value).replace(/\u00a0/g, ' ').trim();
+}
+
+function gzhmuNormalize(value) {
+    return gzhmuText(value).replace(/\s+/g, '').replace(/[(]/g, '(')
+        .replace(/[)]/g, ')').replace(/[[【]/g, '[').replace(/[]】]/g, ']')
+        .replace(/[,、]/g, ',').replace(/[-–—~~]/g, '-');
+}
+
+function gzhmuTimeSlots() {
+    return [
+        { number: 1, startTime: '08:30', endTime: '09:10' },
+        { number: 2, startTime: '09:15', endTime: '09:55' },
+        { number: 3, startTime: '10:05', endTime: '10:45' },
+        { number: 4, startTime: '10:50', endTime: '11:30' },
+        { number: 5, startTime: '11:35', endTime: '12:15' },
+        { number: 6, startTime: '12:20', endTime: '13:00' },
+        { number: 7, startTime: '13:00', endTime: '13:40' },
+        { number: 8, startTime: '14:00', endTime: '14:40' },
+        { number: 9, startTime: '14:45', endTime: '15:25' },
+        { number: 10, startTime: '15:35', endTime: '16:15' },
+        { number: 11, startTime: '16:20', endTime: '17:00' },
+        { number: 12, startTime: '17:05', endTime: '17:45' },
+        { number: 13, startTime: '17:45', endTime: '18:25' },
+        { number: 14, startTime: '18:30', endTime: '19:10' },
+        { number: 15, startTime: '19:15', endTime: '19:55' },
+        { number: 16, startTime: '20:00', endTime: '20:40' }
+    ];
+}
+
+function gzhmuBaseUrl() {
+    const host = window.location.hostname;
+    const path = window.location.pathname.match(/^(.*?\/jsxsd)(?:\/|$)/);
+    if (!path || !(host === 'jwgl.gzhmu.edu.cn' || host === 'webvpn.gzhmu.edu.cn'
+        || host.endsWith('.webvpn.gzhmu.edu.cn'))) {
+        throw new Error('请先登录广州医科大学教务。校外请在学校 WebVPN 内进入教务系统,再点击导入。');
+    }
+    // 保留 WebVPN 的 /https/<代理标识>/ 前缀,不能跳回校内域名。
+    return window.location.origin + path[1] + '/';
+}
+
+function gzhmuCheckLogin(doc) {
+    if (doc.querySelector('input[type="password"]') || /登录|统一身份认证|Login/i.test(doc.title)) {
+        throw new Error('教务登录已失效,请通过学校 WebVPN 重新进入教务系统后再导入。');
+    }
+}
+
+async function gzhmuFetchDoc(url, options) {
+    const response = await fetch(url, { credentials: 'same-origin', ...options });
+    if (!response.ok) throw new Error('教务请求失败:HTTP ' + response.status);
+    const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
+    gzhmuCheckLogin(doc);
+    return doc;
+}
+
+function gzhmuTerms(doc) {
+    const select = doc.querySelector('#xnxq01id');
+    if (!select) throw new Error('未找到学期列表,请确认已进入教务系统。');
+    const terms = [];
+    const ids = new Set();
+    let selectedIndex = -1;
+    for (const option of select.options) {
+        const id = gzhmuText(option.value);
+        if (!id || option.disabled) continue;
+        if (ids.has(id)) throw new Error('教务返回了重复的学期标识,已停止导入。');
+        ids.add(id);
+        if (option.selected) selectedIndex = terms.length;
+        terms.push({ id, name: gzhmuText(option.textContent) || id });
+    }
+    if (!terms.length) throw new Error('教务没有返回可选学期。');
+    return { terms, selectedIndex };
+}
+
+function gzhmuCheckTerm(doc, termId) {
+    const select = doc.querySelector('#xnxq01id');
+    if (!select || gzhmuText(select.value) !== termId) {
+        throw new Error('教务返回的学期与所选学期不一致,已停止导入。');
+    }
+}
+
+function gzhmuParseWeeks(value, max) {
+    const label = '课程周次';
+    const text = gzhmuNormalize(value).replace(/第/g, '').replace(/\(周\)/g, '')
+        .replace(/\((单|双)周\)/g, '($1)').replace(/周/g, '');
+    const numbers = new Set();
+    for (const part of text.split(',')) {
+        const match = part.match(/^(\d+)(?:-(\d+))?(?:\((单|双)\))?$/);
+        if (!match) throw new Error(label + '格式无法识别,已停止导入。');
+        const start = Number(match[1]);
+        const end = Number(match[2] || match[1]);
+        if (start < 1 || end < start || end > max) throw new Error(label + '超出范围,已停止导入。');
+        for (let number = start; number <= end; number++) {
+            if (!match[3] || number % 2 === (match[3] === '单' ? 1 : 0)) numbers.add(number);
+        }
+    }
+    if (!numbers.size) throw new Error(label + '为空,已停止导入。');
+    return Array.from(numbers).sort((a, b) => a - b);
+}
+
+function gzhmuSectionRanges(numbers) {
+    const ranges = [];
+    for (const number of numbers) {
+        const last = ranges[ranges.length - 1];
+        if (last && number === last.endSection + 1) last.endSection = number;
+        else ranges.push({ startSection: number, endSection: number });
+    }
+    return ranges;
+}
+
+function gzhmuCourses(doc, totalWeeks) {
+    const table = doc.querySelector('#timetable');
+    if (!table || !table.rows.length) throw new Error('未找到学期课表 #timetable。');
+    const headers = Array.from(table.rows[0].cells).slice(1).map(cell => gzhmuText(cell.textContent));
+    if (headers.join(',') !== '星期一,星期二,星期三,星期四,星期五,星期六,星期日') {
+        throw new Error('课表星期列顺序无法识别,已停止导入。');
+    }
+    const grouped = new Map();
+    for (const row of table.rows) {
+        const cells = row.querySelectorAll(':scope > td');
+        if (cells.length !== 7) continue; // 表头与页脚不是课程行。
+        for (let column = 0; column < cells.length; column++) {
+            for (const original of cells[column].querySelectorAll('.kbcontent')) {
+                const content = original.cloneNode(true);
+                content.querySelectorAll('.item-box').forEach(item => item.remove());
+                for (const html of content.innerHTML.split(/-{10,}\s*<br\s*\/?>/i)) {
+                    const block = new DOMParser().parseFromString(html, 'text/html');
+                    if (!gzhmuText(block.body.textContent)) continue;
+                    const name = gzhmuText(block.querySelector('font:not([title])')?.textContent);
+                    const teacher = block.querySelector('font[title="教师"]');
+                    const position = block.querySelector('font[title="教室"]');
+                    const time = block.querySelector('font[title="周次(节次)"]');
+                    const match = time && gzhmuNormalize(time.textContent).match(/^(.*?)\[(\d+(?:-\d+)*)节\]$/);
+                    if (!name || !teacher || !position || !match) throw new Error('课程字段不完整,已停止导入。');
+                    const weeks = gzhmuParseWeeks(match[1], totalWeeks);
+                    // 接口逐项列举节次,例如 01-02-03-04;不能将 01-03 擅自补为三节。
+                    const sections = match[2].split('-').map(Number);
+                    if (sections.some(section => section < 1 || section > 16)) throw new Error('课程节次超出作息范围。');
+                    const day = column + 1;
+                    const fields = { day, name, teacher: gzhmuText(teacher.textContent), position: gzhmuText(position.textContent) };
+                    const key = JSON.stringify(fields);
+                    if (!grouped.has(key)) grouped.set(key, { ...fields, occurrences: new Map() });
+                    const occurrences = grouped.get(key).occurrences;
+                    for (const week of weeks) {
+                        if (!occurrences.has(week)) occurrences.set(week, new Set());
+                        for (const section of sections) occurrences.get(week).add(section);
+                    }
+                }
+            }
+        }
+    }
+    const courses = [];
+    for (const course of grouped.values()) {
+        const ranges = new Map();
+        for (const [week, sections] of course.occurrences) {
+            for (const range of gzhmuSectionRanges(Array.from(sections).sort((a, b) => a - b))) {
+                const key = JSON.stringify(range);
+                if (!ranges.has(key)) ranges.set(key, { name: course.name, teacher: course.teacher, position: course.position,
+                    day: course.day, weeks: [], isCustomTime: false, ...range });
+                ranges.get(key).weeks.push(week);
+            }
+        }
+        for (const range of ranges.values()) courses.push({ ...range, weeks: range.weeks.sort((a, b) => a - b) });
+    }
+    if (!courses.length) throw new Error('所选学期没有可识别的固定课程,未保存任何数据。');
+    return courses;
+}
+
+function gzhmuDate(value) {
+    const match = gzhmuText(value).match(/(\d{4})(?:年|-)(\d{1,2})(?:月|-)(\d{1,2})(?:日)?/);
+    if (!match) throw new Error('周历缺少完整日期,已停止导入。');
+    const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
+    const date = new Date(Date.UTC(year, month - 1, day));
+    if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
+        throw new Error('周历日期无效,已停止导入。');
+    }
+    return date;
+}
+
+function gzhmuApplyTimeDifferences(doc, courses, slots) {
+    for (const row of doc.querySelector('#timetable').rows) {
+        if (row.querySelectorAll(':scope > td').length !== 7) continue;
+        const header = gzhmuNormalize(row.querySelector(':scope > th')?.textContent);
+        const match = header.match(/\((\d+(?:,\d+)*)小节\)(\d{2}:\d{2})-(\d{2}:\d{2})$/);
+        if (!match) throw new Error('课表缺少节次时钟,无法核对作息。');
+        const sections = match[1].split(',').map(Number);
+        const first = sections[0], last = sections[sections.length - 1];
+        if (!slots[first - 1] || !slots[last - 1]) throw new Error('课表时段超出公开作息范围。');
+        const changedStart = match[2] !== slots[first - 1].startTime;
+        const changedEnd = match[3] !== slots[last - 1].endTime;
+        if (!changedStart && !changedEnd) continue;
+        // 实测历史学期第 6–7 节为 12:20–13:45;保留教务明确给出的整段时钟。
+        // 若课程只占发生差异的部分,不能从整段时长反推单节时间。
+        for (const course of courses) {
+            const touches = section => course.startSection <= section && course.endSection >= section;
+            if (!(changedStart && touches(first)) && !(changedEnd && touches(last))) continue;
+            if (course.startSection > first || course.endSection < last) {
+                throw new Error('教务时段 ' + first + '–' + last + ' 节与公开作息不同,无法确定其中单节时间。');
+            }
+            course.customStartTime = course.startSection === first ? match[2]
+                : course.customStartTime || slots[course.startSection - 1].startTime;
+            course.customEndTime = course.endSection === last ? match[3]
+                : course.customEndTime || slots[course.endSection - 1].endTime;
+            course.isCustomTime = true;
+        }
+    }
+}
+
+function gzhmuCalendar(doc, termId) {
+    gzhmuCheckTerm(doc, termId);
+    const table = doc.querySelector('#kbtable');
+    if (!table) throw new Error('未找到教学周历 #kbtable,无法确定所选学期的开学日期。');
+    const weeks = new Map();
+    for (const row of table.rows) {
+        const numberText = gzhmuText(row.cells[0]?.textContent);
+        if (!/^\d+$/.test(numberText)) continue;
+        const week = Number(numberText);
+        if (weeks.has(week)) throw new Error('周历出现重复周次,已停止导入。');
+        const date = gzhmuDate(row.cells[1]?.getAttribute('title'));
+        if (date.getUTCDay() !== 1) throw new Error('周历周一日期不正确,已停止导入。');
+        weeks.set(week, date);
+    }
+    if (!weeks.has(1)) throw new Error('周历没有第一教学周的周一日期。');
+    const start = weeks.get(1);
+    let totalWeeks = 0;
+    for (const [week, monday] of weeks) {
+        if (monday.getTime() !== start.getTime() + (week - 1) * 7 * 86400000) {
+            throw new Error('周历日期与周次不一致,已停止导入。');
+        }
+        totalWeeks = Math.max(totalWeeks, week);
+    }
+    if (weeks.size !== totalWeeks) throw new Error('周历存在缺失周次,已停止导入。');
+    const term = termId.match(/^(\d{4})-(\d{4})-([12])$/);
+    if (term && (Number(term[2]) !== Number(term[1]) + 1
+        || start.getUTCFullYear() !== Number(term[term[3] === '1' ? 1 : 2]))) {
+        throw new Error('周历年份与所选学期不一致,已停止导入。');
+    }
+    return { semesterStartDate: start.toISOString().slice(0, 10), semesterTotalWeeks: totalWeeks,
+        defaultClassDuration: 40, defaultBreakDuration: 5, firstDayOfWeek: 1 };
+}
+
+async function gzhmuRunImport() {
+    const bridge = window.shiguangBridgePromise;
+    try {
+        if (!bridge || !window.shiguangBridge) throw new Error('请在支持拾光教务桥接的应用或官方测试器中运行。');
+        const base = gzhmuBaseUrl();
+        window.shiguangBridge.showToast('正在获取广医学期列表…');
+        const endpoint = base + 'xskb/xskb_list.do';
+        const entry = await gzhmuFetchDoc(endpoint, { method: 'GET' });
+        const { terms, selectedIndex } = gzhmuTerms(entry);
+        const mode = entry.querySelector('#kbjcmsid')?.value;
+        if (!mode) throw new Error('未获取到教务节次模式,已停止导入。');
+        const choice = await bridge.showSingleSelection('选择导入学期', JSON.stringify(terms.map(term => term.name)), selectedIndex);
+        if (choice == null) return;
+        const index = Number(choice);
+        if ((typeof choice !== 'number' && !/^\d+$/.test(choice))
+            || !Number.isInteger(index) || index < 0 || index >= terms.length) throw new Error('未选择有效学期。');
+        const term = terms[index];
+        // 即使选中当前学期,也显式请求整学期,避免复用入口的周筛选结果。
+        const schedule = await gzhmuFetchDoc(endpoint, { method: 'POST',
+            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+            body: new URLSearchParams({ cj0701id: '', zc: '', demo: '', xnxq01id: term.id, sfFD: '1', kbjcmsid: mode }).toString() });
+        gzhmuCheckTerm(schedule, term.id);
+        const calendarDoc = await gzhmuFetchDoc(base + 'jxzl/jxzl_query', { method: 'POST',
+            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+            body: new URLSearchParams({ xnxq01id: term.id }).toString() });
+        const config = gzhmuCalendar(calendarDoc, term.id);
+        const courses = gzhmuCourses(schedule, config.semesterTotalWeeks);
+        const slots = gzhmuTimeSlots();
+        gzhmuApplyTimeDifferences(schedule, courses, slots);
+        for (const [method, data] of [['saveCourseConfig', config], ['savePresetTimeSlots', slots], ['saveImportedCourses', courses]]) {
+            const saved = await bridge[method](JSON.stringify(data));
+            if (saved !== true && saved !== 'true') throw new Error('保存失败(' + method + '),导入未完成。');
+        }
+        window.shiguangBridge.showToast('已提交 ' + courses.length + ' 条课程,请在预览中核对后确认。');
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        const message = error instanceof Error ? error.message : '教务导入异常。';
+        if (bridge) await bridge.showAlert('导入未完成', message, '知道了');
+        else if (window.shiguangBridge) window.shiguangBridge.showToast(message);
+        else console.error(message);
+    }
+}
+
+gzhmuRunImport();

+ 9 - 0
resources/XSYU/adapters.yaml

@@ -0,0 +1,9 @@
+# resources/XSYU/adapters.yaml
+adapters:
+  - adapter_id: "XSYU_01"
+    adapter_name: "西安石油大学超星教务"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "xsyu_01.js"
+    import_url: "https://jiaowu.xsyu.edu.cn/admin/login"
+    maintainer: "dr1am1"
+    description: "西安石油大学超星综合教学管理系统(jiaowu.xsyu.edu.cn)课表导入,自动识别当前学期与校区,导入课程、作息时间、开学日期与总周数;支持账密登录与统一认证登录"

+ 356 - 0
resources/XSYU/xsyu_01.js

@@ -0,0 +1,356 @@
+// 西安石油大学(jiaowu.xsyu.edu.cn) 拾光课程表适配脚本
+// 教务系统:超星综合教学管理系统(dbname = xasydx)
+// 使用流程:登录教务系统 → 停留在任意教务页面 → 点击“执行导入”
+//
+// 接口:
+//   GET /admin/pkgl/xskb/queryKbForXsd                              课表页 HTML(#xhid / #xqdm / #xnxq1)
+//   GET /admin/api/getZclistByXnxq?xnxq=<学期>&xqid=<校区代码>        周次表 zclist + 节次时间 jcsjszList
+//   GET /admin/xsd/pkgl/xskb/sdpkkbList?xnxq=&xhid=&xqdm=&xskbxslx=0 课程数据(每行自带 xqid / xqmc)
+//
+// 要点:
+//   1. 课程按“小节”返回(djc 1~10,jcsjszList 同为 10 条),先按小节建课再合并连续节次与周次。
+//   2. kcmc / tmc / croommc 均为 <a> 包裹的 HTML;tmc 可能含多个 <a>,需整体取文本。
+//   3. sdpkkbList 的 xqdm 不生效(传任何校区都返回同一批课),课程行自带的 xqid / xqmc 才是上课校区;
+//      getZclistByXnxq 的 xqid 生效,而三校区作息不同,故作息校区由课程数据推导。
+//   4. #xhid 必须取自课表页(86 字符加密串);首页 /admin 的同名元素是用户 ID,误用返回 ret=-1。
+//
+// 维护者:dr1am1
+
+// 学期选择:true = 弹窗选择(默认当前学期);false = 直接用当前学期
+const ASK_SEMESTER = true;
+
+const KB_PAGE_URL = '/admin/pkgl/xskb/queryKbForXsd';
+
+// 兜底作息(接口异常时使用),键为教务返回的校区名
+const FALLBACK_SLOTS = {
+    '雁塔校区': ['08:00-08:50', '09:00-09:50', '10:20-11:00', '11:10-12:00', '14:30-15:20',
+                 '15:30-16:20', '16:40-17:30', '17:40-18:30', '19:30-20:20', '20:30-21:20'],
+    '明德校区': ['08:00-08:50', '09:00-09:50', '10:10-11:00', '11:10-12:00', '14:30-15:20',
+                 '15:30-16:20', '16:40-17:30', '17:40-18:30', '19:30-20:20', '20:30-21:20'],
+    '鄠邑校区': ['08:20-09:05', '09:15-10:00', '10:20-11:05', '11:15-12:00', '14:00-14:45',
+                 '14:55-15:40', '16:00-16:45', '16:55-17:40', '19:00-19:45', '19:55-20:40']
+};
+FALLBACK_SLOTS['默认校区'] = FALLBACK_SLOTS['鄠邑校区'];
+
+function fallbackSlots(campusName) {
+    const list = FALLBACK_SLOTS[campusName] || FALLBACK_SLOTS['雁塔校区'];
+    return list.map((item, i) => {
+        const [startTime, endTime] = item.split('-');
+        return { number: i + 1, startTime, endTime };
+    });
+}
+
+// ============================== 桥接 ==============================
+
+function toast(message) {
+    if (window.shiguangBridge && typeof window.shiguangBridge.showToast === 'function') {
+        window.shiguangBridge.showToast(message);
+    } else {
+        console.log('[XSYU] ' + message);
+    }
+}
+
+async function alertUser(title, content) {
+    if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.showAlert === 'function') {
+        return await window.shiguangBridgePromise.showAlert(title, content, '确定');
+    }
+    console.warn('[XSYU] ' + title + ' - ' + content);
+    return true;
+}
+
+// ============================== 解析 ==============================
+
+// 取出 <a>包裹字段中的纯文本,如 <a ...>数字图像处理Ⅰ</a>
+function extractAnchorText(htmlStr) {
+    if (!htmlStr) return '';
+    const match = String(htmlStr).match(/>([^<]+)</);
+    return match ? match[1].trim() : String(htmlStr).trim();
+}
+
+// 教师名可能是"<a>张三</a>,<a>李四</a>"或畸形串"<a>张三</a>,(,<a>李四</a>,)",
+// 后者括号内是有效教师而非备注,因此先取出括号内容再清括号,最后去重拼接
+function cleanTeacherName(htmlStr) {
+    if (!htmlStr) return '';
+    let text = String(htmlStr).replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim();
+
+    const inner = [];
+    text.replace(/[((]([^()()]*)[))]/g, (whole, group) => {
+        group.split(/[,,、;;]/).forEach(t => {
+            const name = t.trim();
+            if (name && name.length <= 12) inner.push(name);
+        });
+        return whole;
+    });
+    text = text.replace(/([^)]*)/g, '').replace(/\([^)]*\)/g, '');
+
+    const parts = [...text.split(/[,,、;;]/), ...inner].map(t => t.trim()).filter(Boolean);
+    return [...new Set(parts)].join(',');
+}
+
+// zcstr 为逗号分隔的周次,如 "1,2,3,10,11"
+function parseWeeks(weekStr) {
+    if (!weekStr) return [];
+    return String(weekStr).split(',')
+        .map(w => Number(String(w).trim()))
+        .filter(w => w > 0)
+        .sort((a, b) => a - b);
+}
+
+// "8:00" / "08:00:00" → "08:00"
+function formatTime(timeStr) {
+    if (typeof timeStr !== 'string') return null;
+    const match = timeStr.match(/^(\d{1,2}):(\d{1,2})(?::\d{1,2})?$/);
+    if (!match) return null;
+    return `${match[1].padStart(2, '0')}:${match[2].padStart(2, '0')}`;
+}
+
+// ============================== 网络 ==============================
+
+async function getJson(url) {
+    const response = await fetch(url, {
+        credentials: 'include',
+        headers: { 'Accept': 'application/json, text/plain, */*', 'X-Requested-With': 'XMLHttpRequest' }
+    });
+    if (!response.ok) throw new Error(`网络请求失败,状态码 ${response.status}(${url.split('?')[0]})`);
+    const json = await response.json();
+    if (json.ret !== 0) throw new Error(`${url.split('?')[0]} 返回 ret=${json.ret}:${json.msg || '未知错误'}`);
+    return json;
+}
+
+// 参数一律取自课表页:首页 /admin 的 #xhid 是用户 ID(32 字符),误用会返回 ret=-1
+async function extractPageParams() {
+    const response = await fetch(KB_PAGE_URL, {
+        credentials: 'include',
+        headers: { 'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8' }
+    });
+    if (!response.ok) throw new Error(`抓取课表页失败(${response.status}),请确认已登录教务系统`);
+
+    const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
+    const xhid = doc.querySelector('#xhid')?.value || '';
+    const xqdm = doc.querySelector('#xqdm')?.value || '';
+    if (!xhid || !xqdm) throw new Error('课表页缺少 #xhid / #xqdm,请确认已登录教务系统');
+
+    return { xhid, xqdm, xnxqSelectHtml: doc.querySelector('#xnxq1')?.outerHTML || null };
+}
+
+async function chooseSemester(selectHtml) {
+    const select = selectHtml ? new DOMParser().parseFromString(selectHtml, 'text/html').querySelector('#xnxq1') : null;
+    const options = select ? [...select.options].filter(o => o.value.trim()) : [];
+    if (!options.length) throw new Error('未能读取学年学期下拉,请确认已登录教务系统');
+
+    const current = Math.max(options.findIndex(o => o.selected), 0);
+    if (!ASK_SEMESTER) return options[current].value.trim();
+
+    const index = await window.shiguangBridgePromise.showSingleSelection(
+        '选择学年学期', JSON.stringify(options.map(o => (o.textContent || o.value).trim())), current
+    );
+    if (index === null || index === -1) return null;
+    return options[index].value.trim();
+}
+
+// sdpkkbList 的 xqdm 不过滤,只能靠课程行的 xqid / xqmc 判定上课校区;
+// 极少数跨校区选课的情况取课程最多者,作息以其为准
+function deriveCampus(rawRows, pageXqdm) {
+    const tally = new Map();
+    for (const raw of rawRows) {
+        const xqdm = String(raw.xqid || '').trim();
+        const xqmc = String(raw.xqmc || '').trim();
+        if (!xqdm && !xqmc) continue;
+        const item = tally.get(xqdm || xqmc) || { xqdm, xqmc, rows: 0 };
+        item.rows += 1;
+        tally.set(xqdm || xqmc, item);
+    }
+
+    const list = [...tally.values()].sort((a, b) => b.rows - a.rows);
+    if (!list.length) return { xqdm: pageXqdm, xqmc: '' };
+    if (list.length > 1) {
+        console.warn(`JS: 本学期课程跨校区:${list.map(c => `${c.xqmc || c.xqdm}(${c.rows})`).join('、')}`);
+    }
+    return list[0];
+}
+
+// 节次时间必须从 1 连续且不重叠,否则返回 null 交由调用方回退内置作息
+function buildTimeSlots(list) {
+    if (!Array.isArray(list) || !list.length) return null;
+    const slots = list
+        .map(item => ({ number: Number(item.jc), startTime: formatTime(item.kssj), endTime: formatTime(item.jssj) }))
+        .filter(s => s.number > 0 && s.startTime && s.endTime)
+        .sort((a, b) => a.number - b.number);
+    const valid = slots.length > 0 && slots.every((s, i) => s.number === i + 1 && (i === 0 || s.startTime >= slots[i - 1].endTime));
+    return valid ? slots : null;
+}
+
+async function fetchTimeAndWeekData(xnxq, xqdm) {
+    const data = (await getJson(
+        `/admin/api/getZclistByXnxq?xnxq=${encodeURIComponent(xnxq)}&xqid=${encodeURIComponent(xqdm)}`
+    )).data || {};
+
+    const zclist = Array.isArray(data.zclist) ? data.zclist : [];
+    const firstWeek = zclist.find(z => Number(z.zc) === 1);
+    return {
+        timeSlots: buildTimeSlots(data.jcsjszList),
+        // 第 1 周 minrq 即周一,与 semesterStartDate 语义一致
+        semesterStartDate: firstWeek?.minrq ? String(firstWeek.minrq).split(' ')[0] : null,
+        semesterTotalWeeks: zclist.length || 20
+    };
+}
+
+// ============================== 课程 ==============================
+
+// 课程合并去重(参考 wiki《课程合并与去重函数》)
+function mergeAndDistinctCourses(courses) {
+    if (!Array.isArray(courses) || courses.length <= 1) return courses;
+
+    const list = courses.map(c => ({ ...c, weeks: [...c.weeks].sort((a, b) => a - b) }));
+    const base = (a, b) => a.name.localeCompare(b.name) || a.teacher.localeCompare(b.teacher) ||
+        a.position.localeCompare(b.position) || a.day - b.day;
+
+    // 阶段 1:合并连续节次,剔除完全重复
+    list.sort((a, b) => base(a, b) || a.weeks.join(',').localeCompare(b.weeks.join(',')) || a.startSection - b.startSection);
+    const merged = [];
+    let cur = list[0];
+    for (const next of list.slice(1)) {
+        const sameCourse = cur.name === next.name && cur.teacher === next.teacher &&
+            cur.position === next.position && cur.day === next.day &&
+            cur.weeks.join(',') === next.weeks.join(',');
+        if (sameCourse && cur.endSection + 1 === next.startSection) {
+            cur.endSection = next.endSection;
+        } else if (sameCourse && cur.startSection === next.startSection && cur.endSection === next.endSection) {
+            continue;
+        } else {
+            merged.push(cur);
+            cur = next;
+        }
+    }
+    merged.push(cur);
+
+    // 阶段 2:合并同节次的周次
+    merged.sort((a, b) => base(a, b) || a.startSection - b.startSection || a.endSection - b.endSection);
+    const distinct = [];
+    let prev = merged[0];
+    for (const next of merged.slice(1)) {
+        const sameSection = prev.name === next.name && prev.teacher === next.teacher &&
+            prev.position === next.position && prev.day === next.day &&
+            prev.startSection === next.startSection && prev.endSection === next.endSection;
+        if (sameSection) {
+            prev.weeks = [...new Set([...prev.weeks, ...next.weeks])].sort((a, b) => a - b);
+        } else {
+            distinct.push(prev);
+            prev = next;
+        }
+    }
+    distinct.push(prev);
+    return distinct;
+}
+
+function parseCourseData(jsonData) {
+    if (!Array.isArray(jsonData?.data)) return [];
+
+    const list = [];
+    for (const raw of jsonData.data) {
+        const name = extractAnchorText(raw.kcmc);
+        const day = Number(raw.xingqi);
+        const section = Number(raw.djc);
+        const weeks = parseWeeks(raw.zcstr);
+        if (!name || !(day >= 1 && day <= 7) || !(section >= 1) || !weeks.length) continue;
+
+        const course = {
+            name,
+            teacher: cleanTeacherName(raw.tmc),
+            position: extractAnchorText(raw.croommc) || '待定',
+            day,
+            startSection: section,
+            endSection: section,
+            weeks
+        };
+        const credit = Number(raw.xf);
+        if (credit > 0) course.credit = credit;
+        list.push(course);
+    }
+    return mergeAndDistinctCourses(list);
+}
+
+async function fetchCourses(xnxq, xhid, xqdm) {
+    const json = await getJson(
+        `/admin/xsd/pkgl/xskb/sdpkkbList?xnxq=${encodeURIComponent(xnxq)}&xhid=${encodeURIComponent(xhid)}&xqdm=${encodeURIComponent(xqdm)}&xskbxslx=0`
+    );
+    return { courses: parseCourseData(json), rawRows: Array.isArray(json.data) ? json.data : [] };
+}
+
+// ============================== 保存 ==============================
+
+async function saveCourses(courses) {
+    await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
+}
+
+async function saveTimeSlots(timeSlots) {
+    await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
+}
+
+async function saveConfig(semesterStartDate, semesterTotalWeeks) {
+    const config = { semesterTotalWeeks };
+    if (semesterStartDate) config.semesterStartDate = semesterStartDate;
+    await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
+}
+
+// ============================== 主流程 ==============================
+
+function isLoginPage() {
+    return window.location.href.includes('/admin/login') || window.location.href.includes('slogin');
+}
+
+async function runImportFlow() {
+    try {
+        if (isLoginPage()) {
+            await alertUser('导入失败', '当前是登录页面,请先完成登录并进入教务系统内部页面后再执行导入。');
+            return;
+        }
+
+        const confirmed = await alertUser(
+            '西安石油大学教务系统课表导入',
+            '将自动读取当前学期、上课校区、作息时间与开学日期。\n导入前请确认已成功登录教务系统。'
+        );
+        if (confirmed !== true && confirmed !== 'true') {
+            toast('用户取消了导入。');
+            return;
+        }
+
+        const { xhid, xqdm, xnxqSelectHtml } = await extractPageParams();
+        const xnxq = await chooseSemester(xnxqSelectHtml);
+        if (!xnxq) {
+            toast('导入已取消:未选择学年学期。');
+            return;
+        }
+
+        toast(`正在导入 ${xnxq} ...`);
+        const { courses, rawRows } = await fetchCourses(xnxq, xhid, xqdm);
+        if (!courses.length) {
+            await alertUser('未找到课程', `${xnxq} 学期未获取到任何课程数据,请确认学期选择是否正确。`);
+            return;
+        }
+        await saveCourses(courses);
+
+        // 作息校区取自课程数据,页面 #xqdm 与课程所在校区无关
+        const campus = deriveCampus(rawRows, xqdm);
+        const campusName = campus.xqmc || campus.xqdm || '未知校区';
+
+        // 作息与开学日期:接口失败也要写入内置作息,避免沿用上次导入的遗留时间
+        let extra = null;
+        try {
+            extra = await fetchTimeAndWeekData(xnxq, campus.xqdm);
+        } catch (error) {
+            console.warn('JS: 作息/开学日期获取失败:', error.message);
+            toast('未获取到教务作息,已使用内置作息表。');
+        }
+        if (extra) await saveConfig(extra.semesterStartDate, extra.semesterTotalWeeks);
+        await saveTimeSlots(extra?.timeSlots || fallbackSlots(campus.xqmc));
+
+        toast(`导入成功:${courses.length} 条课程、${xnxq} · ${campusName}。`);
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        console.error('JS: 导入流程异常:', error);
+        await alertUser('导入失败', `${error.message}\n\n请确认:\n1. 已在教务系统中成功登录;\n2. 网络可以正常访问 jiaowu.xsyu.edu.cn。`);
+    }
+}
+
+runImportFlow();