csu.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // 中南大学 拾光课程表适配脚本(强智 jsxsd,与 CSUFT 同厂但页面结构不同)
  2. //
  3. // 四个坑:
  4. // ① 表头列序为「星期日、星期一…」,星期日在第 0 列,需映射为 day=7
  5. // ② 节次表头是全角连字符「1-2」
  6. // ③ 格内 kbcontent1 是隐藏旧数据,必须精确取 div.kbcontent,否则课程翻倍
  7. // ④ 课表页有两个 id=kbtable:第一个是课程表,第二个是页脚周次表
  8. //
  9. // 数据全部走同源请求,不读当前页面。整体包在 IIFE 里:App 每次点导入都会重新
  10. // evaluate 本文件,顶层直接写 const 会让第二次抛 "already been declared" 而崩掉。
  11. (function () {
  12. const KB_PATH = "/jsxsd/xskb/xskb_list.do";
  13. const JXZL_PATH = "/jsxsd/jxzl/jxzl_query"; // 教学周历:学期列表 + 开学日期 + 总周次
  14. // 网络请求:与适配案例一一对应,返回 HTML 文本,解析交给调用方
  15. // 同源请求:有 body 走 POST,否则 GET
  16. async function requestPage(path, body) {
  17. const opt = { method: body ? "POST" : "GET", credentials: "include" };
  18. if (body) {
  19. opt.headers = { "Content-Type": "application/x-www-form-urlencoded" };
  20. opt.body = body;
  21. }
  22. const resp = await fetch(location.origin + path, opt);
  23. if (!resp.ok) throw new Error("HTTP " + resp.status);
  24. return await resp.text();
  25. }
  26. // 三个入口与适配案例同名,便于对照
  27. function requestSemesterPage() {
  28. return requestPage(JXZL_PATH);
  29. }
  30. function requestSemesterDetailPage(semesterId) {
  31. return requestPage(JXZL_PATH, "xnxq01id=" + encodeURIComponent(semesterId));
  32. }
  33. function requestCoursePage(semesterId) {
  34. return requestPage(KB_PATH, "cj0701id=&zc=&demo=&xnxq01id=" + encodeURIComponent(semesterId));
  35. }
  36. // 中南共 9 个学期,全列;案例的「上下各 3 个」会选不到更早的学期
  37. async function fetchSemesterList() {
  38. const doc = parseDoc(await requestSemesterPage());
  39. const select = doc.getElementById("xnxq01id");
  40. const all = select ? Array.from(select.querySelectorAll("option"))
  41. .map(o => ({
  42. value: o.value,
  43. label: (o.textContent || "").trim(),
  44. selected: o.hasAttribute("selected")
  45. }))
  46. .filter(o => o.value) : [];
  47. if (all.length === 0) return { list: [], defaultIndex: 0 };
  48. let idx = all.findIndex(o => o.selected);
  49. if (idx < 0) idx = 0;
  50. return { list: all, defaultIndex: idx };
  51. }
  52. // 开学日期、总周次、周起始日。
  53. // 教务不同学期的周起始并不一致:周日列有日期就从周日起算(firstDayOfWeek=7),
  54. // 该列留空则第 1 周从周一开始(=1)。取第 1 行第一个日期格,按它自己的星期判断。
  55. async function fetchSemesterInfo(semesterId) {
  56. const doc = parseDoc(await requestSemesterDetailPage(semesterId));
  57. const table = doc.getElementById("kbtable");
  58. const rows = table
  59. ? Array.from(table.querySelectorAll("tr")).filter(r => r.querySelector("td"))
  60. : [];
  61. if (rows.length === 0) return { startDate: null, totalWeeks: null, firstDayOfWeek: 7 };
  62. let startDate = null;
  63. let firstDayOfWeek = 7;
  64. const cell = rows[0].querySelector("td[title]");
  65. const m = /^(\d{4})年(\d{2})月(\d{2})/.exec(cell ? (cell.getAttribute("title") || "") : "");
  66. if (m) {
  67. startDate = m[1] + "-" + m[2] + "-" + m[3];
  68. const d = new Date(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10));
  69. firstDayOfWeek = d.getDay() === 0 ? 7 : 1;
  70. }
  71. let totalWeeks = null;
  72. for (const row of rows) {
  73. const first = row.querySelector("td");
  74. const n = parseInt(first ? first.textContent.trim() : "", 10);
  75. if (!isNaN(n) && n > 0 && (totalWeeks === null || n > totalWeeks)) totalWeeks = n;
  76. }
  77. return { startDate, totalWeeks, firstDayOfWeek };
  78. }
  79. async function fetchCourses(semesterId) {
  80. const doc = parseDoc(await requestCoursePage(semesterId));
  81. // 教学周历页同样有 table#kbtable,用 kbcontent 判断是不是真正的课表
  82. if (!doc.querySelector("div.kbcontent")) throw new Error("返回页面里没有课程,请确认已登录");
  83. return parseSchedule(doc);
  84. }
  85. const WEEKDAY_MAP = {
  86. '星期一': 1, '星期二': 2, '星期三': 3, '星期四': 4,
  87. '星期五': 5, '星期六': 6, '星期日': 7, '星期天': 7
  88. };
  89. // 中南作息:校历「上课时间」,2024-2025 起三学年一致,共 10 节。
  90. // 第九节前 17:40-19:00 为晚餐不排课,故第九节不接第八节。
  91. const TIME_SLOTS = [
  92. { number: 1, startTime: "08:00", endTime: "08:45" },
  93. { number: 2, startTime: "08:55", endTime: "09:40" },
  94. { number: 3, startTime: "10:00", endTime: "10:45" },
  95. { number: 4, startTime: "10:55", endTime: "11:40" },
  96. { number: 5, startTime: "14:00", endTime: "14:45" },
  97. { number: 6, startTime: "14:55", endTime: "15:40" },
  98. { number: 7, startTime: "16:00", endTime: "16:45" },
  99. { number: 8, startTime: "16:55", endTime: "17:40" },
  100. { number: 9, startTime: "19:00", endTime: "19:45" },
  101. { number: 10, startTime: "19:55", endTime: "20:40" }
  102. ];
  103. function parseDoc(html) {
  104. return new DOMParser().parseFromString(html, 'text/html');
  105. }
  106. // 两个 id=kbtable(课程格子 / 页脚周次表),按「含星期表头」筛出课程表
  107. function findCourseTable(doc) {
  108. const tables = doc.querySelectorAll('table#kbtable');
  109. for (const t of tables) {
  110. const head = t.querySelector('tr');
  111. if (head && /星期/.test(head.textContent)) return t;
  112. }
  113. return null;
  114. }
  115. // '1-2' → [1,2];取首尾数字,'1-2,3-4' 表示 1~4 节连排
  116. function parseSections(thText) {
  117. const nums = String(thText).match(/\d+/g);
  118. if (!nums) return null;
  119. return [parseInt(nums[0], 10), parseInt(nums[nums.length - 1], 10)];
  120. }
  121. // 周次:'3-12(周)' / '1,3,5(周)' / '2-4,8-20双周' / '3-12(周)[01-02节]'
  122. // 单双标记有 (单)/(双)/(单周)/(双周)/裸「双周」等形态
  123. function parseWeeks(weekStr) {
  124. const weeks = [];
  125. if (!weekStr) return weeks;
  126. let odd = false, even = false;
  127. // 圆括号与方括号整段摘掉。方括号里是节次(如 '[01-02节]'),
  128. // 不摘的话数字会粘成 '3-1201-02' 导致区间匹配失败、只剩第 3 周
  129. let rest = String(weekStr)
  130. .replace(/[((][^))]*[))]/g, '')
  131. .replace(/[\[【][^\]】]*[\]】]/g, '');
  132. // 单双只看括号内,避免课程名里的「双」字被误判
  133. if (/[((][^))]*单[^))]*[))]/.test(weekStr)) odd = true;
  134. if (/[((][^))]*双[^))]*[))]/.test(weekStr)) even = true;
  135. // 裸标记须在提数字前剥离,否则 '8-20双周' 的「双」会粘住区间尾部
  136. rest = rest.replace(/单周|双周/g, '').replace(/周|第/g, '');
  137. if (!odd && !even) {
  138. if (/单周/.test(weekStr)) odd = true;
  139. if (/双周/.test(weekStr)) even = true;
  140. }
  141. rest = rest.replace(/[^\d\--~~,,]/g, ''); // 容忍 '3-12(周)abc' 这类脏数据
  142. for (let seg of rest.split(/[,,]/)) {
  143. seg = seg.trim();
  144. if (!seg) continue;
  145. const m = /^(\d+)\s*[--~~]\s*(\d+)$/.exec(seg);
  146. if (m) {
  147. const s = parseInt(m[1], 10), e = parseInt(m[2], 10);
  148. if (e >= s) for (let i = s; i <= e; i++) weeks.push(i);
  149. else weeks.push(s); // 倒序区间
  150. } else {
  151. const mm = /\d+/.exec(seg);
  152. if (mm) weeks.push(parseInt(mm[0], 10));
  153. }
  154. }
  155. let result = Array.from(new Set(weeks)).sort((a, b) => a - b);
  156. // 单双同时出现时不过滤,无法判定按哪个走,宁可多留不要丢课
  157. if (odd && !even) result = result.filter(w => w % 2 === 1);
  158. else if (even && !odd) result = result.filter(w => w % 2 === 0);
  159. return result;
  160. }
  161. // '贺福利[副教授]' → '贺福利'
  162. function cleanTeacher(s) {
  163. return String(s).replace(/[\[【][^\]】]*[\]】]/g, '').trim();
  164. }
  165. // 解析 kbcontent 内的拼课块 → [[课程名, 教师, 教室, 周次原文], ...]
  166. // 拼课以 5 个以上连字符分隔,分隔符落在 <br> 之后的文本节点里,遇分隔符结算当前段
  167. function parseKbContent(div) {
  168. const parts = [];
  169. let buf = '';
  170. let fonts = [];
  171. for (const node of div.childNodes) {
  172. if (node.nodeType === 3) {
  173. const chunks = node.textContent.split(/-{5,}/);
  174. for (let i = 0; i < chunks.length; i++) {
  175. if (i > 0) { parts.push({ text: buf, fonts }); buf = ''; fonts = []; }
  176. buf += chunks[i];
  177. }
  178. } else if (node.tagName === 'BR') {
  179. buf += '\n';
  180. } else if (node.tagName === 'FONT') {
  181. fonts.push({
  182. title: node.getAttribute('title') || '',
  183. text: node.textContent.trim()
  184. });
  185. buf += node.textContent;
  186. } else {
  187. buf += node.textContent;
  188. }
  189. }
  190. parts.push({ text: buf, fonts });
  191. const out = [];
  192. for (const part of parts) {
  193. // 课程名 = 首个换行之前的非空文本行。
  194. // 拼课第 2 段起以 <br> 开头,首个换行之前是空的,要往后找
  195. let name = '';
  196. for (const line of part.text.split('\n')) {
  197. const t = line.replace(/\s+/g, ' ').trim();
  198. if (t.length >= 2) { name = t; break; }
  199. }
  200. if (!name) continue;
  201. const pick = (titles) => {
  202. for (const t of titles) {
  203. const hit = part.fonts.find(f => f.title === t);
  204. if (hit) return hit.text;
  205. }
  206. return '';
  207. };
  208. const teacher = cleanTeacher(pick(['老师', '教师']));
  209. const position = pick(['教室', '上课地点']);
  210. let weeks = pick(['周次(节次)', '周次', '节次']);
  211. const sd = pick(['单双周']);
  212. // 部分页面的单双周是独立字段,套上括号并入周次串以命中 parseWeeks 的括号匹配
  213. if (weeks && /单|双/.test(sd)) weeks += '(' + sd + ')';
  214. out.push([name, teacher, position, weeks]);
  215. }
  216. return out;
  217. }
  218. // 主解析:课表页 → 合并后的课程数组,接受 Document 或 HTML 字符串
  219. function parseSchedule(input) {
  220. const doc = (input && input.nodeType === 9) ? input : parseDoc(input);
  221. const table = findCourseTable(doc);
  222. if (!table) return [];
  223. const colToDay = {};
  224. const raw = [];
  225. for (const row of table.querySelectorAll('tr')) {
  226. const ths = Array.from(row.querySelectorAll('th'));
  227. const tds = Array.from(row.querySelectorAll('td'));
  228. if (ths.some(th => th.textContent.indexOf('星期') >= 0)) {
  229. ths.forEach((th, ci) => {
  230. if (ci === 0) return; // 第 0 列是节次标签列
  231. const cname = th.textContent;
  232. for (const k in WEEKDAY_MAP) {
  233. if (cname.indexOf(k) >= 0) {
  234. colToDay[ci - 1] = WEEKDAY_MAP[k]; // td 索引从 0 起
  235. break;
  236. }
  237. }
  238. });
  239. continue;
  240. }
  241. const section = ths.length ? parseSections(ths[0].textContent) : null;
  242. if (!section) continue;
  243. tds.forEach((td, ci) => {
  244. const day = colToDay[ci];
  245. if (day === undefined) return;
  246. // 必须精确取 class="kbcontent":隐藏的 kbcontent1 带着同样完整的
  247. // 拼课数据,用模糊选择器会把每门课翻倍
  248. const div = td.querySelector('div.kbcontent');
  249. if (!div) return;
  250. // 同格拼课共用本格节次范围、靠周次区分先后,绝不能拆成不同节次
  251. for (const [name, teacher, position, weeksTxt] of parseKbContent(div)) {
  252. const weeks = parseWeeks(weeksTxt);
  253. if (weeks.length === 0) continue;
  254. raw.push({
  255. name, teacher, position,
  256. day, startSection: section[0], endSection: section[1],
  257. weeksRaw: weeksTxt, weeks
  258. });
  259. }
  260. });
  261. }
  262. return mergeCourses(raw);
  263. }
  264. // 阶段 1 合并连排课(周次须相同,否则分阶段排课会被错并),阶段 2 合并同节次的周次
  265. function mergeCourses(courses) {
  266. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  267. const sameKey = (a, b) =>
  268. a.name === b.name && a.teacher === b.teacher &&
  269. a.position === b.position && a.day === b.day;
  270. const weeksKey = c => (Array.isArray(c.weeks) ? c.weeks.join(',') : '');
  271. const byCourseBase = (a, b) =>
  272. (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) ||
  273. (a.teacher < b.teacher ? -1 : a.teacher > b.teacher ? 1 : 0) ||
  274. (a.position < b.position ? -1 : a.position > b.position ? 1 : 0) ||
  275. (a.day || 0) - (b.day || 0);
  276. const bySection = (a, b) =>
  277. byCourseBase(a, b) ||
  278. (a.startSection || 0) - (b.startSection || 0) ||
  279. (a.endSection || 0) - (b.endSection || 0);
  280. const list = courses.map(c => ({
  281. ...c,
  282. name: c.name || '',
  283. teacher: c.teacher || '',
  284. position: c.position || '',
  285. weeks: Array.isArray(c.weeks) ? c.weeks.slice().sort((a, b) => a - b) : []
  286. }));
  287. // 阶段 1 必须先按周次分组,再按节次排序,防止同节次不同周次的拼课插在连排课中间
  288. list.sort((a, b) =>
  289. byCourseBase(a, b) ||
  290. weeksKey(a).localeCompare(weeksKey(b)) ||
  291. (a.startSection || 0) - (b.startSection || 0) ||
  292. (a.endSection || 0) - (b.endSection || 0)
  293. );
  294. const step1 = [];
  295. let cur = list[0];
  296. for (let i = 1; i < list.length; i++) {
  297. const next = list[i];
  298. const isSameCourse = sameKey(cur, next) && weeksKey(cur) === weeksKey(next);
  299. if (isSameCourse && next.startSection === cur.endSection + 1) {
  300. cur.endSection = next.endSection;
  301. } else if (isSameCourse && next.startSection === cur.startSection &&
  302. next.endSection === cur.endSection) {
  303. continue;
  304. } else {
  305. step1.push(cur);
  306. cur = next;
  307. }
  308. }
  309. step1.push(cur);
  310. step1.sort(bySection);
  311. const out = [];
  312. cur = step1[0];
  313. for (let i = 1; i < step1.length; i++) {
  314. const next = step1[i];
  315. if (sameKey(cur, next) &&
  316. cur.startSection === next.startSection && cur.endSection === next.endSection) {
  317. cur.weeks = Array.from(new Set(cur.weeks.concat(next.weeks))).sort((a, b) => a - b);
  318. } else {
  319. out.push(cur);
  320. cur = next;
  321. }
  322. }
  323. out.push(cur);
  324. return out;
  325. }
  326. async function saveAppConfig(semesterStartDate, totalWeeks, firstDayOfWeek) {
  327. // 周起始随学期而定:周日列有日期为 7,否则为 1(见 fetchSemesterInfo)
  328. const config = {
  329. "semesterStartDate": semesterStartDate,
  330. "semesterTotalWeeks": totalWeeks || 20,
  331. "firstDayOfWeek": firstDayOfWeek
  332. };
  333. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  334. }
  335. async function saveAppTimeSlots() {
  336. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(TIME_SLOTS));
  337. }
  338. async function saveImportedCourses(courses) {
  339. return await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses.map(c => ({
  340. name: c.name,
  341. teacher: c.teacher,
  342. position: c.position,
  343. day: c.day,
  344. startSection: c.startSection,
  345. endSection: c.endSection,
  346. weeks: c.weeks
  347. }))));
  348. }
  349. async function runImportFlow() {
  350. try {
  351. // 停在统一认证页时教务接口会 404,提前拦下
  352. const host = (/^[a-z][a-z0-9+.-]*:\/\/([^/?#]+)/i.exec(String(location.href || '')) || [])[1] || '';
  353. if (!host.toLowerCase().endsWith('.its.csu.edu.cn')) {
  354. window.shiguangBridge.showToast("导入失败:请先登录教务系统");
  355. return;
  356. }
  357. // 1. 用户确认
  358. const confirmed = await window.shiguangBridgePromise.showAlert(
  359. "导入前确认",
  360. "将从教务系统读取课表,导入可在任意教务页面进行。\n\n现在继续?",
  361. "开始导入");
  362. if (!confirmed) return;
  363. // 2. 获取学期列表
  364. window.shiguangBridge.showToast("正在获取学期列表…");
  365. const { list: semesters, defaultIndex } = await fetchSemesterList();
  366. if (semesters.length === 0) {
  367. window.shiguangBridge.showToast("导入失败:未获取到学期列表");
  368. return;
  369. }
  370. // 3. 用户选择学期
  371. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  372. "选择学期", JSON.stringify(semesters.map(s => s.label)), defaultIndex);
  373. if (selectedIndex === null || selectedIndex === undefined || selectedIndex < 0) return;
  374. const semesterId = semesters[selectedIndex].value;
  375. // 4. 获取开学日期 + 总周次
  376. window.shiguangBridge.showToast("正在获取学期信息…");
  377. const { startDate, totalWeeks, firstDayOfWeek } = await fetchSemesterInfo(semesterId);
  378. // 5. 读不到开学日期直接退出,不猜也不让用户手填
  379. if (!startDate) {
  380. window.shiguangBridge.showToast("导入失败:未读到开学日期");
  381. return;
  382. }
  383. // 6. 获取课程
  384. window.shiguangBridge.showToast("正在请求课程数据…");
  385. const courses = await fetchCourses(semesterId);
  386. if (courses.length === 0) {
  387. window.shiguangBridge.showToast("导入失败:该学期没有课程");
  388. return;
  389. }
  390. // 7. 保存配置
  391. await saveAppConfig(startDate, totalWeeks, firstDayOfWeek);
  392. await saveAppTimeSlots();
  393. await saveImportedCourses(courses);
  394. // 8. 完成:三个 save 已各自提示过结果,这里只做收尾跳转
  395. window.shiguangBridge.notifyTaskCompletion();
  396. } catch (err) {
  397. // App 侧 reject 的文案多数已带「失败」,避免出现「导入失败:课程导入失败: …」
  398. const msg = String((err && err.message) ? err.message : err);
  399. window.shiguangBridge.showToast(msg.includes("失败") ? msg : "导入失败:" + msg);
  400. }
  401. }
  402. // Node 下供测试取用;浏览器里没有 module,此段自动跳过
  403. if (typeof module !== 'undefined' && module.exports) {
  404. module.exports = {
  405. parseSchedule, parseDoc, parseWeeks, parseSections, parseKbContent,
  406. mergeCourses, cleanTeacher, fetchSemesterList, fetchSemesterInfo, fetchCourses
  407. };
  408. }
  409. // 挂出口供离线测试直接驱动流程
  410. if (typeof window !== 'undefined') {
  411. window.runImportFlow = runImportFlow;
  412. }
  413. // 入口:WebView 中桥接就绪即执行
  414. if (typeof window !== 'undefined' && window.shiguangBridgePromise) {
  415. runImportFlow();
  416. }
  417. })();