nefu.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /* 东北林业大学本部本科生院:强智个人课表导入。
  2. * 维护者:Chr0n0stasis。沿用已登录会话,不处理登录或保存凭据。
  3. * 桥接及合并规则参考拾光官方 Wiki,测试见 tests/NEFU。
  4. */
  5. (function (factory) {
  6. const api = factory();
  7. if (typeof module === 'object' && module.exports) module.exports = api;
  8. else void api.runImportFlow(window);
  9. })(function () {
  10. 'use strict';
  11. const ORIGIN = 'https://jwxt.nefu.edu.cn';
  12. const PATH = '/jsxsd/xskb/xskb_list.do';
  13. function fail(code, message) {
  14. const error = new Error(message); error.code = code; throw error;
  15. }
  16. const text = element => (element?.textContent || '').replace(/\s+/g, ' ').trim();
  17. function numbers(value, maximum, label) {
  18. const source = String(value).replace(/\s/g, '').replace(/[,、]/g, ',').replace(/[-–—~~]/g, '-');
  19. if (!/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(source)) fail('INVALID_RANGE', `${label}格式不支持:${value}`);
  20. const result = new Set();
  21. for (const part of source.split(',')) {
  22. const [a, b = a] = part.split('-').map(Number);
  23. if (a < 1 || b < a || b > maximum) fail('INVALID_RANGE', `${label}越界或倒序:${value}`);
  24. for (let n = a; n <= b; n++) result.add(n);
  25. }
  26. return [...result].sort((a, b) => a - b);
  27. }
  28. function parseTime(value) {
  29. // 本校已观察到 1-5,7-8周[1-2节];单双周分支只在 HTML 明确写出时采用。
  30. const match = String(value).replace(/\s/g, '').match(/^([\d,,、\--–—~~]+)(单|双)?周(?:[((](单|双)周?[))])?\[([\d,,、\--–—~~]+)节\]$/);
  31. if (!match) fail('INVALID_TIME', `课程时间格式不支持:${value}`);
  32. let weeks = numbers(match[1], 60, '周次');
  33. if (match[2] && match[3] && match[2] !== match[3]) fail('INVALID_TIME', '单双周标记相互矛盾');
  34. const parity = match[2] || match[3];
  35. if (parity) weeks = weeks.filter(w => w % 2 === (parity === '单' ? 1 : 0));
  36. if (!weeks.length) fail('INVALID_TIME', '单双周过滤后没有有效周次');
  37. const sections = numbers(match[4], 48, '节次');
  38. const ranges = [];
  39. for (const section of sections) {
  40. const last = ranges[ranges.length - 1];
  41. if (last && section === last[1] + 1) last[1] = section;
  42. else ranges.push([section, section]);
  43. }
  44. return { weeks, ranges };
  45. }
  46. function metadata(doc) {
  47. if (doc.querySelector('#userAccount, #userPassword') || /登录/.test(doc.title || '')) fail('LOGIN_REQUIRED', '请先在教务系统中登录;登录页不是空课表');
  48. const options = id => {
  49. const select = doc.querySelector(`#${id}`);
  50. if (!select) fail('NOT_TIMETABLE', `缺少 ${id},可能是外层框架、登录页或错误页面`);
  51. return { selected: select.value, items: [...select.options].map(o => ({ value: o.value, label: text(o) })) };
  52. };
  53. return { semesters: options('xnxq01id'), modes: options('kbjcmsid'), weeks: options('zc') };
  54. }
  55. function headerMap(table) {
  56. const headers = [...(table.tHead?.rows[0]?.cells || [])];
  57. const digits = { 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 日: 7, 天: 7 };
  58. const days = headers.map(cell => {
  59. const m = text(cell).match(/^(?:星期|周)([一二三四五六日天])$/);
  60. return m ? digits[m[1]] : null;
  61. });
  62. if (headers.length !== 8 || days[0] !== null || new Set(days.slice(1)).size !== 7 || days.slice(1).some(d => !d)) fail('BAD_HEADER', '课表必须能明确识别星期一至星期日');
  63. if (headers.some(h => h.colSpan !== 1 || h.rowSpan !== 1)) fail('BAD_HEADER', '暂不支持合并表头');
  64. return days;
  65. }
  66. function parseDocument(doc, expected = {}) {
  67. const meta = metadata(doc);
  68. for (const [key, actual] of [['semesterId', meta.semesters.selected], ['modeId', meta.modes.selected], ['week', meta.weeks.selected]]) {
  69. if (expected[key] !== undefined && String(expected[key]) !== actual) fail('QUERY_MISMATCH', `服务器返回的 ${key} 与请求不一致`);
  70. }
  71. const tables = [...doc.querySelectorAll('table.qz-weeklyTable')];
  72. if (tables.length !== 1) fail('NOT_TIMETABLE', '未发现唯一的正式周课表,不能按空课表处理');
  73. const table = tables[0], days = headerMap(table);
  74. const rows = [...table.tBodies].flatMap(body => [...body.rows]);
  75. if (!rows.length) fail('BAD_GRID', '缺少节次行');
  76. const grid = rows.map(() => Array(8));
  77. const teachingBlocks = [], allSections = new Set(), cells = [];
  78. let cardCount = 0;
  79. rows.forEach((row, rowIndex) => {
  80. let column = 0;
  81. // row.cells 只含当前 tr 的实际子单元格;rowspan 占位仅写入 grid。
  82. // 下方行跳过占位,不会再次遍历或统计同一个 td。
  83. for (const cell of row.cells) {
  84. while (column < 8 && grid[rowIndex][column]) column++;
  85. const height = cell.rowSpan, width = cell.colSpan;
  86. if (height < 1 || rowIndex + height > rows.length || column + width > 8) fail('BAD_GRID', '课表单元格跨行或跨列越界');
  87. for (let r = rowIndex; r < rowIndex + height; r++) for (let c = column; c < column + width; c++) {
  88. if (grid[r][c]) fail('BAD_GRID', '课表合并单元格重叠');
  89. grid[r][c] = cell;
  90. }
  91. if (column === 0) {
  92. if (cell.getAttribute('name') !== 'timeTd' || width !== 1 || height !== 1) fail('BAD_GRID', '节次标签结构已变化');
  93. const label = text(cell), sectionMatch = label.match(/[((]([\d、,,\s]+)小节[))]/);
  94. if (!sectionMatch) fail('BAD_GRID', '无法读取行标签中的小节编号');
  95. const sections = numbers(sectionMatch[1], 48, '节次行');
  96. sections.forEach(s => allSections.add(s));
  97. const clock = label.match(/(\d{2}:\d{2})\s*[~~\-]\s*(\d{2}:\d{2})/);
  98. teachingBlocks.push({ sections, startTime: clock?.[1] || null, endTime: clock?.[2] || null });
  99. } else {
  100. if (cell.getAttribute('name') !== 'kbDataTd' || width !== 1) fail('BAD_GRID', '课程单元格类型或跨列发生变化');
  101. const lists = [...cell.querySelectorAll('ul[name="kbdataUl"]')];
  102. if (lists.length !== 1) fail('BAD_GRID', '缺少唯一课程列表');
  103. const items = [...lists[0].children];
  104. if (items.some(e => !e.matches('li.courselists-item'))) fail('BAD_CARD', '出现未知课程卡片结构');
  105. const declaredText = lists[0].getAttribute('kbdatasize');
  106. if (declaredText !== null && (!/^\d+$/.test(declaredText) || Number(declaredText) !== items.length)) fail('BAD_CARD', '页面课程计数与卡片数不一致');
  107. cardCount += items.length;
  108. cells.push({ day: days[column], items });
  109. }
  110. column += width;
  111. }
  112. if (grid[rowIndex].filter(Boolean).length !== 8) fail('BAD_GRID', '课表行不完整,禁止猜测星期');
  113. });
  114. const courses = [], seen = new Set();
  115. for (const { day, items } of cells) for (const item of items) {
  116. const name = text(item.querySelector('.qz-hasCourse-title'));
  117. const detail = text(item.querySelector('.qz-hasCourse-abbrinfo'));
  118. const fields = detail.match(/^老师[::](.*?)[;;]时间[::](.*?)[;;]地点[::](.*)$/);
  119. if (!name || !fields) fail('BAD_CARD', '课程名称或老师/时间/地点字段结构不完整');
  120. const { weeks, ranges } = parseTime(fields[2]);
  121. for (const [startSection, endSection] of ranges) {
  122. for (let s = startSection; s <= endSection; s++) if (!allSections.has(s)) fail('BAD_CARD', '课程节次不在所选作息模式中');
  123. const course = { name, teacher: fields[1].trim(), position: fields[3].trim(), day, weeks: [...weeks], startSection, endSection };
  124. const key = JSON.stringify(course);
  125. if (!seen.has(key)) { seen.add(key); courses.push(course); }
  126. }
  127. }
  128. const remarks = [...table.querySelectorAll('tfoot .qz-weeklyTable-detailtext')].map(text).filter(Boolean);
  129. return {
  130. status: courses.length ? 'ok' : 'scheduled-empty',
  131. semesterId: meta.semesters.selected, modeId: meta.modes.selected, week: meta.weeks.selected,
  132. metadata: meta, courses, remarks, teachingBlocks,
  133. statistics: { sourceCards: cardCount, courseRecords: courses.length, distinctCourseNames: new Set(courses.map(c => c.name)).size },
  134. warnings: [
  135. ...(remarks.length ? ['存在未排具体星期/节次的备注项目;未伪造课程时间,请另行核对。'] : []),
  136. '仅导入课程,保留原有作息和学期设置。'
  137. ]
  138. };
  139. }
  140. function parseHTML(html, expected = {}) {
  141. if (typeof DOMParser === 'undefined') fail('NO_DOM', 'HTML 解析需要浏览器 DOMParser');
  142. return parseDocument(new DOMParser().parseFromString(html, 'text/html'), expected);
  143. }
  144. // 按周合并同名、同教师、同地点、同星期的连续节次,再汇总相同时段的周次。
  145. // 先按周拆分,避免把部分周次的调课扩展到整个学期。
  146. function mergeCourses(courses) {
  147. const groups = new Map();
  148. for (const course of courses) {
  149. const key = JSON.stringify([course.name, course.teacher, course.position, course.day]);
  150. if (!groups.has(key)) groups.set(key, { course, weeks: new Map() });
  151. const group = groups.get(key);
  152. for (const week of new Set(course.weeks)) {
  153. if (!group.weeks.has(week)) group.weeks.set(week, []);
  154. group.weeks.get(week).push([course.startSection, course.endSection]);
  155. }
  156. }
  157. const result = [];
  158. for (const { course, weeks } of groups.values()) {
  159. const ranges = new Map();
  160. for (const [week, intervals] of [...weeks].sort((a, b) => a[0] - b[0])) {
  161. intervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  162. const merged = [];
  163. for (const [start, end] of intervals) {
  164. const last = merged[merged.length - 1];
  165. if (last && start <= last[1] + 1) last[1] = Math.max(last[1], end);
  166. else merged.push([start, end]);
  167. }
  168. for (const [startSection, endSection] of merged) {
  169. const key = startSection + ':' + endSection;
  170. if (!ranges.has(key)) ranges.set(key, {
  171. name: course.name, teacher: course.teacher, position: course.position,
  172. day: course.day, startSection, endSection, weeks: []
  173. });
  174. ranges.get(key).weeks.push(week);
  175. }
  176. }
  177. result.push(...ranges.values());
  178. }
  179. return result.sort((a, b) => a.day - b.day || a.startSection - b.startSection ||
  180. a.endSection - b.endSection || a.name.localeCompare(b.name) ||
  181. a.teacher.localeCompare(b.teacher) || a.position.localeCompare(b.position) ||
  182. a.weeks[0] - b.weeks[0]);
  183. }
  184. function createClient(environment) {
  185. const env = environment || globalThis;
  186. if (env.location?.origin !== ORIGIN) fail('WRONG_ORIGIN', '请在东北林业大学教务系统中执行导入');
  187. async function getHTML(params) {
  188. const controller = new AbortController();
  189. const timer = setTimeout(() => controller.abort(), 20000);
  190. try {
  191. const response = await env.fetch(PATH + '?' + new URLSearchParams(params), {
  192. method: 'GET', credentials: 'same-origin', signal: controller.signal
  193. });
  194. if (!response.ok) fail('HTTP_ERROR', '教务响应 HTTP ' + response.status);
  195. if (new URL(response.url, ORIGIN).origin !== ORIGIN) fail('LOGIN_REQUIRED', '登录已失效,请重新登录');
  196. const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
  197. metadata(doc);
  198. return doc;
  199. } catch (error) {
  200. if (error.name === 'AbortError') fail('TIMEOUT', '教务请求超时,请稍后重试');
  201. throw error;
  202. } finally {
  203. clearTimeout(timer);
  204. }
  205. }
  206. return Object.freeze({
  207. async options() { return metadata(await getHTML({ viweType: '0' })); },
  208. async load({ semesterId, modeId, week = '' } = {}, available) {
  209. const meta = available || await this.options();
  210. const semester = semesterId ?? meta.semesters.selected;
  211. const mode = modeId ?? meta.modes.items.find(o => o.label === '本部')?.value ?? meta.modes.selected;
  212. if (!meta.semesters.items.some(o => o.value === semester)) fail('BAD_SELECTION', '学期不在教务返回的选项内');
  213. if (!meta.modes.items.some(o => o.value === mode)) fail('BAD_SELECTION', '作息模式不在教务返回的选项内');
  214. if (String(week) !== '' && !/^(?:[1-9]|[1-5]\d|60)$/.test(String(week))) fail('BAD_SELECTION', '周次必须为空或 1 到 60 的整数');
  215. const doc = await getHTML({ viweType: '0', xnxq01id: semester, kbjcmsid: mode, zc: String(week) });
  216. return parseDocument(doc, { semesterId: semester, modeId: mode, week: String(week) });
  217. }
  218. });
  219. }
  220. async function runImportFlow(env) {
  221. const bridge = env.shiguangBridgePromise;
  222. const ui = env.shiguangBridge;
  223. try {
  224. const client = createClient(env);
  225. const meta = await client.options();
  226. const index = await bridge.showSingleSelection(
  227. '选择学期(本部本科生院)',
  228. JSON.stringify(meta.semesters.items.map(item => item.label)),
  229. meta.semesters.items.findIndex(item => item.value === meta.semesters.selected)
  230. );
  231. if (index === null) return { status: 'cancelled' };
  232. if (!Number.isInteger(index) || index < 0 || index >= meta.semesters.items.length) {
  233. fail('BAD_SELECTION', '学期选择无效');
  234. }
  235. ui.showToast('正在读取课程;本次保留原有作息和学期设置。');
  236. const result = await client.load({ semesterId: meta.semesters.items[index].value }, meta);
  237. const courses = mergeCourses(result.courses);
  238. if (result.remarks.length) ui.showToast('教务另有未排具体时间的备注项目,请在教务课表中查看。');
  239. // 沿用 App 的目标课表选择和覆盖流程。正常空课表也按完整查询结果提交。
  240. if (await bridge.saveImportedCourses(JSON.stringify(courses)) !== true) {
  241. fail('SAVE_FAILED', '课程保存失败,请重试');
  242. }
  243. ui.showToast(courses.length ? '已导入 ' + courses.length + ' 条排课记录。' : '该学期没有已排时间的课程,已导入空课表。');
  244. ui.notifyTaskCompletion();
  245. return { status: 'saved', count: courses.length };
  246. } catch (error) {
  247. const message = error.code ? error.message : '网络或导入操作失败,请检查登录状态后重试';
  248. if (ui) ui.showToast('导入失败:' + message);
  249. return { status: 'error', code: error.code || 'IMPORT_FAILED' };
  250. }
  251. }
  252. return Object.freeze({ numbers, parseTime, metadata, parseDocument, parseHTML, mergeCourses, createClient, runImportFlow });
  253. });