xzhmu_01.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. const parent = node.parentNode;
  92. if (parent === afterSpan) { collecting = true; continue; }
  93. if (parent === beforeSpan) { collecting = false; break; }
  94. if (collecting) text += node.textContent;
  95. }
  96. return text.trim();
  97. }
  98. /** 解析单个 C_kc_subject / C_kc_today_subject div,可能包含多门课 */
  99. function parseSubjectDiv(div, day, startSection, endSection) {
  100. const courses = [];
  101. const ps = div.querySelectorAll('p');
  102. ps.forEach(p => {
  103. const html = p.innerHTML.replace(/<br\s*\/?>/gi, '\n');
  104. const blocks = html.split(/\n\s*\n/);
  105. blocks.forEach(block => {
  106. const trimmed = block.trim();
  107. if (!trimmed) return;
  108. const tmp = document.createElement('div');
  109. tmp.innerHTML = trimmed;
  110. const spans = Array.from(tmp.querySelectorAll('span'))
  111. .map(s => s.textContent.trim())
  112. .filter(Boolean);
  113. if (spans.length < 3) return;
  114. const name = spans[0];
  115. const weeksStr = spans[1];
  116. const position = spans[2];
  117. const teacher = extractTeacherBetweenSpans(tmp, 1, 2);
  118. const weeks = parseWeeks(weeksStr);
  119. if (!name || !position || weeks.length === 0) return;
  120. courses.push({
  121. name,
  122. teacher: teacher || '',
  123. position,
  124. day,
  125. startSection,
  126. endSection,
  127. weeks
  128. });
  129. });
  130. });
  131. return courses;
  132. }
  133. /** 解析 table#kb.curriculum */
  134. function parseCurriculumTable() {
  135. const doc = getTargetDocument();
  136. if (!doc) {
  137. console.error('JS: 未在任何文档中找到课表 table#kb.curriculum');
  138. return [];
  139. }
  140. const table = doc.querySelector('table#kb.curriculum');
  141. if (!table) return [];
  142. const allCourses = [];
  143. const rows = Array.from(table.querySelectorAll('tbody tr'));
  144. const coveredCells = new Set();
  145. rows.forEach((tr, rowIndex) => {
  146. const tds = Array.from(tr.querySelectorAll('td'));
  147. if (tds.length === 0) return;
  148. const sectionText = tds[0].textContent.trim();
  149. const currentSection = sectionTextToNumber(sectionText);
  150. if (currentSection === undefined) return;
  151. for (let colIndex = 1; colIndex < tds.length; colIndex++) {
  152. const td = tds[colIndex];
  153. const key = `${rowIndex}-${colIndex}`;
  154. // 先判断是否被上方 rowspan 覆盖,避免重复解析
  155. if (coveredCells.has(key)) continue;
  156. const style = td.getAttribute('style') || '';
  157. if (style.includes('display: none')) continue;
  158. const dayAttr = td.getAttribute('w');
  159. const day = DAY_MAP[dayAttr];
  160. if (!day) continue;
  161. // 兼容普通课程与“今天”课程
  162. const div = td.querySelector('.C_kc_subject, .C_kc_today_subject');
  163. if (!div) continue;
  164. const rowspan = parseInt(td.getAttribute('rowspan') || '1', 10);
  165. const startSection = currentSection;
  166. const endSection = currentSection + rowspan - 1;
  167. for (let r = 1; r < rowspan; r++) {
  168. coveredCells.add(`${rowIndex + r}-${colIndex}`);
  169. }
  170. const courses = parseSubjectDiv(div, day, startSection, endSection);
  171. allCourses.push(...courses);
  172. }
  173. });
  174. return allCourses;
  175. }
  176. /** 抓取并解析课程数据 */
  177. async function scrapeAndParseCourses() {
  178. window.shiguangBridge.showToast("正在检查页面并抓取课程数据...");
  179. try {
  180. const doc = getTargetDocument();
  181. if (!doc) {
  182. await window.shiguangBridgePromise.showAlert(
  183. "导入失败",
  184. "未找到课表表格 (table#kb.curriculum)。\n请确认:\n1. 已登录教务系统\n2. 已进入课表查询页面\n3. 已点击查询且课表已加载",
  185. "确定"
  186. );
  187. return null;
  188. }
  189. const courses = parseCurriculumTable();
  190. if (courses.length === 0) {
  191. window.shiguangBridge.showToast("未解析到任何课程,请检查课表是否加载完成。");
  192. return null;
  193. }
  194. console.log(`JS: 课程解析成功,共 ${courses.length} 条原始记录。`);
  195. return { courses };
  196. } catch (error) {
  197. console.error('JS: 抓取/解析失败:', error);
  198. window.shiguangBridge.showToast(`解析失败: ${error.message}`);
  199. await window.shiguangBridgePromise.showAlert(
  200. "解析失败",
  201. `发生错误:${error.message}\n请重试或联系开发者。`,
  202. "确定"
  203. );
  204. return null;
  205. }
  206. }
  207. /** 合并去重课程(参考《课程合并与去重函数》) */
  208. function mergeAndDistinctCourses(courses) {
  209. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  210. const list = courses.map(c => ({
  211. ...c,
  212. name: c.name || '',
  213. teacher: c.teacher || '',
  214. position: c.position || '',
  215. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  216. }));
  217. list.sort((a, b) =>
  218. a.name.localeCompare(b.name) ||
  219. a.teacher.localeCompare(b.teacher) ||
  220. a.position.localeCompare(b.position) ||
  221. (a.day || 0) - (b.day || 0) ||
  222. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  223. (a.startSection || 0) - (b.startSection || 0)
  224. );
  225. const step1Merged = [];
  226. let current = list[0];
  227. for (let i = 1; i < list.length; i++) {
  228. const next = list[i];
  229. const sameCourseAndWeeks =
  230. current.name === next.name &&
  231. current.teacher === next.teacher &&
  232. current.position === next.position &&
  233. current.day === next.day &&
  234. current.weeks.join(',') === next.weeks.join(',');
  235. const isContinuous = current.endSection + 1 === next.startSection;
  236. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  237. if (sameCourseAndWeeks && isContinuous) {
  238. current.endSection = next.endSection;
  239. } else if (sameCourseAndWeeks && isDuplicate) {
  240. continue;
  241. } else {
  242. step1Merged.push(current);
  243. current = next;
  244. }
  245. }
  246. step1Merged.push(current);
  247. step1Merged.sort((a, b) =>
  248. a.name.localeCompare(b.name) ||
  249. a.teacher.localeCompare(b.teacher) ||
  250. a.position.localeCompare(b.position) ||
  251. (a.day || 0) - (b.day || 0) ||
  252. (a.startSection || 0) - (b.startSection || 0) ||
  253. (a.endSection || 0) - (b.endSection || 0)
  254. );
  255. const step2Merged = [];
  256. let cur = step1Merged[0];
  257. for (let i = 1; i < step1Merged.length; i++) {
  258. const nxt = step1Merged[i];
  259. const sameCourseAndSection =
  260. cur.name === nxt.name &&
  261. cur.teacher === nxt.teacher &&
  262. cur.position === nxt.position &&
  263. cur.day === nxt.day &&
  264. cur.startSection === nxt.startSection &&
  265. cur.endSection === nxt.endSection;
  266. if (sameCourseAndSection) {
  267. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  268. } else {
  269. step2Merged.push(cur);
  270. cur = nxt;
  271. }
  272. }
  273. step2Merged.push(cur);
  274. return step2Merged;
  275. }
  276. /** 保存课程 */
  277. async function saveCourses(parsedCourses) {
  278. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  279. try {
  280. await window.shiguangBridgePromise.saveImportedCourses(
  281. JSON.stringify(parsedCourses)
  282. );
  283. console.log("JS: 课程保存成功!");
  284. return true;
  285. } catch (error) {
  286. console.error('JS: 课程保存失败:', error);
  287. window.shiguangBridge.showToast(`保存失败: ${error.message}`);
  288. return false;
  289. }
  290. }
  291. /** 保存课表配置 */
  292. async function saveCourseConfig() {
  293. window.shiguangBridge.showToast("正在导入课表配置...");
  294. try {
  295. await window.shiguangBridgePromise.saveCourseConfig(
  296. JSON.stringify(COURSE_CONFIG)
  297. );
  298. console.log("JS: 课表配置保存成功!");
  299. return true;
  300. } catch (error) {
  301. console.error('JS: 课表配置保存失败:', error);
  302. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  303. return false;
  304. }
  305. }
  306. /** 保存预设作息时间 */
  307. async function savePresetTimeSlots() {
  308. window.shiguangBridge.showToast(`正在导入 ${PRESET_TIME_SLOTS.length} 节作息时间...`);
  309. try {
  310. await window.shiguangBridgePromise.savePresetTimeSlots(
  311. JSON.stringify(PRESET_TIME_SLOTS)
  312. );
  313. console.log("JS: 作息时间保存成功!");
  314. return true;
  315. } catch (error) {
  316. console.error('JS: 作息时间保存失败:', error);
  317. window.shiguangBridge.showToast(`作息时间保存失败: ${error.message}`);
  318. return false;
  319. }
  320. }
  321. /** 流程编排 */
  322. async function runImportFlow() {
  323. const alertConfirmed = await window.shiguangBridgePromise.showAlert(
  324. "教务系统课表导入",
  325. "导入前请确保:\n1. 已成功登录教务系统\n2. 已进入课表查询页面\n3. 已选择学年学期并点击【查询】\n4. 页面上已显示课程表",
  326. "好的,开始导入"
  327. );
  328. if (!alertConfirmed) {
  329. window.shiguangBridge.showToast("用户取消了导入。");
  330. return;
  331. }
  332. const result = await scrapeAndParseCourses();
  333. if (result === null) {
  334. console.log("JS: 课程获取或解析失败,流程终止。");
  335. return;
  336. }
  337. const merged = mergeAndDistinctCourses(result.courses);
  338. console.log(`JS: 合并去重后剩余 ${merged.length} 条记录。`);
  339. const saveResult = await saveCourses(merged);
  340. if (!saveResult) {
  341. console.log("JS: 课程保存失败,流程终止。");
  342. return;
  343. }
  344. // 配置类导入失败不阻断流程
  345. await saveCourseConfig();
  346. await savePresetTimeSlots();
  347. window.shiguangBridge.showToast(`课程导入成功,共 ${merged.length} 条记录!`);
  348. console.log("JS: 整个导入流程执行完毕并成功。");
  349. window.shiguangBridge.notifyTaskCompletion();
  350. }
  351. runImportFlow();