hnu_01.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. // 湖南大学(hnu.edu.cn) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请联系开发者或者提交pr更改,这更加快速
  4. const BASE_URL = "https://hdjw.hnu.edu.cn";
  5. const URL_SEMESTER = `${BASE_URL}/jsxsd/jxzl/jxzl_query`; // 教学周历(学期列表 + 开学日期 + 最大周次)
  6. const URL_COURSE = `${BASE_URL}/jsxsd/xskb/xskb_list.do`; // 课表查询
  7. // 工具函数
  8. function parseWeeks(weekStr) {
  9. const weeks = [];
  10. if (!weekStr) return weeks;
  11. const pureWeekData = String(weekStr).split('(')[0];
  12. pureWeekData.split(/[,,]/).forEach(seg => {
  13. seg = seg.trim();
  14. if (!seg) return;
  15. if (seg.includes('-')) {
  16. const [s, e] = seg.split('-').map(Number);
  17. if (!isNaN(s) && !isNaN(e)) {
  18. for (let i = Math.min(s, e); i <= Math.max(s, e); i++) {
  19. if (i > 0) weeks.push(i);
  20. }
  21. }
  22. } else {
  23. const w = parseInt(seg, 10);
  24. if (!isNaN(w) && w > 0) weeks.push(w);
  25. }
  26. });
  27. return [...new Set(weeks)].sort((a, b) => a - b);
  28. }
  29. /**
  30. * 节次与周次合并去重函数
  31. * @param {Array<Object>} courses 原始解析课程数组
  32. * @returns {Array<Object>} 合并去重后的课程数组
  33. */
  34. function mergeAndDistinctCourses(courses) {
  35. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  36. const list = courses.map(c => ({
  37. ...c,
  38. name: c.name || '',
  39. teacher: c.teacher || '',
  40. position: c.position || '',
  41. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  42. }));
  43. // 阶段 1:合并连续节次与完全重复记录
  44. list.sort((a, b) => {
  45. return a.name.localeCompare(b.name) ||
  46. a.teacher.localeCompare(b.teacher) ||
  47. a.position.localeCompare(b.position) ||
  48. (a.day || 0) - (b.day || 0) ||
  49. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  50. (a.startSection || 0) - (b.startSection || 0);
  51. });
  52. const step1Merged = [];
  53. let current = list[0];
  54. for (let i = 1; i < list.length; i++) {
  55. const next = list[i];
  56. const isSameCourseAndWeeks =
  57. current.name === next.name &&
  58. current.teacher === next.teacher &&
  59. current.position === next.position &&
  60. current.day === next.day &&
  61. current.weeks.join(',') === next.weeks.join(',');
  62. const isContinuous = current.endSection + 1 === next.startSection;
  63. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  64. if (isSameCourseAndWeeks && isContinuous) {
  65. current.endSection = next.endSection;
  66. } else if (isSameCourseAndWeeks && isDuplicate) {
  67. continue;
  68. } else {
  69. step1Merged.push(current);
  70. current = next;
  71. }
  72. }
  73. step1Merged.push(current);
  74. // 阶段 2:合并同节次的周次
  75. step1Merged.sort((a, b) => {
  76. return a.name.localeCompare(b.name) ||
  77. a.teacher.localeCompare(b.teacher) ||
  78. a.position.localeCompare(b.position) ||
  79. (a.day || 0) - (b.day || 0) ||
  80. (a.startSection || 0) - (b.startSection || 0) ||
  81. (a.endSection || 0) - (b.endSection || 0);
  82. });
  83. const step2Merged = [];
  84. let cur = step1Merged[0];
  85. for (let i = 1; i < step1Merged.length; i++) {
  86. const nxt = step1Merged[i];
  87. const isSameCourseAndSection =
  88. cur.name === nxt.name &&
  89. cur.teacher === nxt.teacher &&
  90. cur.position === nxt.position &&
  91. cur.day === nxt.day &&
  92. cur.startSection === nxt.startSection &&
  93. cur.endSection === nxt.endSection;
  94. if (isSameCourseAndSection) {
  95. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  96. } else {
  97. step2Merged.push(cur);
  98. cur = nxt;
  99. }
  100. }
  101. step2Merged.push(cur);
  102. return step2Merged;
  103. }
  104. // 核心解析逻辑
  105. function parseHeaderDays(table) {
  106. const headerCells = Array.from(
  107. table.querySelectorAll('thead tr th, thead tr td')
  108. );
  109. const headerDayMap = {
  110. '星期日': 7, '星期天': 7,
  111. '星期一': 1,
  112. '星期二': 2,
  113. '星期三': 3,
  114. '星期四': 4,
  115. '星期五': 5,
  116. '星期六': 6
  117. };
  118. const columnDays = [];
  119. headerCells.forEach(cell => {
  120. const text = (cell.textContent || '').trim();
  121. for (const key of Object.keys(headerDayMap)) {
  122. if (text.includes(key)) {
  123. columnDays.push(headerDayMap[key]);
  124. return;
  125. }
  126. }
  127. });
  128. if (columnDays.length === 0) {
  129. columnDays.push(7, 1, 2, 3, 4, 5, 6);
  130. }
  131. return columnDays;
  132. }
  133. /**
  134. * 只读 tooltip 解析课程
  135. * 每个 li.qz-toolitiplists 就是一条完整课程详情
  136. */
  137. function parseCellAtomic(cell, daysForCell) {
  138. const results = [];
  139. const tooltipItems = Array.from(cell.querySelectorAll('.qz-tooltip li.qz-toolitiplists'));
  140. if (tooltipItems.length === 0) return results;
  141. tooltipItems.forEach((tip) => {
  142. // 课程名
  143. const name = tip.querySelector('.qz-tooltipContent-title')?.textContent.trim() || '';
  144. if (!name) return;
  145. const detailItems = Array.from(
  146. tip.querySelectorAll('.qz-tooltipContent-detailitem')
  147. );
  148. const findDetail = (prefix) =>
  149. detailItems.find(d => d.textContent.trim().startsWith(prefix));
  150. // 老师
  151. let teacher = '未知教师';
  152. const teacherDiv = findDetail('老师:') || findDetail('老师:');
  153. if (teacherDiv) {
  154. teacher = teacherDiv.textContent.replace(/老师[::]/, '').trim();
  155. }
  156. // 地点
  157. let position = '未知地点';
  158. const posDiv = findDetail('地点:') || findDetail('地点:');
  159. if (posDiv) {
  160. const p = posDiv.textContent.replace(/地点[::]/, '').trim();
  161. if (p && p !== '()') position = p;
  162. }
  163. // 时间:0-3 周 [1-2节]
  164. let weeks = [];
  165. let startSection = 0;
  166. let endSection = 0;
  167. const timeDiv = findDetail('时间:') || findDetail('时间:');
  168. if (timeDiv) {
  169. const t = timeDiv.textContent.replace(/\s+/g, ' ').trim();
  170. const wm = t.match(/时间[::]\s*([\d,\-]+)\s*周/);
  171. if (wm) weeks = parseWeeks(wm[1]);
  172. const sm = t.match(/\[([\d\-,\s]+?)节\]/);
  173. if (sm && sm[1]) {
  174. const nums = sm[1].split(/[^\d]+/).map(Number).filter(n => !isNaN(n) && n > 0);
  175. if (nums.length > 0) {
  176. startSection = Math.min(...nums);
  177. endSection = Math.max(...nums);
  178. }
  179. }
  180. }
  181. if (!name || startSection <= 0) return;
  182. daysForCell.forEach(day => {
  183. results.push({
  184. name,
  185. teacher,
  186. weeks,
  187. position,
  188. day,
  189. startSection,
  190. endSection
  191. });
  192. });
  193. });
  194. return results;
  195. }
  196. function parseTimetableToModel(doc) {
  197. const table = doc.querySelector('table.qz-weeklyTable');
  198. if (!table) return [];
  199. const results = [];
  200. const columnDays = parseHeaderDays(table);
  201. const bodyRows = Array.from(table.querySelectorAll('tbody tr'));
  202. const occupied = new Array(columnDays.length + 1).fill(0);
  203. bodyRows.forEach(row => {
  204. const allTds = Array.from(row.querySelectorAll('td'));
  205. if (allTds.length === 0) return;
  206. let colCursor = 0;
  207. allTds.forEach(td => {
  208. while (colCursor < occupied.length && occupied[colCursor] > 0) {
  209. occupied[colCursor]--;
  210. colCursor++;
  211. }
  212. if (colCursor >= occupied.length) return;
  213. const isTimeLabel =
  214. td.getAttribute('name') === 'timeTd' ||
  215. td.classList.contains('qz-weeklyTable-label');
  216. const colspan = parseInt(td.getAttribute('colspan') || '1', 10);
  217. const rowspan = parseInt(td.getAttribute('rowspan') || '1', 10);
  218. if (isTimeLabel) {
  219. if (rowspan > 1) {
  220. for (let c = colCursor; c < colCursor + colspan && c < occupied.length; c++) {
  221. occupied[c] = rowspan - 1;
  222. }
  223. }
  224. colCursor += colspan;
  225. return;
  226. }
  227. const dayStart = colCursor - 1;
  228. const daysForCell = [];
  229. for (let c = dayStart; c < dayStart + colspan && c < columnDays.length; c++) {
  230. if (c >= 0) daysForCell.push(columnDays[c]);
  231. }
  232. const cellResults = parseCellAtomic(td, daysForCell);
  233. results.push(...cellResults);
  234. if (rowspan > 1) {
  235. for (let c = colCursor; c < colCursor + colspan && c < occupied.length; c++) {
  236. occupied[c] = rowspan - 1;
  237. }
  238. }
  239. colCursor += colspan;
  240. });
  241. });
  242. return mergeAndDistinctCourses(results);
  243. }
  244. // 网络请求封装
  245. /**
  246. * GET 教学周历页面(用于获取学期列表)
  247. */
  248. async function requestSemesterPage() {
  249. const response = await fetch(URL_SEMESTER, {
  250. method: "GET",
  251. credentials: "include"
  252. });
  253. return await response.text();
  254. }
  255. /**
  256. * POST 教学周历页面(用于获取指定学期的开学日期与最大周次)
  257. * @param {string} semesterId 形如 "2025-2026-2"
  258. */
  259. async function requestSemesterDetailPage(semesterId) {
  260. const response = await fetch(URL_SEMESTER, {
  261. method: "POST",
  262. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  263. body: `xnxq01id=${semesterId}`,
  264. credentials: "include"
  265. });
  266. return await response.text();
  267. }
  268. async function requestCoursePage(semesterId) {
  269. const params = new URLSearchParams({
  270. viweType: "0",
  271. xnxq01id: semesterId
  272. });
  273. const response = await fetch(`${URL_COURSE}?${params.toString()}`, {
  274. method: "GET",
  275. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  276. referrer: `${URL_COURSE}?viweType=0`,
  277. credentials: "include"
  278. });
  279. return await response.text();
  280. }
  281. // 业务逻辑
  282. /**
  283. * 获取学期列表,以 selected 为原点上下各取 3 个
  284. * @returns {Promise<{list: Array<{value:string,label:string}>, defaultIndex:number}>}
  285. */
  286. async function fetchSemesterList() {
  287. const html = await requestSemesterPage();
  288. const doc = new DOMParser().parseFromString(html, "text/html");
  289. const select = doc.getElementById("xnxq01id");
  290. if (!select) return { list: [], defaultIndex: -1 };
  291. const allOptions = Array.from(select.querySelectorAll("option")).map(opt => ({
  292. value: opt.value,
  293. label: opt.textContent.trim(),
  294. selected: opt.hasAttribute("selected")
  295. }));
  296. let selectedIndex = allOptions.findIndex(o => o.selected);
  297. if (selectedIndex === -1) selectedIndex = 0;
  298. const start = Math.max(0, selectedIndex - 3);
  299. const end = Math.min(allOptions.length, selectedIndex + 4);
  300. const list = allOptions.slice(start, end);
  301. const defaultIndex = selectedIndex - start;
  302. return { list, defaultIndex };
  303. }
  304. /**
  305. * 获取指定学期的开学日期 + 最大周次
  306. * @param {string} semesterId 形如 "2026-2027-1"
  307. * @returns {Promise<{startDate: string|null, totalWeeks: number|null}>}
  308. */
  309. async function fetchSemesterInfo(semesterId) {
  310. const html = await requestSemesterDetailPage(semesterId);
  311. const doc = new DOMParser().parseFromString(html, "text/html");
  312. const timetable = doc.getElementById("dataTable");
  313. if (!timetable) return { startDate: null, totalWeeks: null };
  314. const rows = Array.from(timetable.querySelectorAll("tbody tr"))
  315. .filter(r => r.querySelector("td"));
  316. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  317. let week1Row = null;
  318. for (const row of rows) {
  319. const label = row.querySelector("td.qz-weeklyTable-label")?.textContent.trim() || "";
  320. if (label === "第1周") {
  321. week1Row = row;
  322. break;
  323. }
  324. }
  325. if (!week1Row) week1Row = rows[0];
  326. let startDate = null;
  327. const dayCells = Array.from(week1Row.querySelectorAll("td.qz-weeklyTable-normalDay"));
  328. if (dayCells.length > 0) {
  329. const firstCellText = dayCells[0].textContent || "";
  330. const dm = firstCellText.match(/(\d{2})月(\d{2})日/);
  331. if (dm) {
  332. const month = parseInt(dm[1], 10);
  333. const day = dm[2];
  334. const yearMatch = semesterId.match(/^(\d{4})/);
  335. let year = yearMatch ? parseInt(yearMatch[1], 10) : new Date().getFullYear();
  336. if (month < 8) year += 1;
  337. startDate = `${year}-${dm[1]}-${day}`;
  338. }
  339. }
  340. let totalWeeks = null;
  341. for (const row of rows) {
  342. const label = row.querySelector("td.qz-weeklyTable-label")?.textContent.trim() || "";
  343. const wm = label.match(/第(\d+)周/);
  344. if (wm) {
  345. const n = parseInt(wm[1], 10);
  346. if (!isNaN(n) && n > 0) {
  347. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  348. }
  349. }
  350. }
  351. return { startDate, totalWeeks };
  352. }
  353. /**
  354. * 获取并解析指定学期的课程
  355. * @param {string} semesterId 形如 "2025-2026-2"
  356. * @returns {Promise<Array<Object>>}
  357. */
  358. async function fetchCourses(semesterId) {
  359. const html = await requestCoursePage(semesterId);
  360. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  361. }
  362. // 配置保存
  363. async function saveAppConfig(semesterStartDate, totalWeeks) {
  364. const config = {
  365. "semesterTotalWeeks": totalWeeks || 20,
  366. "firstDayOfWeek": 7
  367. };
  368. if (semesterStartDate) {
  369. config.semesterStartDate = semesterStartDate;
  370. }
  371. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  372. }
  373. /**
  374. * 统一作息(湖南大学)
  375. */
  376. async function saveAppTimeSlots() {
  377. const unifiedSlots = [
  378. { "number": 1, "startTime": "08:00", "endTime": "08:45" },
  379. { "number": 2, "startTime": "08:55", "endTime": "09:40" },
  380. { "number": 3, "startTime": "10:00", "endTime": "10:45" },
  381. { "number": 4, "startTime": "10:55", "endTime": "11:40" },
  382. { "number": 5, "startTime": "14:30", "endTime": "15:15" },
  383. { "number": 6, "startTime": "15:15", "endTime": "16:00" },
  384. { "number": 7, "startTime": "16:10", "endTime": "16:55" },
  385. { "number": 8, "startTime": "16:55", "endTime": "17:40" },
  386. { "number": 9, "startTime": "19:00", "endTime": "19:45" },
  387. { "number": 10, "startTime": "19:55", "endTime": "20:40" },
  388. { "number": 11, "startTime": "20:50", "endTime": "21:35" }
  389. ];
  390. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(unifiedSlots));
  391. }
  392. // 流程编排
  393. async function runImportFlow() {
  394. try {
  395. // 1. 用户确认
  396. const confirmed = await window.shiguangBridgePromise.showAlert(
  397. "提示", "请确保已成功登录教务系统。是否开始导入?", "开始"
  398. );
  399. if (!confirmed) return;
  400. // 2. 获取学期列表
  401. window.shiguangBridge.showToast("正在获取学期列表...");
  402. const { list: semesters, defaultIndex } = await fetchSemesterList();
  403. if (!semesters || semesters.length === 0) {
  404. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  405. return;
  406. }
  407. // 3. 用户选择学期
  408. const labels = semesters.map(s => s.label);
  409. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  410. "选择学期", JSON.stringify(labels), defaultIndex
  411. );
  412. if (selectedIndex === null) return;
  413. const semesterId = semesters[selectedIndex].value;
  414. // 4. 获取开学日期 + 最大周次
  415. window.shiguangBridge.showToast("正在获取学期信息...");
  416. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  417. // 5. 获取课程
  418. window.shiguangBridge.showToast("正在请求课程数据...");
  419. const finalCourses = await fetchCourses(semesterId);
  420. if (finalCourses.length === 0) {
  421. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  422. return;
  423. }
  424. // 6. 保存配置(含开学日期 + 最大周次)/ 作息 / 课程
  425. await saveAppConfig(semesterStartDate, totalWeeks);
  426. await saveAppTimeSlots();
  427. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  428. // 7. 完成
  429. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  430. window.shiguangBridge.notifyTaskCompletion();
  431. } catch (error) {
  432. window.shiguangBridge.showToast("异常: " + error.message);
  433. }
  434. }
  435. // 启动导入流程
  436. runImportFlow();