xzhmu_01.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // 徐州医科大学-研究生(xzhmu.edu.cn) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请提联系开发者或者提交pr更改,这更加快速
  4. const DAY_MAP = {
  5. 'Monday': 1,
  6. 'Tuesday': 2,
  7. 'Wednesday': 3,
  8. 'Thursday': 4,
  9. 'Friday': 5,
  10. 'Saturday': 6,
  11. 'Sunday': 7
  12. };
  13. /** 预设作息时间 */
  14. const PRESET_TIME_SLOTS = [
  15. { number: 1, startTime: "08:00", endTime: "08:40" },
  16. { number: 2, startTime: "08:50", endTime: "09:30" },
  17. { number: 3, startTime: "09:40", endTime: "10:20" },
  18. { number: 4, startTime: "10:30", endTime: "11:10" },
  19. { number: 5, startTime: "11:20", endTime: "12:00" },
  20. { number: 6, startTime: "14:00", endTime: "14:40" },
  21. { number: 7, startTime: "14:50", endTime: "15:30" },
  22. { number: 8, startTime: "15:40", endTime: "16:20" },
  23. { number: 9, startTime: "16:30", endTime: "17:10" },
  24. { number: 10, startTime: "17:20", endTime: "18:00" },
  25. { number: 11, startTime: "19:00", endTime: "19:40" },
  26. { number: 12, startTime: "19:50", endTime: "20:30" },
  27. { number: 13, startTime: "20:40", endTime: "21:20" }
  28. ];
  29. /** 课表配置 */
  30. const COURSE_CONFIG = {
  31. defaultClassDuration: 40,
  32. defaultBreakDuration: 10
  33. };
  34. /** 节次文本 -> 数字,提取末尾数字 */
  35. function sectionTextToNumber(text) {
  36. const m = text.match(/(\d+)\s*$/);
  37. return m ? parseInt(m[1], 10) : undefined;
  38. }
  39. /** 解析周次字符串,支持 "5-5周"、"1,3,5周"、"1-5(单)"、"第1-5周" 等 */
  40. function parseWeeks(weekStr) {
  41. if (!weekStr) return [];
  42. const weeks = new Set();
  43. const cleaned = String(weekStr)
  44. .replace(/[周第]/g, '')
  45. .replace(/[,、;]/g, ',')
  46. .replace(/[(]/g, '(')
  47. .replace(/[)]/g, ')')
  48. .trim();
  49. const segRegex = /(\d+)(?:\s*-\s*(\d+))?\s*(?:\(?\s*([单双])\s*\)?)?/g;
  50. let match;
  51. while ((match = segRegex.exec(cleaned)) !== null) {
  52. const start = parseInt(match[1], 10);
  53. const end = match[2] ? parseInt(match[2], 10) : start;
  54. const flag = match[3] || '';
  55. for (let w = start; w <= end; w++) {
  56. if (flag === '单' && w % 2 === 0) continue;
  57. if (flag === '双' && w % 2 !== 0) continue;
  58. weeks.add(w);
  59. }
  60. }
  61. return Array.from(weeks).sort((a, b) => a - b);
  62. }
  63. /** 穿透 iframe 查找包含课表的 document */
  64. function getTargetDocument() {
  65. if (document.querySelector('table#kb.curriculum')) return document;
  66. const iframes = document.querySelectorAll('iframe');
  67. for (const iframe of iframes) {
  68. try {
  69. const doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  70. if (doc && doc.querySelector('table#kb.curriculum')) {
  71. console.log(`JS: 在 iframe#${iframe.id || '(匿名)'} 中找到课表`);
  72. return doc;
  73. }
  74. } catch (e) {
  75. console.warn('JS: 无法访问 iframe', iframe.id, e.message);
  76. }
  77. }
  78. return null;
  79. }
  80. /** 提取两个 span 之间的裸文本(用于教师名) */
  81. function extractTeacherBetweenSpans(root, afterSpanIndex, beforeSpanIndex) {
  82. const spans = root.querySelectorAll('span');
  83. if (spans.length <= afterSpanIndex || spans.length <= beforeSpanIndex) return '';
  84. const afterSpan = spans[afterSpanIndex];
  85. const beforeSpan = spans[beforeSpanIndex];
  86. let collecting = false;
  87. let text = '';
  88. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
  89. let node;
  90. while ((node = walker.nextNode())) {
  91. if (node === afterSpan) { collecting = true; continue; }
  92. if (node === beforeSpan) { collecting = false; break; }
  93. if (collecting) text += node.textContent;
  94. }
  95. return text.trim();
  96. }
  97. /** 解析单个 C_kc_subject div,可能包含多门课 */
  98. function parseSubjectDiv(div, day, startSection, endSection) {
  99. const courses = [];
  100. const ps = div.querySelectorAll('p');
  101. ps.forEach(p => {
  102. const html = p.innerHTML.replace(/<br\s*\/?>/gi, '\n');
  103. const blocks = html.split(/\n\s*\n/);
  104. blocks.forEach(block => {
  105. const trimmed = block.trim();
  106. if (!trimmed) return;
  107. const tmp = document.createElement('div');
  108. tmp.innerHTML = trimmed;
  109. const spans = Array.from(tmp.querySelectorAll('span'))
  110. .map(s => s.textContent.trim())
  111. .filter(Boolean);
  112. if (spans.length < 3) return;
  113. const name = spans[0];
  114. const weeksStr = spans[1];
  115. const position = spans[2];
  116. const teacher = extractTeacherBetweenSpans(tmp, 1, 2);
  117. const weeks = parseWeeks(weeksStr);
  118. if (!name || !position || weeks.length === 0) return;
  119. courses.push({
  120. name,
  121. teacher: teacher || '',
  122. position,
  123. day,
  124. startSection,
  125. endSection,
  126. weeks
  127. });
  128. });
  129. });
  130. return courses;
  131. }
  132. /** 解析 table#kb.curriculum */
  133. function parseCurriculumTable() {
  134. const doc = getTargetDocument();
  135. if (!doc) {
  136. console.error('JS: 未在任何文档中找到课表 table#kb.curriculum');
  137. return [];
  138. }
  139. const table = doc.querySelector('table#kb.curriculum');
  140. if (!table) return [];
  141. const allCourses = [];
  142. const rows = Array.from(table.querySelectorAll('tbody tr'));
  143. const coveredCells = new Set();
  144. rows.forEach((tr, rowIndex) => {
  145. const tds = Array.from(tr.querySelectorAll('td'));
  146. if (tds.length === 0) return;
  147. const sectionText = tds[0].textContent.trim();
  148. const currentSection = sectionTextToNumber(sectionText);
  149. if (currentSection === undefined) return;
  150. for (let colIndex = 1; colIndex < tds.length; colIndex++) {
  151. const td = tds[colIndex];
  152. const key = `${rowIndex}-${colIndex}`;
  153. if (coveredCells.has(key)) continue;
  154. const style = td.getAttribute('style') || '';
  155. if (style.includes('display: none')) continue;
  156. const dayAttr = td.getAttribute('w');
  157. const day = DAY_MAP[dayAttr];
  158. if (!day) continue;
  159. const div = td.querySelector('.C_kc_subject');
  160. if (!div) continue;
  161. const rowspan = parseInt(td.getAttribute('rowspan') || '1', 10);
  162. const startSection = currentSection;
  163. const endSection = currentSection + rowspan - 1;
  164. for (let r = 1; r < rowspan; r++) {
  165. coveredCells.add(`${rowIndex + r}-${colIndex}`);
  166. }
  167. const courses = parseSubjectDiv(div, day, startSection, endSection);
  168. allCourses.push(...courses);
  169. }
  170. });
  171. return allCourses;
  172. }
  173. /** 抓取并解析课程数据 */
  174. async function scrapeAndParseCourses() {
  175. window.shiguangBridge.showToast("正在检查页面并抓取课程数据...");
  176. try {
  177. const doc = getTargetDocument();
  178. if (!doc) {
  179. await window.shiguangBridgePromise.showAlert(
  180. "导入失败",
  181. "未找到课表表格 (table#kb.curriculum)。\n请确认:\n1. 已登录教务系统\n2. 已进入课表查询页面\n3. 已点击查询且课表已加载",
  182. "确定"
  183. );
  184. return null;
  185. }
  186. const courses = parseCurriculumTable();
  187. if (courses.length === 0) {
  188. window.shiguangBridge.showToast("未解析到任何课程,请检查课表是否加载完成。");
  189. return null;
  190. }
  191. console.log(`JS: 课程解析成功,共 ${courses.length} 条原始记录。`);
  192. return { courses };
  193. } catch (error) {
  194. console.error('JS: 抓取/解析失败:', error);
  195. window.shiguangBridge.showToast(`解析失败: ${error.message}`);
  196. await window.shiguangBridgePromise.showAlert(
  197. "解析失败",
  198. `发生错误:${error.message}\n请重试或联系开发者。`,
  199. "确定"
  200. );
  201. return null;
  202. }
  203. }
  204. /** 合并去重课程(参考《课程合并与去重函数》) */
  205. function mergeAndDistinctCourses(courses) {
  206. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  207. const list = courses.map(c => ({
  208. ...c,
  209. name: c.name || '',
  210. teacher: c.teacher || '',
  211. position: c.position || '',
  212. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  213. }));
  214. list.sort((a, b) =>
  215. a.name.localeCompare(b.name) ||
  216. a.teacher.localeCompare(b.teacher) ||
  217. a.position.localeCompare(b.position) ||
  218. (a.day || 0) - (b.day || 0) ||
  219. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  220. (a.startSection || 0) - (b.startSection || 0)
  221. );
  222. const step1Merged = [];
  223. let current = list[0];
  224. for (let i = 1; i < list.length; i++) {
  225. const next = list[i];
  226. const sameCourseAndWeeks =
  227. current.name === next.name &&
  228. current.teacher === next.teacher &&
  229. current.position === next.position &&
  230. current.day === next.day &&
  231. current.weeks.join(',') === next.weeks.join(',');
  232. const isContinuous = current.endSection + 1 === next.startSection;
  233. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  234. if (sameCourseAndWeeks && isContinuous) {
  235. current.endSection = next.endSection;
  236. } else if (sameCourseAndWeeks && isDuplicate) {
  237. continue;
  238. } else {
  239. step1Merged.push(current);
  240. current = next;
  241. }
  242. }
  243. step1Merged.push(current);
  244. step1Merged.sort((a, b) =>
  245. a.name.localeCompare(b.name) ||
  246. a.teacher.localeCompare(b.teacher) ||
  247. a.position.localeCompare(b.position) ||
  248. (a.day || 0) - (b.day || 0) ||
  249. (a.startSection || 0) - (b.startSection || 0) ||
  250. (a.endSection || 0) - (b.endSection || 0)
  251. );
  252. const step2Merged = [];
  253. let cur = step1Merged[0];
  254. for (let i = 1; i < step1Merged.length; i++) {
  255. const nxt = step1Merged[i];
  256. const sameCourseAndSection =
  257. cur.name === nxt.name &&
  258. cur.teacher === nxt.teacher &&
  259. cur.position === nxt.position &&
  260. cur.day === nxt.day &&
  261. cur.startSection === nxt.startSection &&
  262. cur.endSection === nxt.endSection;
  263. if (sameCourseAndSection) {
  264. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  265. } else {
  266. step2Merged.push(cur);
  267. cur = nxt;
  268. }
  269. }
  270. step2Merged.push(cur);
  271. return step2Merged;
  272. }
  273. /** 保存课程 */
  274. async function saveCourses(parsedCourses) {
  275. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  276. try {
  277. await window.shiguangBridgePromise.saveImportedCourses(
  278. JSON.stringify(parsedCourses)
  279. );
  280. console.log("JS: 课程保存成功!");
  281. return true;
  282. } catch (error) {
  283. console.error('JS: 课程保存失败:', error);
  284. window.shiguangBridge.showToast(`保存失败: ${error.message}`);
  285. return false;
  286. }
  287. }
  288. /** 保存课表配置 */
  289. async function saveCourseConfig() {
  290. window.shiguangBridge.showToast("正在导入课表配置...");
  291. try {
  292. await window.shiguangBridgePromise.saveCourseConfig(
  293. JSON.stringify(COURSE_CONFIG)
  294. );
  295. console.log("JS: 课表配置保存成功!");
  296. return true;
  297. } catch (error) {
  298. console.error('JS: 课表配置保存失败:', error);
  299. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  300. return false;
  301. }
  302. }
  303. /** 保存预设作息时间 */
  304. async function savePresetTimeSlots() {
  305. window.shiguangBridge.showToast(`正在导入 ${PRESET_TIME_SLOTS.length} 节作息时间...`);
  306. try {
  307. await window.shiguangBridgePromise.savePresetTimeSlots(
  308. JSON.stringify(PRESET_TIME_SLOTS)
  309. );
  310. console.log("JS: 作息时间保存成功!");
  311. return true;
  312. } catch (error) {
  313. console.error('JS: 作息时间保存失败:', error);
  314. window.shiguangBridge.showToast(`作息时间保存失败: ${error.message}`);
  315. return false;
  316. }
  317. }
  318. /** 流程编排 */
  319. async function runImportFlow() {
  320. const alertConfirmed = await window.shiguangBridgePromise.showAlert(
  321. "教务系统课表导入",
  322. "导入前请确保:\n1. 已成功登录教务系统\n2. 已进入课表查询页面\n3. 已选择学年学期并点击【查询】\n4. 页面上已显示课程表",
  323. "好的,开始导入"
  324. );
  325. if (!alertConfirmed) {
  326. window.shiguangBridge.showToast("用户取消了导入。");
  327. return;
  328. }
  329. const result = await scrapeAndParseCourses();
  330. if (result === null) {
  331. console.log("JS: 课程获取或解析失败,流程终止。");
  332. return;
  333. }
  334. const merged = mergeAndDistinctCourses(result.courses);
  335. console.log(`JS: 合并去重后剩余 ${merged.length} 条记录。`);
  336. const saveResult = await saveCourses(merged);
  337. if (!saveResult) {
  338. console.log("JS: 课程保存失败,流程终止。");
  339. return;
  340. }
  341. // 配置类导入失败不阻断流程
  342. await saveCourseConfig();
  343. await savePresetTimeSlots();
  344. window.shiguangBridge.showToast(`课程导入成功,共 ${merged.length} 条记录!`);
  345. console.log("JS: 整个导入流程执行完毕并成功。");
  346. window.shiguangBridge.notifyTaskCompletion();
  347. }
  348. runImportFlow();