qdu_01.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // 青岛大学(xjw.qdu.edu.cn)拾光课程表适配脚本
  2. // 由本校开发者JellyfisHawthorn适配
  3. // 出现问题请提联系开发者或者提交pr更改,这更加快速
  4. const BASE_URL = "https://xjw.qdu.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. // 1. 深拷贝并规范周次数据,过滤无效项
  33. const list = courses.map(c => ({
  34. ...c,
  35. name: c.name || '',
  36. teacher: c.teacher || '',
  37. position: c.position || '',
  38. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  39. }));
  40. // 阶段 1:合并连续节次与完全重复记录
  41. list.sort((a, b) => {
  42. return a.name.localeCompare(b.name) ||
  43. a.teacher.localeCompare(b.teacher) ||
  44. a.position.localeCompare(b.position) ||
  45. (a.day || 0) - (b.day || 0) ||
  46. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  47. (a.startSection || 0) - (b.startSection || 0);
  48. });
  49. const step1Merged = [];
  50. let current = list[0];
  51. for (let i = 1; i < list.length; i++) {
  52. const next = list[i];
  53. const isSameCourseAndWeeks =
  54. current.name === next.name &&
  55. current.teacher === next.teacher &&
  56. current.position === next.position &&
  57. current.day === next.day &&
  58. current.weeks.join(',') === next.weeks.join(',');
  59. const isContinuous = current.endSection + 1 === next.startSection;
  60. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  61. if (isSameCourseAndWeeks && isContinuous) {
  62. current.endSection = next.endSection;
  63. } else if (isSameCourseAndWeeks && isDuplicate) {
  64. continue;
  65. } else {
  66. step1Merged.push(current);
  67. current = next;
  68. }
  69. }
  70. step1Merged.push(current);
  71. // 阶段 2:合并同节次的周次
  72. step1Merged.sort((a, b) => {
  73. return a.name.localeCompare(b.name) ||
  74. a.teacher.localeCompare(b.teacher) ||
  75. a.position.localeCompare(b.position) ||
  76. (a.day || 0) - (b.day || 0) ||
  77. (a.startSection || 0) - (b.startSection || 0) ||
  78. (a.endSection || 0) - (b.endSection || 0);
  79. });
  80. const step2Merged = [];
  81. let cur = step1Merged[0];
  82. for (let i = 1; i < step1Merged.length; i++) {
  83. const nxt = step1Merged[i];
  84. const isSameCourseAndSection =
  85. cur.name === nxt.name &&
  86. cur.teacher === nxt.teacher &&
  87. cur.position === nxt.position &&
  88. cur.day === nxt.day &&
  89. cur.startSection === nxt.startSection &&
  90. cur.endSection === nxt.endSection;
  91. if (isSameCourseAndSection) {
  92. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  93. } else {
  94. step2Merged.push(cur);
  95. cur = nxt;
  96. }
  97. }
  98. step2Merged.push(cur);
  99. return step2Merged;
  100. }
  101. // 核心解析逻辑
  102. function parseTimetableToModel(doc) {
  103. const timetable = doc.getElementById('timetable');
  104. if (!timetable) return [];
  105. let rawCourses = [];
  106. const rows = Array.from(timetable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  107. rows.forEach((row, SectionIndex) => {
  108. const cells = row.querySelectorAll('td');
  109. cells.forEach((cell, dayIndex) => {
  110. const day = dayIndex + 1;
  111. const detailDivs = cell.querySelectorAll('div.kbcontent');
  112. detailDivs.forEach(div => {
  113. const rawHtml = div.innerHTML.trim();
  114. if (!rawHtml || rawHtml === "&nbsp;" || div.innerText.trim().length < 2) return;
  115. const blocks = rawHtml.split(/---------------------|----------------------/);
  116. blocks.forEach(block => {
  117. if (!block.trim()) return;
  118. const tempDiv = document.createElement('div');
  119. tempDiv.innerHTML = block;
  120. let name = "";
  121. for (let node of tempDiv.childNodes) {
  122. if (node.nodeType === 1 && node.textContent.trim() !== "") {
  123. name = node.textContent.trim();
  124. break;
  125. }
  126. }
  127. const teacherRaw = tempDiv.querySelector('font[title="老师"], font[title="教师"]')?.innerText || "";
  128. const teacher = teacherRaw.replace("任课教师:", "").trim();
  129. const position = tempDiv.querySelector('font[title="教室"]')?.innerText || "未知地点";
  130. const weekStr = tempDiv.querySelector('font[title="周次(节次)"]')?.innerText || "";
  131. let startSection = SectionIndex * 2 + 1;
  132. if (SectionIndex >= 2) startSection += 1;
  133. if (SectionIndex >= 4) startSection += 1;
  134. let endSection = 0;
  135. if (SectionIndex === 5) endSection = startSection; else endSection = startSection + 1;
  136. if (name) {
  137. rawCourses.push({
  138. "name": name,
  139. "teacher": teacher || "未知教师",
  140. "weeks": parseWeeks(weekStr),
  141. "position": position,
  142. "day": day,
  143. "startSection": startSection,
  144. "endSection": endSection
  145. });
  146. }
  147. });
  148. });
  149. });
  150. });
  151. return mergeAndDistinctCourses(rawCourses);
  152. }
  153. // 网络请求封装
  154. /**
  155. * GET 教学周历页面(用于获取学期列表)
  156. */
  157. async function requestSemesterPage() {
  158. const response = await fetch(URL_SEMESTER, {
  159. method: "GET",
  160. credentials: "include"
  161. });
  162. return await response.text();
  163. }
  164. /**
  165. * POST 教学周历页面(用于获取指定学期的开学日期与最大周次)
  166. * @param {string} semesterId 形如 "2025-2026-2"
  167. */
  168. async function requestSemesterDetailPage(semesterId) {
  169. const response = await fetch(URL_SEMESTER, {
  170. method: "POST",
  171. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  172. body: `xnxq01id=${semesterId}`,
  173. credentials: "include"
  174. });
  175. return await response.text();
  176. }
  177. /**
  178. * POST 课表页面(用于获取课程数据)
  179. * @param {string} semesterId 形如 "2025-2026-2"
  180. */
  181. async function requestCoursePage(semesterId) {
  182. const response = await fetch(URL_COURSE, {
  183. method: "POST",
  184. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  185. body: `jx0404id=&cj0701id=&zc=&demo=&xnxq01id=${semesterId}`,
  186. credentials: "include"
  187. });
  188. return await response.text();
  189. }
  190. // 业务逻辑
  191. /**
  192. * 获取学期列表,以 selected 为原点上下各取 3 个
  193. * @returns {Promise<{list: Array<{value:string,label:string}>, defaultIndex:number}>}
  194. */
  195. async function fetchSemesterList() {
  196. const html = await requestSemesterPage();
  197. const doc = new DOMParser().parseFromString(html, "text/html");
  198. const select = doc.getElementById("xnxq01id");
  199. if (!select) return { list: [], defaultIndex: -1 };
  200. const allOptions = Array.from(select.querySelectorAll("option")).map(opt => ({
  201. value: opt.value,
  202. label: opt.textContent.trim(),
  203. selected: opt.hasAttribute("selected")
  204. }));
  205. let selectedIndex = allOptions.findIndex(o => o.selected);
  206. if (selectedIndex === -1) selectedIndex = 0;
  207. const start = Math.max(0, selectedIndex - 3);
  208. const end = Math.min(allOptions.length, selectedIndex + 4);
  209. const list = allOptions.slice(start, end);
  210. const defaultIndex = selectedIndex - start;
  211. return { list, defaultIndex };
  212. }
  213. /**
  214. * 获取指定学期的开学日期 + 最大周次
  215. * @param {string} semesterId 形如 "2025-2026-2"
  216. * @returns {Promise<{startDate: string|null, totalWeeks: number|null}>}
  217. */
  218. async function fetchSemesterInfo(semesterId) {
  219. const html = await requestSemesterDetailPage(semesterId);
  220. const doc = new DOMParser().parseFromString(html, "text/html");
  221. const timetable = doc.getElementById("kbtable");
  222. if (!timetable) return { startDate: null, totalWeeks: null };
  223. const rows = Array.from(timetable.querySelectorAll("tr")).filter(r => r.querySelector("td"));
  224. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  225. const firstDateCell = rows[0].querySelector("td[title]");
  226. const title = firstDateCell?.getAttribute("title") || "";
  227. const match = title.match(/^(\d{4})年(\d{2})月(\d{2})$/);
  228. const startDate = match ? `${match[1]}-${match[2]}-${match[3]}` : null;
  229. // 最大周次:所有行第一个 td 中能解析为整数的最大值
  230. let totalWeeks = null;
  231. for (const row of rows) {
  232. const firstTd = row.querySelector("td");
  233. if (!firstTd) continue;
  234. const n = parseInt(firstTd.textContent.trim(), 10);
  235. if (!isNaN(n) && n > 0) {
  236. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  237. }
  238. }
  239. return { startDate, totalWeeks };
  240. }
  241. /**
  242. * 获取并解析指定学期的课程
  243. * @param {string} semesterId 形如 "2025-2026-2"
  244. * @returns {Promise<Array<Object>>}
  245. */
  246. async function fetchCourses(semesterId) {
  247. const html = await requestCoursePage(semesterId);
  248. // 打印html todo
  249. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  250. }
  251. // 配置保存
  252. async function saveAppConfig(semesterStartDate, totalWeeks) {
  253. const config = {
  254. "semesterTotalWeeks": totalWeeks || 20,
  255. "firstDayOfWeek": 1,
  256. "defaultClassDuration": 50
  257. };
  258. if (semesterStartDate) {
  259. config.semesterStartDate = semesterStartDate;
  260. }
  261. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  262. }
  263. /**
  264. * 统一作息
  265. */
  266. async function saveAppTimeSlots() {
  267. // 分别定义春夏季和秋冬季的作息时间表。注:T2时段仅供参考(因为我没上过且没找到官方具体时间)
  268. const ssTimeSlots = [
  269. { "number": 1, "startTime": "08:00", "endTime": "08:50"},
  270. { "number": 2, "startTime": "09:00", "endTime": "09:50"},
  271. { "number": 3, "startTime": "10:10", "endTime": "11:00"},
  272. { "number": 4, "startTime": "11:10", "endTime": "12:00"},
  273. { "number": 5, "startTime": "13:10", "endTime": "14:00"},
  274. { "number": 6, "startTime": "14:00", "endTime": "14:50"},
  275. { "number": 7, "startTime": "15:00", "endTime": "15:50"},
  276. { "number": 8, "startTime": "16:00", "endTime": "16:50"},
  277. { "number": 9, "startTime": "17:00", "endTime": "17:50"},
  278. { "number": 10, "startTime": "17:50", "endTime": "18:30"},
  279. { "number": 11, "startTime": "19:00", "endTime": "19:50"},
  280. { "number": 12, "startTime": "20:00", "endTime": "20:50"},
  281. { "number": 13, "startTime": "21:00", "endTime": "21:50"}
  282. ]
  283. const awTimeSlots = [
  284. { "number": 1, "startTime": "08:00", "endTime": "08:50"},
  285. { "number": 2, "startTime": "09:00", "endTime": "09:50"},
  286. { "number": 3, "startTime": "10:10", "endTime": "11:00"},
  287. { "number": 4, "startTime": "11:10", "endTime": "12:00"},
  288. { "number": 5, "startTime": "12:40", "endTime": "13:30"},
  289. { "number": 6, "startTime": "13:30", "endTime": "14:20"},
  290. { "number": 7, "startTime": "14:30", "endTime": "15:20"},
  291. { "number": 8, "startTime": "15:30", "endTime": "16:20"},
  292. { "number": 9, "startTime": "16:30", "endTime": "17:20"},
  293. { "number": 10, "startTime": "17:20", "endTime": "18:00"},
  294. { "number": 11, "startTime": "18:30", "endTime": "19:20"},
  295. { "number": 12, "startTime": "19:30", "endTime": "20:20"},
  296. { "number": 13, "startTime": "20:30", "endTime": "21:20"}
  297. ];
  298. // 用户选择作息时间表,春夏还是秋冬
  299. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  300. "选择作息时间", JSON.stringify(["春夏季作息", "秋冬季作息"]), 0
  301. );
  302. let timeSlots = [];
  303. if (selectedIndex === null) return;
  304. else if (selectedIndex === 0) {
  305. timeSlots = ssTimeSlots;
  306. } else {
  307. timeSlots = awTimeSlots;
  308. }
  309. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  310. }
  311. // 流程编排
  312. async function runImportFlow() {
  313. try {
  314. // 1. 用户确认
  315. const confirmed = await window.shiguangBridgePromise.showAlert(
  316. "提示", "请确保已成功登录教务系统。是否开始导入?", "开始"
  317. );
  318. if (!confirmed) return;
  319. // 2. 获取学期列表
  320. window.shiguangBridge.showToast("正在获取学期列表...");
  321. const { list: semesters, defaultIndex } = await fetchSemesterList();
  322. if (!semesters || semesters.length === 0) {
  323. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  324. return;
  325. }
  326. // 3. 用户选择学期
  327. const labels = semesters.map(s => s.label);
  328. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  329. "选择学期", JSON.stringify(labels), defaultIndex
  330. );
  331. if (selectedIndex === null) return;
  332. const semesterId = semesters[selectedIndex].value;
  333. // 4. 获取开学日期
  334. window.shiguangBridge.showToast("正在获取学期信息...");
  335. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  336. // 5. 获取课程
  337. window.shiguangBridge.showToast("正在请求课程数据...");
  338. const finalCourses = await fetchCourses(semesterId);
  339. if (finalCourses.length === 0) {
  340. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  341. return;
  342. }
  343. // 6. 保存配置(含开学日期 + 最大周次(最大限制为 20))/ 作息 / 课程
  344. await saveAppConfig(semesterStartDate, Math.min(totalWeeks, 20));
  345. await saveAppTimeSlots();
  346. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  347. // 7. 完成
  348. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  349. window.shiguangBridge.notifyTaskCompletion();
  350. } catch (error) {
  351. window.shiguangBridge.showToast("异常: " + error.message);
  352. }
  353. }
  354. // 启动
  355. runImportFlow();