qfnu_01.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // 曲阜师范大学(zhjw.qfnu.edu.cn) 拾光课程表适配脚本
  2. // 教务系统:强智 jsxsd
  3. // 使用流程:在软件内置浏览器登录教务系统,停留在任意教务功能页面后执行导入
  4. // 说明:学期列表与教学周历自动读取;教务系统不提供节次时间,导入后需在软件内设置上课时间
  5. // 维护者:Yumu-banxia
  6. const QFNU_KB_URL = '/jsxsd/xskb/xskb_list.do';
  7. const QFNU_CALENDAR_URL = '/jsxsd/jxzl/jxzl_query';
  8. const QFNU_CLASS_DURATION = 45;
  9. const QFNU_BREAK_DURATION = 10;
  10. const QFNU_POST_OPTIONS = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };
  11. // ==================== 桥接封装 ====================
  12. function toast(message) {
  13. if (window.shiguangBridge && typeof window.shiguangBridge.showToast === 'function') {
  14. window.shiguangBridge.showToast(message);
  15. } else {
  16. console.log('[QFNU] ' + message);
  17. }
  18. }
  19. async function alertUser(title, message) {
  20. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.showAlert === 'function') {
  21. const confirmed = await window.shiguangBridgePromise.showAlert(title, message, '知道了');
  22. return confirmed === true || confirmed === 'true';
  23. }
  24. alert(title + '\n' + message);
  25. return true;
  26. }
  27. // 原生以字符串序号或 "null" 回传,统一为数字序号,-1 表示取消
  28. async function selectFromList(title, items, defaultIndex) {
  29. if (!(window.shiguangBridgePromise && typeof window.shiguangBridgePromise.showSingleSelection === 'function')) {
  30. return defaultIndex;
  31. }
  32. const result = await window.shiguangBridgePromise.showSingleSelection(title, JSON.stringify(items), defaultIndex);
  33. if (result === null || result === undefined || result === 'null') return -1;
  34. const index = typeof result === 'number' ? result : parseInt(result, 10);
  35. return isNaN(index) ? -1 : index;
  36. }
  37. // ==================== 请求 ====================
  38. // 兼容直连与 WebVPN 形态的地址,取 /jsxsd/ 之前的部分作为前缀
  39. function jsxsdUrl(path) {
  40. const currentPath = window.location.pathname || '';
  41. const index = currentPath.indexOf('/jsxsd/');
  42. return window.location.origin + (index < 0 ? '' : currentPath.slice(0, index)) + path;
  43. }
  44. async function requestText(url, options) {
  45. const response = await fetch(url, Object.assign({ credentials: 'include' }, options || {}));
  46. return await response.text();
  47. }
  48. // 课表页表单字段与页面 Form1 一致,POST 失败时退回带查询参数的 GET
  49. async function fetchTimetableDoc(semesterValue, kbjcmsid) {
  50. const url = jsxsdUrl(QFNU_KB_URL);
  51. const body = 'jx0404id=&cj0701id=&zc=&demo=&xnxq01id=' + encodeURIComponent(semesterValue) +
  52. '&sfFD=1&kbjcmsid=' + encodeURIComponent(kbjcmsid);
  53. const posted = new DOMParser().parseFromString(
  54. await requestText(url, Object.assign({ method: 'POST', body: body }, QFNU_POST_OPTIONS)), 'text/html');
  55. if (findTimetableTable(posted)) return posted;
  56. const got = new DOMParser().parseFromString(
  57. await requestText(url + '?xnxq01id=' + encodeURIComponent(semesterValue)), 'text/html');
  58. return findTimetableTable(got) ? got : null;
  59. }
  60. // ==================== 学期与教学周历 ====================
  61. // 学期列表:[{ value: "2026-2027-1", label: "2026-2027 学年第 1 学期", selected: true }]
  62. function parseSemesters(doc) {
  63. const select = doc.querySelector('select[name="xnxq01id"], select#xnxq01id');
  64. if (!select) return [];
  65. const list = [];
  66. select.querySelectorAll('option').forEach(function (option) {
  67. const value = String(option.getAttribute('value') || '').trim();
  68. if (!value) return;
  69. list.push({
  70. value: value,
  71. label: value.replace(/^(\d{4})-(\d{4})-(\d)$/, '$1-$2 学年第 $3 学期'),
  72. selected: option.hasAttribute('selected')
  73. });
  74. });
  75. return list;
  76. }
  77. function parseKbjcmsid(doc) {
  78. const select = doc.querySelector('select[name="kbjcmsid"]');
  79. const option = select ? (select.querySelector('option[selected]') || select.querySelector('option')) : null;
  80. return option ? String(option.getAttribute('value') || '').trim() : '';
  81. }
  82. // 教学周历:首列为周次序号,第二列含该周星期一日期
  83. function parseCalendar(doc) {
  84. const result = { semesterStartDate: null, totalWeeks: null };
  85. const table = doc.querySelector('table');
  86. if (!table) return result;
  87. const toDate = function (text) {
  88. const match = String(text || '').match(/(\d{4})\s*[-年]\s*(\d{1,2})\s*[-月]\s*(\d{1,2})/);
  89. return match ? match[1] + '-' + match[2].padStart(2, '0') + '-' + match[3].padStart(2, '0') : null;
  90. };
  91. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  92. const cells = Array.from(row.children);
  93. const first = cells.length > 0 ? String(cells[0].textContent).trim() : '';
  94. if (!/^\d+$/.test(first)) return;
  95. const week = parseInt(first, 10);
  96. result.totalWeeks = result.totalWeeks === null ? week : Math.max(result.totalWeeks, week);
  97. if (week === 1 && !result.semesterStartDate && cells.length > 1) {
  98. result.semesterStartDate = toDate(cells[1].getAttribute('title')) || toDate(cells[1].textContent);
  99. }
  100. });
  101. return result;
  102. }
  103. async function fetchCalendar(semesterValue) {
  104. try {
  105. const text = await requestText(jsxsdUrl(QFNU_CALENDAR_URL), Object.assign(
  106. { method: 'POST', body: 'xnxq01id=' + encodeURIComponent(semesterValue) }, QFNU_POST_OPTIONS));
  107. return parseCalendar(new DOMParser().parseFromString(text, 'text/html'));
  108. } catch (error) {
  109. console.warn('[QFNU] 教学周历读取失败:', error);
  110. return { semesterStartDate: null, totalWeeks: null };
  111. }
  112. }
  113. // ==================== 课表解析 ====================
  114. // 不同强智版本分别使用 #timetable 与 #kbtable
  115. function findTimetableTable(doc) {
  116. return doc.getElementById('timetable') || doc.getElementById('kbtable');
  117. }
  118. // 周次与节次:兼容 1-16(周)[01-02节]、1-8,10-16(周)、1-15周(单)、2-16(双)、第3-4节 等写法
  119. function parseWeeksAndSections(text) {
  120. const result = { weeks: [], sections: [] };
  121. const content = String(text || '').trim();
  122. if (!content) return result;
  123. const parity = /双/.test(content) ? 2 : (/单/.test(content) ? 1 : 0);
  124. const bracketIndex = content.indexOf('[');
  125. const cleaned = (bracketIndex >= 0 ? content.slice(0, bracketIndex) : content)
  126. .replace(/第/g, '')
  127. .replace(/至|到|~/g, '-')
  128. .replace(/[((][^()()]*[))]/g, '')
  129. .replace(/周/g, '');
  130. cleaned.split(/[,,、;;\s]+/).forEach(function (segment) {
  131. const item = segment.trim();
  132. const range = item.match(/^(\d+)\s*[-–—]\s*(\d+)$/);
  133. if (range) {
  134. for (let week = parseInt(range[1], 10); week <= parseInt(range[2], 10); week++) result.weeks.push(week);
  135. } else if (/^\d+$/.test(item)) {
  136. result.weeks.push(parseInt(item, 10));
  137. }
  138. });
  139. if (parity) {
  140. result.weeks = result.weeks.filter(function (week) { return week % 2 === (parity === 1 ? 1 : 0); });
  141. }
  142. result.weeks = Array.from(new Set(result.weeks)).sort(function (a, b) { return a - b; });
  143. const sectionMatch = content.match(/\[([^\]]*)\]/);
  144. if (sectionMatch) {
  145. (sectionMatch[1].match(/\d+/g) || []).forEach(function (number) {
  146. const section = parseInt(number, 10);
  147. if (result.sections.indexOf(section) < 0) result.sections.push(section);
  148. });
  149. result.sections.sort(function (a, b) { return a - b; });
  150. }
  151. return result;
  152. }
  153. // 收集单个课表单元格内的全部课程候选。强智在格内同时输出简表与详表,
  154. // 简表缺少教师与节次方括号,此处一并解析,交由归并阶段择优。
  155. function collectCellCandidates(cellDiv, day, output, rowSections) {
  156. const html = String(cellDiv.innerHTML || '').trim();
  157. if (!html || html.replace(/&nbsp;/gi, '').trim() === '') return;
  158. html.split(/[-—–]{6,}\s*(?:<br\s*\/?>)?/i).forEach(function (blockHtml) {
  159. if (!blockHtml.trim()) return;
  160. const holder = document.createElement('div');
  161. holder.innerHTML = blockHtml;
  162. let name = '';
  163. for (let i = 0; i < holder.childNodes.length; i++) {
  164. const node = holder.childNodes[i];
  165. if (node.nodeType === 3 && /[\u4e00-\u9fa5]/.test(node.textContent)) {
  166. name = node.textContent.trim();
  167. break;
  168. }
  169. }
  170. if (!name) name = String(holder.textContent || '').split('\n')[0].trim();
  171. if (!name) return;
  172. const pickText = function (titles) {
  173. for (let i = 0; i < titles.length; i++) {
  174. const element = holder.querySelector('font[title*="' + titles[i] + '"]');
  175. if (element && element.textContent.trim()) return element.textContent.trim();
  176. }
  177. return '';
  178. };
  179. let timeText = pickText(['周次', '节次']);
  180. if (!/\[[^\]]*\]/.test(timeText)) {
  181. const bracket = String(holder.textContent || '').match(/\[[^\]]*\]/);
  182. if (bracket) timeText += bracket[0];
  183. }
  184. const parsed = parseWeeksAndSections(timeText || holder.textContent);
  185. if (parsed.weeks.length === 0) return;
  186. if (parsed.sections.length === 0 && rowSections) {
  187. for (let section = rowSections[0]; section <= rowSections[1]; section++) parsed.sections.push(section);
  188. }
  189. const teacher = pickText(['教师', '老师']);
  190. const position = pickText(['教室', '地点']).replace(/\[\s*\d+\s*-\s*\d+\s*\]\s*节?$/, '').trim();
  191. output.push({
  192. name: name,
  193. teacher: teacher,
  194. position: position,
  195. day: day,
  196. weeks: parsed.weeks,
  197. sections: parsed.sections,
  198. score: (teacher ? 4 : 0) + (/\[[^\]]*\]/.test(timeText) ? 3 : 0) +
  199. (position ? 1 : 0) + (parsed.sections.length > 1 ? 1 : 0)
  200. });
  201. });
  202. }
  203. // 按课程名、周次、教室归并候选,保留信息更完整的一条
  204. function mergeCellCandidates(candidates) {
  205. const groups = {};
  206. const order = [];
  207. candidates.forEach(function (item) {
  208. const key = item.name + '|' + item.weeks.join(',') + '|' + item.position;
  209. if (groups[key] === undefined) {
  210. groups[key] = item;
  211. order.push(key);
  212. } else if (item.score > groups[key].score) {
  213. groups[key] = item;
  214. }
  215. });
  216. const courses = [];
  217. order.forEach(function (key) {
  218. const item = groups[key];
  219. if (item.sections.length === 0) return;
  220. courses.push({
  221. name: item.name,
  222. teacher: item.teacher || '未知教师',
  223. position: item.position || '未知地点',
  224. day: item.day,
  225. weeks: item.weeks,
  226. startSection: item.sections[0],
  227. endSection: item.sections[item.sections.length - 1]
  228. });
  229. });
  230. return courses;
  231. }
  232. function parseTimetable(doc) {
  233. const table = findTimetableTable(doc);
  234. if (!table) return [];
  235. const courses = [];
  236. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  237. const label = row.querySelector('th');
  238. const labelMatch = label ? String(label.textContent).match(/(\d+)\s*[~~\-—]\s*(\d+)\s*节/) : null;
  239. const rowSections = labelMatch ? [parseInt(labelMatch[1], 10), parseInt(labelMatch[2], 10)] : null;
  240. Array.from(row.querySelectorAll('td')).forEach(function (cell, index) {
  241. const blocks = cell.querySelectorAll('div.kbcontent, div.kbcontent1');
  242. if (blocks.length === 0) return;
  243. const candidates = [];
  244. Array.from(blocks).forEach(function (block) {
  245. collectCellCandidates(block, index + 1, candidates, rowSections);
  246. });
  247. mergeCellCandidates(candidates).forEach(function (course) {
  248. courses.push(course);
  249. });
  250. });
  251. });
  252. return courses;
  253. }
  254. // 节次与周次合并去重函数
  255. // 来源:官方 Wiki《课程合并与去重函数》
  256. // https://github.com/XingHeYuZhuan/shiguangschedule/wiki/课程合并与去重函数
  257. // 阶段一按名称、教师、地点、星期、周次一致合并连续节次并去除完全重复,阶段二按相同节次合并周次
  258. function mergeAndDistinctCourses(courses) {
  259. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  260. const list = courses.map(c => ({
  261. ...c,
  262. name: c.name || '',
  263. teacher: c.teacher || '',
  264. position: c.position || '',
  265. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  266. }));
  267. list.sort((a, b) => {
  268. return a.name.localeCompare(b.name) ||
  269. a.teacher.localeCompare(b.teacher) ||
  270. a.position.localeCompare(b.position) ||
  271. (a.day || 0) - (b.day || 0) ||
  272. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  273. (a.startSection || 0) - (b.startSection || 0);
  274. });
  275. const step1Merged = [];
  276. let current = list[0];
  277. for (let i = 1; i < list.length; i++) {
  278. const next = list[i];
  279. const isSameCourseAndWeeks =
  280. current.name === next.name &&
  281. current.teacher === next.teacher &&
  282. current.position === next.position &&
  283. current.day === next.day &&
  284. current.weeks.join(',') === next.weeks.join(',');
  285. const isContinuous = current.endSection + 1 === next.startSection;
  286. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  287. if (isSameCourseAndWeeks && isContinuous) {
  288. current.endSection = next.endSection;
  289. } else if (isSameCourseAndWeeks && isDuplicate) {
  290. continue;
  291. } else {
  292. step1Merged.push(current);
  293. current = next;
  294. }
  295. }
  296. step1Merged.push(current);
  297. step1Merged.sort((a, b) => {
  298. return a.name.localeCompare(b.name) ||
  299. a.teacher.localeCompare(b.teacher) ||
  300. a.position.localeCompare(b.position) ||
  301. (a.day || 0) - (b.day || 0) ||
  302. (a.startSection || 0) - (b.startSection || 0) ||
  303. (a.endSection || 0) - (b.endSection || 0);
  304. });
  305. const step2Merged = [];
  306. let merged = step1Merged[0];
  307. for (let i = 1; i < step1Merged.length; i++) {
  308. const next = step1Merged[i];
  309. const isSameCourseAndSection =
  310. merged.name === next.name &&
  311. merged.teacher === next.teacher &&
  312. merged.position === next.position &&
  313. merged.day === next.day &&
  314. merged.startSection === next.startSection &&
  315. merged.endSection === next.endSection;
  316. if (isSameCourseAndSection) {
  317. merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
  318. } else {
  319. step2Merged.push(merged);
  320. merged = next;
  321. }
  322. }
  323. step2Merged.push(merged);
  324. return step2Merged;
  325. }
  326. // ==================== 流程编排 ====================
  327. async function runImportFlow() {
  328. try {
  329. if ((window.location.pathname || '').indexOf('/jsxsd/') < 0) {
  330. await alertUser('请先进入教务系统', '请登录教务系统并停留在任意教务功能页面后重新执行导入。');
  331. return;
  332. }
  333. toast('正在获取学期信息…');
  334. const listDoc = new DOMParser().parseFromString(await requestText(jsxsdUrl(QFNU_KB_URL)), 'text/html');
  335. const semesters = parseSemesters(listDoc);
  336. if (semesters.length === 0) {
  337. await alertUser('未获取到学期列表', '课表页返回异常,请确认登录状态有效后重试。');
  338. return;
  339. }
  340. let defaultIndex = 0;
  341. semesters.forEach(function (item, index) { if (item.selected) defaultIndex = index; });
  342. const picked = semesters.length > 1
  343. ? await selectFromList('选择学期', semesters.map(function (item) { return item.label; }), defaultIndex)
  344. : defaultIndex;
  345. if (picked < 0 || picked >= semesters.length) {
  346. toast('导入已取消');
  347. return;
  348. }
  349. const semester = semesters[picked];
  350. toast('正在获取 ' + semester.label + ' 课表…');
  351. const tableDoc = await fetchTimetableDoc(semester.value, parseKbjcmsid(listDoc));
  352. if (!tableDoc) {
  353. await alertUser('未获取到课表数据', '请确认已登录教务系统后重试。');
  354. return;
  355. }
  356. const courses = mergeAndDistinctCourses(parseTimetable(tableDoc));
  357. if (courses.length === 0) {
  358. await alertUser('未解析到课程', semester.label + ' 页面中没有课程内容,该学期可能尚未发布课表。');
  359. return;
  360. }
  361. const calendar = await fetchCalendar(semester.value);
  362. const weeks = courses.reduce(function (all, course) { return all.concat(course.weeks); }, []);
  363. const config = {
  364. semesterTotalWeeks: calendar.totalWeeks || Math.max.apply(null, weeks),
  365. defaultClassDuration: QFNU_CLASS_DURATION,
  366. defaultBreakDuration: QFNU_BREAK_DURATION
  367. };
  368. if (calendar.semesterStartDate) {
  369. config.semesterStartDate = calendar.semesterStartDate;
  370. } else {
  371. toast('未读取到教学周历,开学日期可在软件内手动校准');
  372. }
  373. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  374. if (!await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses))) {
  375. toast('课程保存失败,请重试');
  376. return;
  377. }
  378. toast('导入成功:' + semester.label + ' 共 ' + courses.length + ' 条课程时段');
  379. if (window.shiguangBridge && typeof window.shiguangBridge.notifyTaskCompletion === 'function') {
  380. window.shiguangBridge.notifyTaskCompletion();
  381. }
  382. } catch (error) {
  383. console.error('[QFNU] 导入流程异常:', error);
  384. await alertUser('导入失败', error && error.message ? error.message : String(error));
  385. }
  386. }
  387. // 启动导入流程
  388. runImportFlow();