Browse Source

Merge pull request #880 from ShiGuangSchedule/pending

星河欲转 2 tuần trước cách đây
mục cha
commit
19a65bf07a

+ 11 - 0
index/root_index.yaml

@@ -1302,3 +1302,14 @@ schools:
     name: "广东交通职业技术学院"
     initial: "G"
     resource_folder: "GDCP"
+    
+  - id: "OUC"
+    name: "中国海洋大学"
+    initial: "Z"
+    resource_folder: "OUC"
+
+  - id: "SDWCVC"
+    name: "山东水利职业学院"
+    initial: "S"
+    resource_folder: "SDWCVC"
+    

+ 8 - 0
resources/GDCP/adapters.yaml

@@ -6,3 +6,11 @@ adapters:
     import_url: "https://cas.gdcp.edu.cn/"
     maintainer: "小漫君"
     description: "登录融合门户并进入新教务系统后导入,选择学期与上课校区,按教学楼应用学校作息,并读取开学日期与总周数。"
+
+  - adapter_id: "GDCP_02"
+    adapter_name: "广东交通职业技术学院强智教务"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "gdcp_02.js"
+    import_url: "https://jw.gdcp.edu.cn/"
+    maintainer: "Haooz"
+    description: "登录教务系统后,选择学期后直接执行导入,按教学楼自动判定校区"

+ 13 - 7
resources/GDCP/gdcp_01.js

@@ -9,8 +9,8 @@
 const GDCP_TIMETABLE_URL = 'https://jw.gdcp.edu.cn/jsxsd/xskb/xskb_list.do';
 const GDCP_CALENDAR_URL = 'https://jw.gdcp.edu.cn/jsxsd/jxzl/jxzl_query';
 
-// 来源:学校《各校区上课作息时间表》(用户提供)。
-// 第 7~8、9~10 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
+// 来源:学校《各校区上课作息时间表(新)》(用户提供)。
+// 第 7~8、9~10、11~12 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
 const GDCP_TIME_SLOTS = [
     { number: 1, startTime: '08:30', endTime: '09:10' },
     { number: 2, startTime: '09:15', endTime: '09:55' },
@@ -21,7 +21,9 @@ const GDCP_TIME_SLOTS = [
     { number: 7, startTime: '15:55', endTime: '16:35' },
     { number: 8, startTime: '16:35', endTime: '17:15' },
     { number: 9, startTime: '18:05', endTime: '18:45' },
-    { number: 10, startTime: '18:45', endTime: '19:25' }
+    { number: 10, startTime: '18:45', endTime: '19:25' },
+    { number: 11, startTime: '19:40', endTime: '20:20' },
+    { number: 12, startTime: '20:20', endTime: '21:00' }
 ];
 const GDCP_LATE_MORNING = [
     { number: 3, startTime: '10:30', endTime: '11:10' },
@@ -38,7 +40,7 @@ const GDCP_CAMPUSES = [
 function applyCampusTimes(courses, campus) {
     return courses.map(function ({ building, ...course }) {
         if (course.startSection < 1 || course.endSection > GDCP_TIME_SLOTS.length) {
-            throw new Error('学校作息表只提供第 1~10 节,课程“' + course.name + '”的节次超出范围。');
+            throw new Error('学校作息表只提供第 1~12 节,课程“' + course.name + '”的节次超出范围。');
         }
         const slots = GDCP_TIME_SLOTS.slice();
         if (course.startSection <= 4 && course.endSection >= 3) {
@@ -55,9 +57,13 @@ function applyCampusTimes(courses, campus) {
                 slots[3] = GDCP_LATE_MORNING[1];
             }
         }
-        // 学校与用户课表都将这两组小节视为一个完整时间块,不能按普通课间拆开。
-        const startTime = course.startSection === 8 ? '15:55' : course.startSection === 10 ? '18:05' : slots[course.startSection - 1].startTime;
-        const endTime = course.endSection === 7 ? '17:15' : course.endSection === 9 ? '19:25' : slots[course.endSection - 1].endTime;
+        // 学校将这三组小节分别视为一个完整时间块,不能按普通课间拆开。
+        const startTime = course.startSection === 8 ? '15:55'
+            : course.startSection === 10 ? '18:05'
+            : course.startSection === 12 ? '19:40' : slots[course.startSection - 1].startTime;
+        const endTime = course.endSection === 7 ? '17:15'
+            : course.endSection === 9 ? '19:25'
+            : course.endSection === 11 ? '21:00' : slots[course.endSection - 1].endTime;
         return {
             ...course,
             isCustomTime: true,

+ 436 - 0
resources/GDCP/gdcp_02.js

@@ -0,0 +1,436 @@
+// 广东交通职业技术学院(gdcp.edu.cn)拾光课程表适配脚本(自动判定校区作息版)
+// 接口与作息数据参考同目录 gdcp_01.js(作者:小漫君),本适配不再让用户选择校区。
+// 适配作者:Haooz
+// 课表:GET /jsxsd/xskb/xskb_list.do 读学期下拉与节次模式;POST 同路径取整学期详表(div.kbcontent)。
+// 周历:POST /jsxsd/jxzl/jxzl_query 读首周日期与总周数。
+// 作息:按教学楼自动判断校区;校区有两套作息时,课程较多的一套写入预设作息,较少的一套按自定义时间写入。
+
+const GDCP_ORIGIN = 'https://jw.gdcp.edu.cn';
+const GDCP_TIMETABLE_URL = GDCP_ORIGIN + '/jsxsd/xskb/xskb_list.do';
+const GDCP_CALENDAR_URL = GDCP_ORIGIN + '/jsxsd/jxzl/jxzl_query';
+
+// 第 7~8、9~10、11~12 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
+const GDCP_TIME_SLOTS = [
+    { number: 1, startTime: '08:30', endTime: '09:10' },
+    { number: 2, startTime: '09:15', endTime: '09:55' },
+    { number: 3, startTime: '10:10', endTime: '10:50' },
+    { number: 4, startTime: '10:55', endTime: '11:35' },
+    { number: 5, startTime: '14:15', endTime: '14:55' },
+    { number: 6, startTime: '15:00', endTime: '15:40' },
+    { number: 7, startTime: '15:55', endTime: '16:35' },
+    { number: 8, startTime: '16:35', endTime: '17:15' },
+    { number: 9, startTime: '18:05', endTime: '18:45' },
+    { number: 10, startTime: '18:45', endTime: '19:25' },
+    { number: 11, startTime: '19:40', endTime: '20:20' },
+    { number: 12, startTime: '20:20', endTime: '21:00' }
+];
+
+// 部分楼栋第 3、4 节使用的晚班作息(早班取 GDCP_TIME_SLOTS 的值)
+const GDCP_LATE_MORNING = [
+    { number: 3, startTime: '10:30', endTime: '11:10' },
+    { number: 4, startTime: '11:15', endTime: '11:55' }
+];
+
+// 晚班完整作息(仅第 3、4 节与早班不同)
+const GDCP_LATE_TIME_SLOTS = GDCP_TIME_SLOTS.map(function (slot) {
+    if (slot.number === 3) return GDCP_LATE_MORNING[0];
+    if (slot.number === 4) return GDCP_LATE_MORNING[1];
+    return slot;
+});
+
+const GDCP_CAMPUSES = [
+    // 轨道楼(16#)未列入原表;用户已确认第 3、4 节使用 10:10 起的早班作息。
+    { name: '天河校区', early: ['9号楼', '10号楼', '12号楼', '图书馆', '公路楼', '汽车实训楼', '轨道楼'], late: ['2号楼', '运动场'] },
+    { name: '花都校区', early: ['1号楼', '图书馆'], late: ['10号楼', '15号楼', '16号楼', '运动场'] },
+    { name: '国际校区', early: ['教学楼', '运动场'], late: [] },
+    { name: '清远校区', early: ['厚德楼', '明德楼', '立业楼', '创新楼', '求是楼', '笃实楼'], late: ['融新楼', '融创楼', '运动场', '体育馆'] }
+];
+
+// 教学楼名归一:去掉【】与校区后缀,楼号去前导零;“操场”对应作息表的“运动场”
+function normalizeVenue(building) {
+    return String(building)
+        .replace(/[【】]/g, '')
+        .replace(/((?:天河|花都|国际|清远))$/, '')
+        .replace(/^0+(\d+号楼)$/, '$1')
+        .replace(/^操场$/, '运动场');
+}
+
+function isBuildingMatch(venue, name) {
+    return venue === name || venue.startsWith(name + '(');
+}
+
+// 7-8、9-10、11-12 由学校视为一个完整时间块,不能取普通小节的边界
+function sectionTime(slots, section, isStart) {
+    if (isStart) {
+        if (section === 8) return '15:55';
+        if (section === 10) return '18:05';
+        if (section === 12) return '19:40';
+        return slots[section - 1].startTime;
+    }
+    if (section === 7) return '17:15';
+    if (section === 9) return '19:25';
+    if (section === 11) return '21:00';
+    return slots[section - 1].endTime;
+}
+
+// 某一教学楼出现在哪些校区(早班、晚班名单都算;如“运动场”会同时出现在多个校区)
+function campusesOf(building) {
+    const venue = normalizeVenue(building);
+    return GDCP_CAMPUSES.filter(function (campus) {
+        return campus.early.some(function (name) { return isBuildingMatch(venue, name); }) ||
+            campus.late.some(function (name) { return isBuildingMatch(venue, name); });
+    });
+}
+
+// 课程在所属校区走早班还是晚班;国际校区未列入名单的“其他区域”按晚班处理
+function scheduleOf(campus, building) {
+    const venue = normalizeVenue(building);
+    if (campus.early.some(function (name) { return isBuildingMatch(venue, name); })) return 'early';
+    if (campus.late.some(function (name) { return isBuildingMatch(venue, name); })) return 'late';
+    if (campus.name === '国际校区') return 'late';
+    throw new Error(campus.name + '的“' + building + '”未列入学校作息表,无法确定第 3、4 节时间。');
+}
+
+// 课程数最多的校区即当前上课校区
+function dominantCampus(courses) {
+    const count = new Map();
+    courses.forEach(function (course) {
+        campusesOf(course.building).forEach(function (campus) {
+            count.set(campus, (count.get(campus) || 0) + 1);
+        });
+    });
+    let picked = null;
+    count.forEach(function (times, campus) {
+        if (!picked || times > count.get(picked)) picked = campus;
+    });
+    if (!picked) throw new Error('未能根据教学楼名称判断上课校区。');
+    return picked;
+}
+
+// 按指定作息写入课程的自定义起止时间
+function applyGroupTime(course, slots) {
+    if (course.startSection < 1 || course.endSection > GDCP_TIME_SLOTS.length) {
+        throw new Error('学校作息表只提供第 1~12 节,课程“' + course.name + '”的节次超出范围。');
+    }
+    return {
+        ...course,
+        isCustomTime: true,
+        customStartTime: sectionTime(slots, course.startSection, true),
+        customEndTime: sectionTime(slots, course.endSection, false)
+    };
+}
+
+async function fetchTimetableDoc(parameters) {
+    const options = { credentials: 'include' };
+    if (parameters !== undefined) {
+        options.method = 'POST';
+        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
+        options.body = parameters.toString();
+    }
+    const response = await fetch(GDCP_TIMETABLE_URL, options);
+    if (!response.ok) throw new Error('课表请求失败(HTTP ' + response.status + ')。');
+    return new DOMParser().parseFromString(await response.text(), 'text/html');
+}
+
+// 解析详表“周次(节次)”文本,如“1-16周(全部)[01-02节]”“1-8周(单)”
+function parseWeeksAndSections(text) {
+    const result = { weeks: [], sections: [] };
+    const content = String(text || '').trim();
+    if (!content) return result;
+
+    const parity = /双/.test(content) ? 2 : (/单/.test(content) ? 1 : 0);
+    const bracketIndex = content.indexOf('[');
+    const cleaned = (bracketIndex >= 0 ? content.slice(0, bracketIndex) : content)
+        .replace(/第/g, '')
+        .replace(/至|到|~/g, '-')
+        .replace(/[((][^()()]*[))]/g, '')
+        .replace(/周/g, '');
+
+    cleaned.split(/[,,、;;\s]+/).forEach(function (segment) {
+        const item = segment.trim();
+        const range = item.match(/^(\d+)\s*[-–—]\s*(\d+)$/);
+        if (range) {
+            for (let week = parseInt(range[1], 10); week <= parseInt(range[2], 10); week++) result.weeks.push(week);
+        } else if (/^\d+$/.test(item)) {
+            result.weeks.push(parseInt(item, 10));
+        }
+    });
+
+    if (parity) {
+        result.weeks = result.weeks.filter(function (week) { return week % 2 === (parity === 1 ? 1 : 0); });
+    }
+    result.weeks = Array.from(new Set(result.weeks)).sort(function (a, b) { return a - b; });
+
+    const sectionMatch = content.match(/\[([^\]]*)\]/);
+    if (sectionMatch) {
+        (sectionMatch[1].match(/\d+/g) || []).forEach(function (number) {
+            const section = parseInt(number, 10);
+            if (result.sections.indexOf(section) < 0) result.sections.push(section);
+        });
+        result.sections.sort(function (a, b) { return a - b; });
+    }
+    return result;
+}
+
+function parseTimetable(doc) {
+    const table = doc.getElementById('timetable');
+    if (!table) throw new Error('未获取到课表,请确认已登录新教务系统。');
+
+    const courses = [];
+    Array.from(table.querySelectorAll('tr')).forEach(function (row) {
+        const cells = row.querySelectorAll('td');
+        if (cells.length !== 7) return;
+        cells.forEach(function (cell, index) {
+            const detail = cell.querySelector('div.kbcontent');
+            if (!detail) throw new Error('课表详表结构不匹配。');
+
+            const content = detail.cloneNode(true);
+            // 悬浮信息在详表里是重复的,只解析详表字段
+            content.querySelectorAll('.item-box').forEach(function (node) { node.remove(); });
+            if (!content.textContent.trim()) return;
+
+            content.innerHTML.split(/-{10,}\s*<br\s*\/?>/i).forEach(function (html) {
+                const block = doc.createElement('div');
+                block.innerHTML = html;
+
+                const name = block.querySelector('font:not([title])');
+                const teacher = block.querySelector('font[title="教师"]');
+                const time = block.querySelector('font[title="周次(节次)"]');
+                const position = block.querySelector('font[title="教室"]');
+                const building = block.querySelector('font[title="教学楼"]');
+                if (!name || !teacher || !time || !position || !building) throw new Error('课程字段结构不匹配。');
+
+                const parsed = parseWeeksAndSections(time.textContent);
+                if (!name.textContent.trim() || parsed.weeks.length === 0 || parsed.sections.length === 0) {
+                    throw new Error('课程名称、周次或节次为空。');
+                }
+
+                courses.push({
+                    name: name.textContent.trim(),
+                    teacher: teacher.textContent.trim(),
+                    position: position.textContent.trim(),
+                    building: building.textContent.trim(),
+                    day: index + 1,
+                    weeks: parsed.weeks,
+                    startSection: parsed.sections[0],
+                    endSection: parsed.sections[parsed.sections.length - 1]
+                });
+            });
+        });
+    });
+    return courses;
+}
+
+// 课程合并与去重(连续节次合并、同节次周次合并、完全重复剔除)
+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) => {
+        return 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 step1Merged = [];
+    let current = list[0];
+
+    for (let i = 1; i < list.length; i++) {
+        const next = list[i];
+
+        const isSameCourseAndWeeks =
+            current.name === next.name &&
+            current.teacher === next.teacher &&
+            current.position === next.position &&
+            current.day === next.day &&
+            current.weeks.join(',') === next.weeks.join(',');
+
+        const isContinuous = current.endSection + 1 === next.startSection;
+        const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
+
+        if (isSameCourseAndWeeks && isContinuous) {
+            current.endSection = next.endSection;
+        } else if (isSameCourseAndWeeks && isDuplicate) {
+            continue;
+        } else {
+            step1Merged.push(current);
+            current = next;
+        }
+    }
+    step1Merged.push(current);
+
+    step1Merged.sort((a, b) => {
+        return 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 step2Merged = [];
+    let merged = step1Merged[0];
+
+    for (let i = 1; i < step1Merged.length; i++) {
+        const next = step1Merged[i];
+
+        const isSameCourseAndSection =
+            merged.name === next.name &&
+            merged.teacher === next.teacher &&
+            merged.position === next.position &&
+            merged.day === next.day &&
+            merged.startSection === next.startSection &&
+            merged.endSection === next.endSection;
+
+        if (isSameCourseAndSection) {
+            merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
+        } else {
+            step2Merged.push(merged);
+            merged = next;
+        }
+    }
+    step2Merged.push(merged);
+
+    return step2Merged;
+}
+
+// 教学周历:行首为周次,第 1 周第 2 格的日期即开学日
+function parseCalendar(doc) {
+    const result = { semesterStartDate: null, totalWeeks: null };
+    const table = doc.querySelector('table');
+    if (!table) return result;
+
+    const toDate = function (text) {
+        const match = String(text || '').match(/(\d{4})\s*[-年]\s*(\d{1,2})\s*[-月]\s*(\d{1,2})/);
+        return match ? match[1] + '-' + match[2].padStart(2, '0') + '-' + match[3].padStart(2, '0') : null;
+    };
+
+    Array.from(table.querySelectorAll('tr')).forEach(function (row) {
+        const cells = Array.from(row.children);
+        const first = cells.length > 0 ? String(cells[0].textContent).trim() : '';
+        if (!/^\d+$/.test(first)) return;
+
+        const week = parseInt(first, 10);
+        result.totalWeeks = result.totalWeeks === null ? week : Math.max(result.totalWeeks, week);
+        if (week === 1 && !result.semesterStartDate && cells.length > 1) {
+            result.semesterStartDate = toDate(cells[1].getAttribute('title')) || toDate(cells[1].textContent);
+        }
+    });
+    return result;
+}
+
+async function fetchCourseConfig(semesterValue) {
+    const response = await fetch(GDCP_CALENDAR_URL, {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+        body: new URLSearchParams({ xnxq01id: semesterValue }).toString(),
+        credentials: 'include'
+    });
+    if (!response.ok) throw new Error('教学周历请求失败(HTTP ' + response.status + ')。');
+
+    const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
+    const returned = doc.getElementById('xnxq01id');
+    if (!returned || returned.value !== semesterValue) throw new Error('返回周历与所选学期不一致。');
+
+    const calendar = parseCalendar(doc);
+    const totalWeeks = calendar.totalWeeks;
+    if (!calendar.semesterStartDate || !Number.isInteger(totalWeeks) || totalWeeks < 1) {
+        throw new Error('教学周历未提供完整的首周日期或总周数。');
+    }
+
+    const monday = new Date(calendar.semesterStartDate + 'T00:00:00Z');
+    const isMonday = !Number.isNaN(monday.getTime()) && monday.getUTCDay() === 1 &&
+        monday.toISOString().slice(0, 10) === calendar.semesterStartDate;
+    if (!isMonday) throw new Error('教学周历第 1 周的星期一日期无效。');
+
+    return {
+        semesterStartDate: calendar.semesterStartDate,
+        semesterTotalWeeks: totalWeeks,
+        firstDayOfWeek: 1,
+        defaultClassDuration: 40,
+        defaultBreakDuration: 5
+    };
+}
+
+async function runImportFlow() {
+    try {
+        if (window.location.origin !== GDCP_ORIGIN) {
+            await window.shiguangBridgePromise.showAlert(
+                '请先登录教务系统',
+                '请先登录教务系统后再执行导入。',
+                '知道了'
+            );
+            return;
+        }
+
+        window.shiguangBridge.showToast('正在获取学期信息...');
+        const initialDoc = await fetchTimetableDoc();
+        const semesterSelect = initialDoc.getElementById('xnxq01id');
+        const modeSelect = initialDoc.getElementById('kbjcmsid');
+        if (!semesterSelect || semesterSelect.options.length === 0 || !modeSelect || !modeSelect.value) {
+            throw new Error('未获取到学期或节次模式,请确认教务登录状态。');
+        }
+
+        const semesters = Array.from(semesterSelect.options);
+        const picked = await window.shiguangBridgePromise.showSingleSelection(
+            '选择学期',
+            JSON.stringify(semesters.map(function (option) { return option.textContent.trim(); })),
+            semesterSelect.selectedIndex
+        );
+        if (picked === null) return;
+        if (!Number.isInteger(picked) || picked < 0 || picked >= semesters.length) throw new Error('学期选择无效。');
+        const semesterValue = semesters[picked].value;
+
+        const parameters = new URLSearchParams({
+            cj0701id: '', zc: '', demo: '', xnxq01id: semesterValue, sfFD: '1', kbjcmsid: modeSelect.value
+        });
+        window.shiguangBridge.showToast('正在获取整学期课表...');
+        const doc = await fetchTimetableDoc(parameters);
+        const returned = doc.getElementById('xnxq01id');
+        if (!returned || returned.value !== semesterValue) throw new Error('返回课表与所选学期不一致。');
+
+        const parsedCourses = mergeAndDistinctCourses(parseTimetable(doc));
+        if (!parsedCourses.length) { window.shiguangBridge.showToast('该学期暂无课程。'); return; }
+
+        // 不弹校区选择:按教学楼判断校区,两组作息中课程较多的一套作为默认作息
+        const campus = dominantCampus(parsedCourses);
+        const groupCount = { early: 0, late: 0 };
+        parsedCourses.forEach(function (course) { groupCount[scheduleOf(campus, course.building)]++; });
+        const majority = groupCount.early >= groupCount.late ? 'early' : 'late';
+        const minority = majority === 'early' ? 'late' : 'early';
+        const minoritySlots = minority === 'late' ? GDCP_LATE_TIME_SLOTS : GDCP_TIME_SLOTS;
+
+        let customCount = 0;
+        const courses = parsedCourses.map(function ({ building, ...course }) {
+            if (scheduleOf(campus, building) !== minority) return course;
+            customCount++;
+            return applyGroupTime(course, minoritySlots);
+        });
+
+        window.shiguangBridge.showToast('正在获取所选学期的教学周历...');
+        const config = await fetchCourseConfig(semesterValue);
+
+        await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
+        await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(majority === 'late' ? GDCP_LATE_TIME_SLOTS : GDCP_TIME_SLOTS));
+        await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
+
+        window.shiguangBridge.showToast('导入成功:' + courses.length + ' 条 · ' + campus.name + ' · 默认' +
+            (majority === 'late' ? '10:30' : '10:10') + (customCount ? ' · 自定义 ' + customCount + ' 条' : ''));
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        window.shiguangBridge.showToast('导入失败:' + error.message);
+        console.error('JS: Import Error', error);
+    }
+}
+
+runImportFlow();

+ 8 - 0
resources/OUC/adapters.yaml

@@ -0,0 +1,8 @@
+adapters:
+  - adapter_id: "OUC_01"
+    adapter_name: "中国海洋大学本科教务系统"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "ouc_01.js"
+    import_url: "https://id.ouc.edu.cn/sso/login?service=https%3A%2F%2Fjwgl2024.ouc.edu.cn%2F"
+    maintainer: "anOsprey"
+    description: "中国海洋大学本科生教务课程表导入,基于强智教务系统网络请求适配。使用校园网络登录教务系统后,可选择目标学期一键导入课程表,自动读取教学周历获取开学日期与总周数,并对课程进行合并去重;导入时可按需选择崂山/鱼山或西海岸校区的作息时间进行配置。如遇问题可及时反馈"

+ 417 - 0
resources/OUC/ouc_01.js

@@ -0,0 +1,417 @@
+// 中国海洋大学(ouc.edu.cn) 拾光课程表适配脚本 v3
+// 基于强智教务系统网络请求方式导入 流程:确认登录 -> 拉取学期列表 -> 用户选择学期 -> 拉取教学周历 -> 请求课表 -> 选择校区作息 -> 保存课程/作息/配置
+
+const BASE_URL = "https://jwgl2024.ouc.edu.cn";
+const URL_COURSE   = `${BASE_URL}/jsxsd/xskb/xskb_list.do`; 
+const URL_CALENDAR = `${BASE_URL}/jsxsd/jxzl/jxzl_query`; 
+const KBJCMSID = "16FD8C2BE55E15F9E0630100007FF6B5";
+
+function pad2(n) { return String(n).padStart(2, "0"); }
+
+function parseWeeks(weekStr) {
+    const weeks = [];
+    if (!weekStr) return weeks;
+    const isSingle = weekStr.includes("(单)");
+    const isDouble = weekStr.includes("(双)");
+    const clean = weekStr.replace(/\([单双]\)/g, "").replace(/[周课]/g, "");
+
+    clean.split(/[,,、]/).forEach(seg => {
+        seg = seg.trim();
+        if (!seg) return;
+        const m = seg.match(/^(\d+)\s*-\s*(\d+)$/);
+        let start, end;
+        if (m) { start = Number(m[1]); end = Number(m[2]); }
+        else if (/^\d+$/.test(seg)) { start = end = Number(seg); }
+        else { return; }
+        for (let w = start; w <= end; w++) {
+            if (isSingle && w % 2 === 0) continue;
+            if (isDouble && w % 2 !== 0) continue;
+            weeks.push(w);
+        }
+    });
+    return [...new Set(weeks)].sort((a, b) => a - b);
+}
+
+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) => {
+        return (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 step1Merged = [];
+    let current = list[0] && { ...list[0] };
+
+    for (let i = 1; i < list.length; i++) {
+        const next = list[i];
+        if (!current) { current = { ...next }; continue; }
+        const same = current.name === next.name &&
+            current.teacher === next.teacher &&
+            current.position === next.position &&
+            current.day === next.day &&
+            (current.weeks || []).join(',') === (next.weeks || []).join(',');
+        const isContinuous = current.endSection + 1 === next.startSection;
+        const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
+        if (same && isContinuous) {
+            current.endSection = next.endSection;
+        } else if (same && isDuplicate) {
+            continue;
+        } else {
+            step1Merged.push(current);
+            current = { ...next };
+        }
+    }
+    if (current) step1Merged.push(current);
+
+    const step2Merged = [];
+    let cur = step1Merged[0] && { ...step1Merged[0] };
+    for (let i = 1; i < step1Merged.length; i++) {
+        const nxt = step1Merged[i];
+        if (!cur) { cur = { ...nxt }; continue; }
+        const same = 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 (same) {
+            cur.weeks = Array.from(new Set([...(cur.weeks || []), ...(nxt.weeks || [])])).sort((a, b) => a - b);
+        } else {
+            step2Merged.push(cur);
+            cur = { ...nxt };
+        }
+    }
+    if (cur) step2Merged.push(cur);
+
+    return step2Merged;
+}
+
+// 课表解析
+function parseCourseItem(li, day) {
+    const titleEl = li.querySelector && li.querySelector(".qz-hasCourse-title");
+    const name = titleEl ? titleEl.textContent.trim() : "";
+
+    const text = (li.textContent || "").replace(/\s+/g, "");
+
+    const timeMatch = text.match(/时间[::]([^;;]*)(?:;|$)/);
+    let weeks = [];
+    let startSection = 1;
+    let endSection = 1;
+    if (timeMatch) {
+        const timePart = timeMatch[1];
+        const weekMatch = timePart.match(/([\d][\d,,、-]*(?:\([单双]\))?)\s*周/);
+        if (weekMatch) weeks = parseWeeks(weekMatch[1]);
+        const secMatch = timePart.match(/\[(\d+)(?:\s*-\s*(\d+))?\s*节\]/);
+        if (secMatch) {
+            startSection = Number(secMatch[1]);
+            endSection = secMatch[2] ? Number(secMatch[2]) : startSection;
+        }
+    }
+
+    const teacherMatch = text.match(/老师[::]([^;;]+)/);
+    const teacher = teacherMatch ? teacherMatch[1].trim() : "";
+
+    const posMatch = text.match(/地点[::]([^;;]*)/);
+    const position = posMatch ? posMatch[1].trim() : "";
+
+    if (!name || weeks.length === 0) return null;
+    return { name, teacher, position, day, startSection, endSection, weeks };
+}
+
+function parseTimetableToModel(doc) {
+    const table = doc.querySelector("table.qz-weeklyTable");
+    if (!table) return [];
+
+    const courses = [];
+    const body = table.querySelector("tbody") || table;
+    body.querySelectorAll("tr.qz-weeklyTable-tr").forEach(row => {
+        let day = 0;
+        row.querySelectorAll("td[name=kbDataTd], td[name='kbDataTd']").forEach(cell => {
+            day++;
+            cell.querySelectorAll("li.courselists-item").forEach(li => {
+                const c = parseCourseItem(li, day);
+                if (c) courses.push(c);
+            });
+        });
+    });
+
+    return mergeAndDistinctCourses(courses);
+}
+
+function parseSemesterOptions(doc) {
+    const select = doc.querySelector("select#xnxq01id");
+    if (!select) return { list: [], defaultIndex: -1 };
+    const options = Array.from(select.querySelectorAll("option"));
+    const allOptions = options.map(opt => ({
+        value: opt.value.trim(),
+        label: opt.textContent.trim()
+    }));
+    if (allOptions.length === 0) return { list: [], defaultIndex: -1 };
+
+    let defaultIndex = options.findIndex(o => o.hasAttribute("selected"));
+    if (defaultIndex === -1) defaultIndex = 0;
+
+    const start = Math.max(0, defaultIndex - 3);
+    const end = Math.min(allOptions.length, defaultIndex + 4);
+    const list = allOptions.slice(start, end);
+    const localDefault = defaultIndex - start;
+    return { list, defaultIndex: localDefault };
+}
+
+function parseCalendarRows(doc) {
+    const rows = [];
+    const table = doc.querySelector("table.qz-weeklyTable") || doc.querySelector("table");
+    if (!table) return rows;
+
+    const body = table.querySelector("tbody") || table;
+    body.querySelectorAll("tr").forEach(tr => {
+        const cells = Array.from(tr.querySelectorAll("td"));
+        if (!cells.length) return;
+        const label = cells[0].textContent.replace(/\s+/g, "");
+        const wkMatch = label.match(/第\s*(\d+)\s*周/);
+        if (!wkMatch) return;
+
+        const dayText = cells.slice(1).map(c => c.textContent.replace(/\s+/g, ""));
+        rows.push({ week: Number(wkMatch[1]), cells: dayText });
+    });
+    return rows;
+}
+
+function deriveMondayFromRow(row, week, semesterYear) {
+    const yearGuess = [semesterYear, semesterYear + 1];
+
+    const fullDateIdx = [];
+    row.cells.forEach((t, i) => {
+        const m = t.match(/^(\d{1,2})月(\d{1,2})日$/);
+        if (m) fullDateIdx.push({ idx: i, month: Number(m[1]), day: Number(m[2]) });
+    });
+
+    for (const fd of fullDateIdx) {
+        const weekdayFrom = (fd.idx + 1) % 7; 
+        for (const y of yearGuess) {
+            const d = new Date(y, fd.month - 1, fd.day);
+            if (d.getDay() === weekdayFrom) {
+                const monday = new Date(d.getTime() - fd.idx * 86400000);
+                return `${monday.getFullYear()}-${pad2(monday.getMonth() + 1)}-${pad2(monday.getDate())}`;
+            }
+        }
+    }
+
+    const mondayCell = row.cells[0];
+    const mm = mondayCell.match(/^(\d{1,2})月(\d{1,2})日$/);
+    if (mm) {
+        for (const y of yearGuess) {
+            const d = new Date(y, Number(mm[1]) - 1, Number(mm[2]));
+            if (d.getDay() === 1) return `${y}-${pad2(Number(mm[1]))}-${pad2(Number(mm[2]))}`;
+        }
+    }
+    return null;
+}
+
+async function fetchSemesterList() {
+    const html = await requestText(`${URL_COURSE}?viweType=0`);
+    const doc = new DOMParser().parseFromString(html, "text/html");
+    return parseSemesterOptions(doc);
+}
+
+async function fetchCalendarInfo(semesterId, semesterYear) {
+    const url = `${URL_CALENDAR}?xnxq01id=${encodeURIComponent(semesterId)}`;
+    const html = await requestText(url);
+    const doc = new DOMParser().parseFromString(html, "text/html");
+    const calendarRows = parseCalendarRows(doc);
+    if (calendarRows.length === 0) return { startDate: null, totalWeeks: null };
+
+    let startDate = null;
+    let totalWeeks = 0;
+    calendarRows.forEach(r => {
+        if (r.week > totalWeeks) totalWeeks = r.week;
+        if (r.week === 1) {
+            startDate = deriveMondayFromRow(r, r.week, semesterYear);
+        }
+    });
+    return { startDate, totalWeeks };
+}
+
+async function fetchCourses(semesterId) {
+    const url = `${URL_COURSE}?viweType=0&showallprint=0&showkchprint=0&showkink=0&showfzmprint=0`
+        + `&baseUrl=%2Fjsxsd&xsflMapListJsonStr=${encodeURIComponent("讲课学时,实践学时,")}`
+        + `&xnxq01id=${encodeURIComponent(semesterId)}&zc=&kbjcmsid=${KBJCMSID}`;
+    const html = await requestText(url);
+    const doc = new DOMParser().parseFromString(html, "text/html");
+    return parseTimetableToModel(doc);
+}
+
+async function requestText(url) {
+    const resp = await fetch(url, { method: "GET", credentials: "include" });
+    if (!resp.ok) {
+        throw new Error(`请求失败:HTTP ${resp.status}`);
+    }
+    return await resp.text();
+}
+
+function buildCourseConfig(semesterStartDate, totalWeeks) {
+    const config = {
+        semesterTotalWeeks: totalWeeks || 20,
+        firstDayOfWeek: 1,
+        defaultClassDuration: 50,
+        defaultBreakDuration: 10
+    };
+    if (semesterStartDate) config.semesterStartDate = semesterStartDate;
+    return config;
+}
+
+async function saveCourseConfig(config) {
+    try {
+        await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
+        return true;
+    } catch (error) {
+        window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
+        return false;
+    }
+}
+
+async function saveCourses(courses) {
+    try {
+        await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses, null, 2));
+        return true;
+    } catch (error) {
+        window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
+        return false;
+    }
+}
+
+async function importPresetTimeSlots(timeSlots) {
+    if (timeSlots.length === 0) {
+        window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
+        return;
+    }
+    window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
+    try {
+        await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
+        window.shiguangBridge.showToast("预设时间段导入成功!");
+    } catch (error) {
+        window.shiguangBridge.showToast("导入时间段失败: " + error.message);
+    }
+}
+
+const LAOSHAN_TIME_SLOTS = [
+    { number: 1, startTime: "08:00", endTime: "08:50" },
+    { number: 2, startTime: "09:00", endTime: "09:50" },
+    { number: 3, startTime: "10:10", endTime: "11:00" },
+    { number: 4, startTime: "11:10", endTime: "12:00" },
+    { number: 5, startTime: "13:30", endTime: "14:20" },
+    { number: 6, startTime: "14:30", endTime: "15:20" },
+    { number: 7, startTime: "15:30", endTime: "16:20" },
+    { number: 8, startTime: "16:30", endTime: "17:20" },
+    { number: 9, startTime: "17:30", endTime: "18:20" },
+    { number: 10, startTime: "18:30", endTime: "19:20" },
+    { number: 11, startTime: "19:30", endTime: "20:20" },
+    { number: 12, startTime: "20:30", endTime: "21:20" }
+];
+
+const WEST_COAST_TIME_SLOTS = [
+    { number: 1, startTime: "08:30", endTime: "09:20" },
+    { number: 2, startTime: "09:25", endTime: "10:15" },
+    { number: 3, startTime: "10:30", endTime: "11:20" },
+    { number: 4, startTime: "11:25", endTime: "12:15" },
+    ...LAOSHAN_TIME_SLOTS.slice(4)
+];
+
+const SCHEDULE_OPTIONS = [
+    { name: "崂山/鱼山校区", slots: LAOSHAN_TIME_SLOTS },
+    { name: "西海岸校区", slots: WEST_COAST_TIME_SLOTS }
+];
+
+async function runImportFlow() {
+    try {
+        window.shiguangBridge.showToast("课程导入流程即将开始...");
+        const confirmed = await window.shiguangBridgePromise.showAlert(
+            "中国海洋大学课表导入",
+            "导入前请确保已成功登录教务系统,且当前网络可访问",
+            "好的,开始导入"
+        );
+        if (!confirmed) {
+            window.shiguangBridge.showToast("用户取消了导入。");
+            return;
+        }
+
+        window.shiguangBridge.showToast("正在获取学期列表...");
+        const { list: semesters, defaultIndex } = await fetchSemesterList();
+        if (!semesters || semesters.length === 0) {
+            window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
+            return;
+        }
+
+        const labels = semesters.map(s => s.label);
+        const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
+            "选择学期",
+            JSON.stringify(labels),
+            defaultIndex
+        );
+        if (selectedIndex === null || selectedIndex === undefined || selectedIndex < 0) {
+            window.shiguangBridge.showToast("用户取消了导入。");
+            return;
+        }
+        const semester = semesters[Math.min(selectedIndex, semesters.length - 1)];
+        const semesterId = semester.value;
+
+        const parts = semesterId.split("-");
+        const suffix = Number(parts[2]);
+        const semesterYear = suffix === 3 ? Number(parts[0]) + 1 : Number(parts[0]);
+
+        window.shiguangBridge.showToast("正在获取学期信息...");
+        let startDate = null, totalWeeks = null;
+        try {
+            const cal = await fetchCalendarInfo(semesterId, semesterYear);
+            startDate = cal.startDate;
+            totalWeeks = cal.totalWeeks;
+        } catch (e) {
+            console.warn("获取教学周历失败:", e.message);
+        }
+
+        window.shiguangBridge.showToast("正在请求课程数据...");
+        const courses = await fetchCourses(semesterId);
+        if (courses.length === 0) {
+            window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
+            return;
+        }
+
+        const scheduleIdxRaw = await window.shiguangBridgePromise.showSingleSelection(
+            "请选择校区作息表:",
+            JSON.stringify(SCHEDULE_OPTIONS.map(option => option.name)),
+            0
+        );
+        const scheduleIndex = Number(scheduleIdxRaw);
+        const schedule = SCHEDULE_OPTIONS[
+            Number.isInteger(scheduleIndex) && scheduleIndex >= 0 && scheduleIndex < SCHEDULE_OPTIONS.length
+                ? scheduleIndex
+                : 0
+        ];
+
+        const config = buildCourseConfig(startDate, totalWeeks);
+        await saveCourseConfig(config);
+        await importPresetTimeSlots(schedule.slots);
+        const courseSaved = await saveCourses(courses);
+        if (!courseSaved) {
+            window.shiguangBridge.showToast("课程保存失败,请重试。");
+            return;
+        }
+
+        window.shiguangBridge.showToast(
+            `导入成功:${courses.length} 门课程,作息 ${schedule.name},共 ${config.semesterTotalWeeks} 周。`
+        );
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        console.error("课程导入失败:", error);
+        window.shiguangBridge.showToast("异常: " + error.message);
+    }
+}
+
+runImportFlow();

+ 8 - 0
resources/SDWCVC/adapters.yaml

@@ -0,0 +1,8 @@
+adapters:
+  - adapter_id: "SDWCVC_01"
+    adapter_name: "山东水利职业学院树维教务"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "sdwcvc_01.js"
+    import_url: "https://sso.sdwcvc.cn/"
+    maintainer: "小漫君"
+    description: "登录统一认证并在门户中打开教务系统后导入,按所选学期读取课程与校历,使用学校公布的统一作息(第1~10节)。"

+ 340 - 0
resources/SDWCVC/sdwcvc_01.js

@@ -0,0 +1,340 @@
+// 山东水利职业学院树维 EAMS 拾光适配脚本
+// 适配作者:小漫君
+// 参数拆分、周次位图、逐周合并与日期校验复用拾光 ZUA/zua.js(沿用 HFNU/hfnu.js 的 EAMS 实现)。
+// TaskActivity 解析参考以上实现;教学周历英文日期格式参考 HIIT/hiit_01.js。
+// 上游:https://github.com/ShiGuangSchedule/shiguang_warehouse/tree/pending/resources
+// 按上游 MIT 许可保留来源;账号、学生参数、学期和开学日期均不写死。
+
+const BASE_URL = 'https://jw.sdwcvc.edu.cn';
+const MAX_SUPPORTED_WEEK = 60;
+
+// 来源:学校官网“作息时间”公布的统一作息(第 1~10 节)。
+// https://www.sdwcvc.edu.cn/ggfw/zxsj.htm
+const SDWCVC_TIME_SLOTS = [
+    { number: 1, startTime: '08:15', endTime: '09:00' },
+    { number: 2, startTime: '09:10', endTime: '09:55' },
+    { number: 3, startTime: '10:10', endTime: '10:55' },
+    { number: 4, startTime: '11:05', endTime: '11:50' },
+    { number: 5, startTime: '14:30', endTime: '15:15' },
+    { number: 6, startTime: '15:25', endTime: '16:10' },
+    { number: 7, startTime: '16:20', endTime: '17:05' },
+    { number: 8, startTime: '17:15', endTime: '18:00' },
+    { number: 9, startTime: '19:30', endTime: '20:15' },
+    { number: 10, startTime: '20:25', endTime: '21:10' }
+];
+
+function powerSplit(paramsRaw) {
+    const args = [];
+    let current = "";
+    let depth = 0;
+    let inQuote = false;
+    let quoteChar = "";
+
+    for (let i = 0; i < paramsRaw.length; i++) {
+        const char = paramsRaw[i];
+        if ((char === '"' || char === "'") && (i === 0 || paramsRaw[i - 1] !== "\\")) {
+            if (!inQuote) {
+                inQuote = true;
+                quoteChar = char;
+            } else if (char === quoteChar) {
+                inQuote = false;
+            }
+        }
+        if (!inQuote) {
+            if (char === "(" || char === "[" || char === "{") depth++;
+            if (char === ")" || char === "]" || char === "}") depth--;
+        }
+        if (char === "," && depth === 0 && !inQuote) {
+            args.push(cleanArg(current));
+            current = "";
+        } else {
+            current += char;
+        }
+    }
+    args.push(cleanArg(current));
+    return args;
+}
+
+function cleanArg(value) {
+    const trimmed = value.trim();
+    if (trimmed === "null") return null;
+    return trimmed.replace(/^["']|["']$/g, "");
+}
+
+function parseWeeksBitmap(bitmap) {
+    const weeks = [];
+    const value = String(bitmap || "");
+    // 树维 EAMS 位图的下标就是周次,下标 0 是占位符;拾光使用 1 基周次。
+    for (let week = 1; week < value.length && week <= MAX_SUPPORTED_WEEK; week++) {
+        if (value[week] === "1") weeks.push(week);
+    }
+    return weeks;
+}
+
+/**
+ * 沿用 HFNU 的按周次矩阵合并算法:只有课程名、教师、地点和星期均相同
+ * 且在同一周内节次连续时才合并。remark 不参与分组,重复实验项会由 Set 去重。
+ */
+
+function mergeContinuousLessons(lessons) {
+    if (!lessons || lessons.length === 0) return [];
+
+    const groups = {};
+    lessons.forEach(lesson => {
+        const key = `${lesson.name}|${lesson.teacher}|${lesson.position}|${lesson.day}`;
+        if (!groups[key]) {
+            groups[key] = {
+                name: lesson.name,
+                teacher: lesson.teacher,
+                position: lesson.position,
+                day: lesson.day,
+                weeksMatrix: Array.from({ length: MAX_SUPPORTED_WEEK + 1 }, () => new Set())
+            };
+        }
+
+        if (Array.isArray(lesson.weeks)) {
+            lesson.weeks.forEach(week => {
+                if (Number.isInteger(week) && week > 0 && week <= MAX_SUPPORTED_WEEK) {
+                    for (let section = lesson.startSection; section <= lesson.endSection; section++) {
+                        groups[key].weeksMatrix[week].add(section);
+                    }
+                }
+            });
+        }
+    });
+
+    const merged = [];
+    for (const key in groups) {
+        const group = groups[key];
+        const blockMap = {};
+
+        for (let week = 1; week < group.weeksMatrix.length; week++) {
+            const sections = Array.from(group.weeksMatrix[week]).sort((a, b) => a - b);
+            if (sections.length === 0) continue;
+
+            let start = sections[0];
+            let previous = sections[0];
+            for (let i = 1; i < sections.length; i++) {
+                const current = sections[i];
+                if (current === previous + 1) {
+                    previous = current;
+                } else {
+                    const blockKey = `${start}-${previous}`;
+                    if (!blockMap[blockKey]) blockMap[blockKey] = [];
+                    blockMap[blockKey].push(week);
+                    start = current;
+                    previous = current;
+                }
+            }
+
+            const blockKey = `${start}-${previous}`;
+            if (!blockMap[blockKey]) blockMap[blockKey] = [];
+            blockMap[blockKey].push(week);
+        }
+
+        for (const blockKey in blockMap) {
+            const [startSection, endSection] = blockKey.split("-").map(Number);
+            merged.push({
+                name: group.name,
+                teacher: group.teacher,
+                position: group.position,
+                day: group.day,
+                startSection,
+                endSection,
+                weeks: blockMap[blockKey]
+            });
+        }
+    }
+
+    merged.sort((a, b) => {
+        if (a.day !== b.day) return a.day - b.day;
+        if (a.startSection !== b.startSection) return a.startSection - b.startSection;
+        if (a.name !== b.name) return a.name.localeCompare(b.name);
+        return a.position.localeCompare(b.position);
+    });
+    return merged;
+}
+
+function normalizeNumericDate(year, month, day) {
+    const yearNumber = Number(year);
+    const monthNumber = Number(month);
+    const dayNumber = Number(day);
+    const date = new Date(Date.UTC(yearNumber, monthNumber - 1, dayNumber));
+    if (
+        date.getUTCFullYear() !== yearNumber ||
+        date.getUTCMonth() + 1 !== monthNumber ||
+        date.getUTCDate() !== dayNumber
+    ) {
+        return null;
+    }
+
+    return [
+        String(yearNumber).padStart(4, "0"),
+        String(monthNumber).padStart(2, "0"),
+        String(dayNumber).padStart(2, "0")
+    ].join("-");
+}
+
+
+function parseParameters(html) {
+    const student = html.match(/bg\.form\.addInput\(\s*form\s*,\s*["']ids["']\s*,\s*["'](\d+)["']\s*\)/);
+    const semester = html.match(/\bentityId\s*:\s*["'](\d+)["']/);
+    if (!student || !semester) throw new Error('未识别到教务课表参数,请先登录并进入“教务系统”。');
+    return { ids: student[1], semesterId: semester[1] };
+}
+
+function parseSemesters(html) {
+    const doc = new DOMParser().parseFromString(html, 'text/html');
+    const semesters = Array.from(doc.querySelectorAll('option')).map(function (option) {
+        const id = option.value.trim();
+        const name = option.textContent.trim();
+        if (!/^\d+$/.test(id) || !/^\d{4}-\d{4}-\d+$/.test(name)) throw new Error('学期列表格式不匹配。');
+        return { id, name };
+    });
+    if (semesters.length === 0) throw new Error('未获取到可选学期。');
+    return semesters;
+}
+
+function parseTeacherName(block) {
+    const teachers = block.match(/actTeachers\s*=\s*\[([\s\S]*?)\]\s*;/);
+    if (!teachers) throw new Error('课程教师字段结构不匹配。');
+    const names = Array.from(teachers[1].matchAll(/\bname\s*:\s*"([^"]*)"/g), function (match) { return match[1]; });
+    if (teachers[1].trim() && names.length === 0) throw new Error('课程教师字段结构不匹配。');
+    return Array.from(new Set(names)).join(',');
+}
+
+function parseTaskActivities(html) {
+    const unitCountMatch = html.match(/\bunitCount\s*=\s*(\d+)\s*;/);
+    if (!unitCountMatch || Number(unitCountMatch[1]) < 1) throw new Error('未获取到有效节次定义。');
+    const unitCount = Number(unitCountMatch[1]);
+    const indexRegex = new RegExp('index\\s*=\\s*(\\d+)\\s*\\*\\s*unitCount\\s*\\+\\s*(\\d+)\\s*;', 'g');
+    const rawResults = [];
+    const blocks = html.split(/var\s+teachers\s*=/);
+    const expectedCount = (html.match(/new\s+TaskActivity\(/g) || []).length;
+    let parsedCount = 0;
+
+    for (let i = 1; i < blocks.length; i++) {
+        const block = blocks[i];
+        const teacher = parseTeacherName(block);
+        const activities = Array.from(block.matchAll(/new\s+TaskActivity\(([\s\S]*?)\)\s*;/g));
+        for (let j = 0; j < activities.length; j++) {
+            parsedCount++;
+            const activity = activities[j];
+            const args = powerSplit(activity[1]);
+            if (args.length < 7 || typeof args[3] !== 'string' || typeof args[5] !== 'string' || !/^[01]+$/.test(args[6])) {
+                throw new Error('课程活动字段结构不匹配。');
+            }
+            // EAMS 的课程显示名在名称后附加 <sup ...>...</sup>,保留名称中的罗马数字等正文。
+            const name = args[3].replace(/\([^()]*\)\s*$/, '')
+                .replace(/<sup\b[^>]*>[\s\S]*?<\/sup>\s*$/i, '').trim();
+            const position = args[5].trim();
+            if (!name || args[6].length > MAX_SUPPORTED_WEEK + 1) throw new Error('课程名称或周次位图无效。');
+            const weeks = parseWeeksBitmap(args[6]);
+            // 全零位图没有实际教学周,不生成课程。
+            if (weeks.length === 0) continue;
+            const end = j + 1 < activities.length ? activities[j + 1].index : block.length;
+            const scope = block.slice(activity.index + activity[0].length, end);
+            indexRegex.lastIndex = 0;
+            let match;
+            let sectionCount = 0;
+            while ((match = indexRegex.exec(scope)) !== null) {
+                const day = Number(match[1]) + 1;
+                const section = Number(match[2]) + 1;
+                if (day < 1 || day > 7 || section < 1 || section > unitCount) throw new Error('课程星期或节次超出教务定义。');
+                rawResults.push({ name, teacher, position, day, startSection: section, endSection: section, weeks: [...weeks] });
+                sectionCount++;
+            }
+            if (sectionCount === 0) throw new Error('课程活动缺少实际上课节次。');
+        }
+    }
+    if (parsedCount !== expectedCount) throw new Error('课程活动结构不匹配。');
+    return mergeContinuousLessons(rawResults);
+}
+
+function parseCalendarInfo(html, semesterName) {
+    const doc = new DOMParser().parseFromString(html, 'text/html');
+    const termCell = Array.from(doc.querySelectorAll('td')).find(function (cell) {
+        return /学年度\s*\/\s*学期/.test(cell.textContent);
+    });
+    if (termCell?.nextElementSibling?.textContent.trim().replace(/\s+/g, '-') !== semesterName) {
+        throw new Error('返回校历与所选学期不一致。');
+    }
+    const text = doc.body.textContent;
+    const match = text.match(/([A-Za-z]{3})\s+(\d{1,2}),\s+(\d{4})\s*~\s*([A-Za-z]{3})\s+(\d{1,2}),\s+(\d{4})\s*\((\d+)\)/);
+    if (!match) throw new Error('未识别到教学周历起止日期。');
+    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+    const startDate = normalizeNumericDate(match[3], months.indexOf(match[1]) + 1, match[2]);
+    const endDate = normalizeNumericDate(match[6], months.indexOf(match[4]) + 1, match[5]);
+    const totalWeeks = Number(match[7]);
+    if (!startDate || !endDate || endDate < startDate || totalWeeks < 1 || totalWeeks > MAX_SUPPORTED_WEEK ||
+        new Date(startDate + 'T00:00:00Z').getUTCDay() !== 1) {
+        throw new Error('教学周历日期或总周数无效。');
+    }
+    return { semesterStartDate: startDate, semesterTotalWeeks: totalWeeks, firstDayOfWeek: 1, defaultClassDuration: 45, defaultBreakDuration: 10 };
+}
+
+async function requestText(path, parameters) {
+    const options = { credentials: 'include' };
+    if (parameters !== undefined) {
+        options.method = 'POST';
+        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' };
+        options.body = new URLSearchParams(parameters).toString();
+    }
+    const response = await fetch(BASE_URL + path, options);
+    if (!response.ok) throw new Error('教务请求失败(HTTP ' + response.status + ')。');
+    const responseUrl = new URL(response.url);
+    if (responseUrl.origin === BASE_URL && responseUrl.pathname === '/eams/loginExt.action') {
+        throw new Error('教务接口返回了登录页,请从统一认证门户重新打开“教务系统”后导入。');
+    }
+    return response.text();
+}
+
+async function runImportFlow() {
+    try {
+        if (window.location.origin !== BASE_URL) {
+            await window.shiguangBridgePromise.showAlert('请进入教务系统', '请先登录统一认证,并在门户中打开“教务系统”后导入。', '知道了');
+            return;
+        }
+        window.shiguangBridge.showToast('正在读取学期信息…');
+        const parameters = parseParameters(await requestText('/eams/courseTableForStd.action'));
+        const semesters = parseSemesters(await requestText('/eams/dataQuery.action', {
+            dataType: 'semester', entityId: parameters.semesterId
+        }));
+        const currentSemesterIndex = semesters.findIndex(function (semester) { return semester.id === parameters.semesterId; });
+        if (currentSemesterIndex < 0) throw new Error('学期列表缺少教务当前学期。');
+        const picked = await window.shiguangBridgePromise.showSingleSelection(
+            '选择学期', JSON.stringify(semesters.map(function (semester) { return semester.name; })),
+            currentSemesterIndex
+        );
+        if (picked === null) return;
+        if (!Number.isInteger(picked) || picked < 0 || picked >= semesters.length) throw new Error('学期选择无效。');
+        const semester = semesters[picked];
+        window.shiguangBridge.showToast('正在获取整学期课表…');
+        const courseHtml = await requestText('/eams/courseTableForStd!courseTable.action', {
+            ignoreHead: '1', 'setting.kind': 'std', startWeek: '', 'semester.id': semester.id, ids: parameters.ids
+        });
+        const courses = parseTaskActivities(courseHtml);
+        if (courses.length === 0) {
+            await window.shiguangBridgePromise.showAlert('该学期暂无课程', '所选学期没有已安排上课周次和节次的课程。', '知道了');
+            return;
+        }
+        const config = parseCalendarInfo(await requestText('/eams/base/calendar-info.action', {
+            version: '1', semesterId: semester.id
+        }), semester.name);
+        if (courses.some(function (course) { return course.weeks.some(function (week) { return week > config.semesterTotalWeeks; }); })) {
+            throw new Error('课程周次超出所选学期校历。');
+        }
+        if (courses.some(function (course) { return course.endSection > SDWCVC_TIME_SLOTS.length; })) {
+            throw new Error('课程节次超出学校统一作息表的第 1~10 节。');
+        }
+        if (!await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config))) throw new Error('课表配置保存失败。');
+        if (!await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(SDWCVC_TIME_SLOTS))) throw new Error('作息时间保存失败。');
+        if (!await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses))) throw new Error('课程保存失败。');
+        window.shiguangBridge.showToast('已获取 ' + courses.length + ' 条课程时段,并应用学校统一作息。');
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        await window.shiguangBridgePromise.showAlert('导入失败', error.message, '知道了');
+    }
+}
+
+runImportFlow();

+ 3 - 3
resources/ZQU/adapters.yaml

@@ -1,9 +1,9 @@
 # resources/ZQU/adapters.yaml
 adapters:
   - adapter_id: "ZQU_01"
-    adapter_name: "肇庆学院(WebVPN)"
+    adapter_name: "肇庆学院"
     category: "BACHELOR_AND_ASSOCIATE"
     asset_js_path: "zqu_01.js"
-    import_url: "https://webvpn.zqu.edu.cn/login"
+    import_url: "https://jwgl.zqu.edu.cn/"
     maintainer: "NoobLLiu"
-    description: "肇庆学院URP教务,校外访问走WebVPN。登录进入教务系统后点击开始导入,脚本直取课表JSON接口(getKbRq)一次读取整学期数据,导入过程中会请用户确认开学日期。无需打开课表查询页面,停留在教务系统任意页面即可。校内直连版本另行提交。非本校开发者适配,如有误差欢迎提issue"
+    description: "肇庆学院教务系统对接,登录进入教务系统后点击开始导入,无需打开课表查询页面,停留在教务系统任意页面即可。校外经WebVPN访问或校内直连均支持。"

+ 11 - 8
resources/ZQU/zqu_01.js

@@ -1,6 +1,7 @@
 // 肇庆学院(zqu.edu.cn) 拾光课程表适配脚本
 // 教务系统:URP 系(Struts2,形如 xxx!yyy.action)
-// 适用范围:本脚本为【WebVPN 校外访问】版本;校内直连版本另行提交
+// 适用范围:校外经 WebVPN 访问、或校内直连,两种渠道均支持。
+// 渠道由当前页面 URL 自动识别(见 siteBase),无需分别提供脚本。
 // 维护者:NoobLLiu
 //
 // 课表数据直接取自后台 JSON 接口,不做 HTML 表格解析:
@@ -8,7 +9,7 @@
 // zc 传空即不限周次,一次可取回整学期排课记录;每条记录自带 zc 字段
 // 标明该门课的上课周次,因此无需逐周请求,也无需读取页面 DOM。
 //
-// 使用前提:用户已在弹窗打开的网页中登录 WebVPN 并进入教务系统,
+// 使用前提:用户已在弹窗打开的网页中登录教务系统,
 // 停留在教务系统内的任意页面即可,无需打开课表查询页。
 
 // ---------------------------------------------------------------- 常量
@@ -45,11 +46,13 @@ const UNKNOWN_POSITION = '未获取到教室';
 /**
  * 推算教务系统的站点根路径。
  *
- * WebVPN 下页面地址形如:
- *   https://webvpn.zqu.edu.cn/https/<加密串>/xsgrkbcx!getXsgrbkList.action
- * 校内直连下形如:
- *   https://jwgl.zqu.edu.cn/xsgrkbcx!getXsgrbkList.action
- * 取到 <加密串>/ 这一层,后续所有接口都基于它拼接。
+ * 两种登录渠道下页面地址形如:
+ *   校外 WebVPN:https://webvpn.zqu.edu.cn/https/<加密串>/xsgrkbcx!getXsgrbkList.action
+ *   校内直连:    https://jwgl.zqu.edu.cn/xsgrkbcx!getXsgrbkList.action
+ *
+ * 二者只是站点根不同,其余完全一致。因此这里不判断渠道,
+ * 只按教务内部页面的路径特征截断:取到 xsgrkbcx! 之前的一段即为站点根
+ * (WebVPN 场景会自然带上 <加密串>/ 这一层),后续所有接口都基于它拼接。
  */
 function siteBase() {
     try {
@@ -405,7 +408,7 @@ function collectCourses(records) {
 async function promptUserToStart() {
     return await window.shiguangBridgePromise.showAlert(
         '肇庆学院课表导入',
-        '导入前请确认:\n1) 已在当前网页登录 WebVPN;\n2) 已进入教务系统(停留在任意页面即可,无需打开课表查询)。',
+        '导入前请确认:\n1) 已进入教务系统(校外经 WebVPN、校内直连均可);\n2) 停留在教务系统任意页面即可,无需打开课表查询。',
         '开始导入'
     );
 }