hnu_01.js 17 KB

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