qdu_01.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. const URL_PLAN = `${BASE_URL}/jsxsd/pyfa/pyfa_query`; // 执行计划查询(用于查课程学分)
  8. const URL_FXPLAN = `${BASE_URL}/jsxsd/pyfa/fxpyfa_query`; // 辅修执行计划查询
  9. const URL_WZYPLAN = `${BASE_URL}/jsxsd/pyfa/wzypyfa_query`; // 微专业执行计划查询
  10. // 工具函数
  11. function parseWeeks(weekStr) {
  12. const weeks = [];
  13. if (!weekStr) return weeks;
  14. const pureWeekData = weekStr.split('(')[0];
  15. pureWeekData.split(',').forEach(seg => {
  16. if (seg.includes('-')) {
  17. const [s, e] = seg.split('-').map(Number);
  18. if (!isNaN(s) && !isNaN(e)) {
  19. for (let i = s; i <= e; i++) weeks.push(i);
  20. }
  21. } else {
  22. const w = parseInt(seg);
  23. if (!isNaN(w)) weeks.push(w);
  24. }
  25. });
  26. return [...new Set(weeks)].sort((a, b) => a - b);
  27. }
  28. /**
  29. * 节次与周次合并去重函数(供开发者参考)
  30. * @param {Array<Object>} courses 原始解析课程数组
  31. * @returns {Array<Object>} 合并去重后的课程数组
  32. */
  33. function mergeAndDistinctCourses(courses) {
  34. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  35. // 1. 深拷贝并规范周次数据,过滤无效项
  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 parseTimetableToModel(doc, courseCredits) {
  106. // 获取课程学分对象
  107. const timetable = doc.getElementById('timetable');
  108. if (!timetable) return [];
  109. let rawCourses = [];
  110. const rows = Array.from(timetable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  111. rows.forEach((row, SectionIndex) => {
  112. const cells = row.querySelectorAll('td');
  113. cells.forEach((cell, dayIndex) => {
  114. const day = dayIndex + 1;
  115. const detailDivs = cell.querySelectorAll('div.kbcontent');
  116. detailDivs.forEach(div => {
  117. const rawHtml = div.innerHTML.trim();
  118. if (!rawHtml || rawHtml === "&nbsp;" || div.innerText.trim().length < 2) return;
  119. const blocks = rawHtml.split(/---------------------|----------------------/);
  120. blocks.forEach(block => {
  121. if (!block.trim()) return;
  122. const tempDiv = document.createElement('div');
  123. tempDiv.innerHTML = block;
  124. let name = "";
  125. for (let node of tempDiv.childNodes) {
  126. if (node.nodeType === 1 && node.textContent.trim() !== "") {
  127. name = node.textContent.trim();
  128. break;
  129. }
  130. }
  131. const teacherRaw = tempDiv.querySelector('font[title="老师"], font[title="教师"]')?.innerText || "";
  132. const teacher = teacherRaw.replace("任课教师:", "").trim();
  133. const position = tempDiv.querySelector('font[title="教室"]')?.innerText || "未知地点";
  134. const weekStr = tempDiv.querySelector('font[title="周次(节次)"]')?.innerText || "";
  135. let startSection = SectionIndex * 2 + 1;
  136. if (SectionIndex >= 2) startSection += 1;
  137. if (SectionIndex >= 4) startSection += 1;
  138. let endSection = 0;
  139. if (SectionIndex === 5) endSection = startSection; else endSection = startSection + 1;
  140. if (name) {
  141. rawCourses.push({
  142. "name": name,
  143. "teacher": teacher || "未知教师",
  144. "weeks": parseWeeks(weekStr),
  145. "position": position,
  146. "day": day,
  147. "startSection": startSection,
  148. "endSection": endSection,
  149. "credit": courseCredits[name] || null
  150. });
  151. }
  152. });
  153. });
  154. });
  155. });
  156. return mergeAndDistinctCourses(rawCourses);
  157. }
  158. // 网络请求封装
  159. /**
  160. * GET 教学周历页面(用于获取学期列表)
  161. */
  162. async function requestSemesterPage() {
  163. const response = await fetch(URL_SEMESTER, {
  164. method: "GET",
  165. credentials: "include"
  166. });
  167. return await response.text();
  168. }
  169. /**
  170. * POST 教学周历页面(用于获取指定学期的开学日期与最大周次)
  171. * @param {string} semesterId 形如 "2025-2026-2"
  172. */
  173. async function requestSemesterDetailPage(semesterId) {
  174. const response = await fetch(URL_SEMESTER, {
  175. method: "POST",
  176. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  177. body: `xnxq01id=${semesterId}`,
  178. credentials: "include"
  179. });
  180. return await response.text();
  181. }
  182. /**
  183. * POST 课表页面(用于获取课程数据)
  184. * @param {string} semesterId 形如 "2025-2026-2"
  185. */
  186. async function requestCoursePage(semesterId) {
  187. const response = await fetch(URL_COURSE, {
  188. method: "POST",
  189. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  190. body: `jx0404id=&cj0701id=&zc=&demo=&xnxq01id=${semesterId}`,
  191. credentials: "include"
  192. });
  193. return await response.text();
  194. }
  195. /**
  196. * GET 执行计划页面(用于获取课程对应的学分)
  197. */
  198. async function requestPlanPage() {
  199. const response = await fetch(URL_PLAN, {
  200. method: "GET",
  201. credentials: "include"
  202. });
  203. return await response.text();
  204. }
  205. /**
  206. * GET 辅修执行计划页面(用于获取课程对应的学分)
  207. */
  208. async function requestFxFPlanPage() {
  209. const response = await fetch(URL_FXPLAN, {
  210. method: "GET",
  211. credentials: "include"
  212. });
  213. return await response.text();
  214. }
  215. /**
  216. * GET 微专业执行计划页面(用于获取课程对应的学分)
  217. */
  218. async function requestWZYPlanPage() {
  219. const response = await fetch(URL_WZYPLAN, {
  220. method: "GET",
  221. credentials: "include"
  222. });
  223. return await response.text();
  224. }
  225. // 业务逻辑
  226. /**
  227. * 获取学期列表,以 selected 为原点上下各取 3 个
  228. * @returns {Promise<{list: Array<{value:string,label:string}>, defaultIndex:number}>}
  229. */
  230. async function fetchSemesterList() {
  231. const html = await requestSemesterPage();
  232. const doc = new DOMParser().parseFromString(html, "text/html");
  233. const select = doc.getElementById("xnxq01id");
  234. if (!select) return { list: [], defaultIndex: -1 };
  235. const allOptions = Array.from(select.querySelectorAll("option")).map(opt => ({
  236. value: opt.value,
  237. label: opt.textContent.trim(),
  238. selected: opt.hasAttribute("selected")
  239. }));
  240. let selectedIndex = allOptions.findIndex(o => o.selected);
  241. if (selectedIndex === -1) selectedIndex = 0;
  242. const start = Math.max(0, selectedIndex - 3);
  243. const end = Math.min(allOptions.length, selectedIndex + 4);
  244. const list = allOptions.slice(start, end);
  245. const defaultIndex = selectedIndex - start;
  246. return { list, defaultIndex };
  247. }
  248. /**
  249. * 获取指定学期的开学日期 + 最大周次
  250. * @param {string} semesterId 形如 "2025-2026-2"
  251. * @returns {Promise<{startDate: string|null, totalWeeks: number|null}>}
  252. */
  253. async function fetchSemesterInfo(semesterId) {
  254. const html = await requestSemesterDetailPage(semesterId);
  255. const doc = new DOMParser().parseFromString(html, "text/html");
  256. const timetable = doc.getElementById("kbtable");
  257. if (!timetable) return { startDate: null, totalWeeks: null };
  258. const rows = Array.from(timetable.querySelectorAll("tr")).filter(r => r.querySelector("td"));
  259. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  260. const firstDateCell = rows[0].querySelector("td[title]");
  261. const title = firstDateCell?.getAttribute("title") || "";
  262. const match = title.match(/^(\d{4})年(\d{2})月(\d{2})$/);
  263. const startDate = match ? `${match[1]}-${match[2]}-${match[3]}` : null;
  264. // 最大周次:所有行第一个 td 中能解析为整数的最大值
  265. let totalWeeks = null;
  266. for (const row of rows) {
  267. const firstTd = row.querySelector("td");
  268. if (!firstTd) continue;
  269. const n = parseInt(firstTd.textContent.trim(), 10);
  270. if (!isNaN(n) && n > 0) {
  271. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  272. }
  273. }
  274. return { startDate, totalWeeks };
  275. }
  276. /**
  277. * 获取并解析指定学期的课程
  278. * @param {string} semesterId 形如 "2025-2026-2"
  279. * @returns {Promise<Array<Object>>}
  280. */
  281. async function fetchCourses(semesterId) {
  282. const courseCredits = await fetchAllCourseCredits();
  283. const html = await requestCoursePage(semesterId);
  284. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"), courseCredits);
  285. }
  286. /**
  287. * 获取执行计划里所有课程对应的学分
  288. * 部分限选、任选课的学分信息暂时无法获取
  289. * @returns {Promise<Object>} 课程名称 -> 学分
  290. */
  291. async function fetchAllCourseCredits() {
  292. const courseCredits = {}; // 存储所有课程的学分信息
  293. // 依次获取三个执行计划表的学分信息
  294. const requestFns = [
  295. requestPlanPage,
  296. requestFxFPlanPage,
  297. requestWZYPlanPage
  298. ];
  299. for (const requestFn of requestFns) {
  300. const html = await requestFn();
  301. const doc = new DOMParser().parseFromString(html, "text/html");
  302. const dataTable = doc.getElementById("dataList");
  303. const rows = Array.from(dataTable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  304. // 如果rows的第一项内容只有“未查询到数据”文本,说明没有数据,跳过后续处理
  305. if (rows[0].querySelector('td').textContent.trim() === "未查询到数据") {
  306. continue;
  307. }
  308. rows.forEach((row) => {
  309. // 每一行的第四个单元格是课程名称,第六个单元格是学分
  310. const courseName = row.querySelector('td:nth-child(4)').textContent.trim();
  311. const credit = row.querySelector('td:nth-child(6)').textContent.trim();
  312. if (courseName && !(courseName in courseCredits)) {
  313. courseCredits[courseName] = parseFloat(credit);
  314. }
  315. });
  316. }
  317. return courseCredits;
  318. }
  319. /**
  320. * 获取某课程的学分
  321. * @param {string} courseName 课程名称
  322. * @param {Object} courseCredits 学分信息对象
  323. * @returns {Promise<number|null>}
  324. */
  325. async function fetchCourseCredit(courseName, courseCredits) {
  326. if (courseName in courseCredits) {
  327. return courseCredits[courseName];
  328. } else {
  329. window.shiguangBridge.showToast(`${courseName}的学分信息未找到!`);
  330. return null;
  331. }
  332. }
  333. // 配置保存
  334. async function saveAppConfig(semesterStartDate, totalWeeks) {
  335. const config = {
  336. "semesterTotalWeeks": totalWeeks || 20,
  337. "firstDayOfWeek": 1,
  338. "defaultClassDuration": 50
  339. };
  340. if (semesterStartDate) {
  341. config.semesterStartDate = semesterStartDate;
  342. }
  343. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  344. }
  345. /**
  346. * 统一作息
  347. */
  348. async function saveAppTimeSlots(semesterId) {
  349. // 基础时间段
  350. const baseTimeSlots = [
  351. { "number": 1, "startTime": "08:00", "endTime": "08:50" },
  352. { "number": 2, "startTime": "09:00", "endTime": "09:50" },
  353. { "number": 3, "startTime": "10:10", "endTime": "11:00" },
  354. { "number": 4, "startTime": "11:10", "endTime": "12:00" },
  355. { "number": 5, "startTime": "13:10", "endTime": "14:00" },
  356. { "number": 6, "startTime": "14:00", "endTime": "14:50" },
  357. { "number": 7, "startTime": "15:00", "endTime": "15:50" },
  358. { "number": 8, "startTime": "16:00", "endTime": "16:50" },
  359. { "number": 9, "startTime": "17:00", "endTime": "17:50" },
  360. { "number": 10, "startTime": "17:50", "endTime": "18:30" },
  361. { "number": 11, "startTime": "19:00", "endTime": "19:50" },
  362. { "number": 12, "startTime": "20:00", "endTime": "20:50" },
  363. { "number": 13, "startTime": "21:00", "endTime": "21:50" }
  364. ];
  365. // 创建当前学期的组合作息方案。注:T2时段(第10节)仅供参考(因为我没上过且没找到官方具体时间)
  366. // 根据semesterId获取此学期的信息
  367. const [startYear, endYear, semester] = semesterId.split("-");
  368. let comboSchedule = null;
  369. if (semester === "1") {
  370. // 秋冬学期
  371. comboSchedule = {
  372. name: `${startYear}秋组合作息方案`,
  373. publicSchedules: [
  374. {
  375. name: `${startYear}春夏作息`,
  376. startDate: `${startYear}-05-01`,
  377. endDate: `${startYear}-09-30`,
  378. timeSlots: [
  379. { "number": 5, "startTime": "13:10", "endTime": "14:00" },
  380. { "number": 6, "startTime": "14:00", "endTime": "14:50" },
  381. { "number": 7, "startTime": "15:00", "endTime": "15:50" },
  382. { "number": 8, "startTime": "16:00", "endTime": "16:50" },
  383. { "number": 9, "startTime": "17:00", "endTime": "17:50" },
  384. { "number": 10, "startTime": "17:50", "endTime": "18:30" },
  385. { "number": 11, "startTime": "19:00", "endTime": "19:50" },
  386. { "number": 12, "startTime": "20:00", "endTime": "20:50" },
  387. { "number": 13, "startTime": "21:00", "endTime": "21:50" }
  388. ]
  389. },
  390. {
  391. name: `${startYear}秋冬作息`,
  392. startDate: `${startYear}-10-01`,
  393. endDate: `${endYear}-04-30`,
  394. timeSlots: [
  395. { "number": 5, "startTime": "12:40", "endTime": "13:30" },
  396. { "number": 6, "startTime": "13:30", "endTime": "14:20" },
  397. { "number": 7, "startTime": "14:30", "endTime": "15:20" },
  398. { "number": 8, "startTime": "15:30", "endTime": "16:20" },
  399. { "number": 9, "startTime": "16:30", "endTime": "17:20" },
  400. { "number": 10, "startTime": "17:20", "endTime": "18:00" },
  401. { "number": 11, "startTime": "18:30", "endTime": "19:20" },
  402. { "number": 12, "startTime": "19:30", "endTime": "20:20" },
  403. { "number": 13, "startTime": "20:30", "endTime": "21:20" }
  404. ]
  405. }
  406. ]
  407. };
  408. } else if (semester === "2") {
  409. // 春夏学期
  410. comboSchedule = {
  411. name: `${endYear}春组合作息方案`,
  412. publicSchedules: [
  413. {
  414. name: `${startYear}秋冬作息`,
  415. startDate: `${startYear}-10-01`,
  416. endDate: `${endYear}-04-30`,
  417. timeSlots: [
  418. { "number": 5, "startTime": "12:40", "endTime": "13:30" },
  419. { "number": 6, "startTime": "13:30", "endTime": "14:20" },
  420. { "number": 7, "startTime": "14:30", "endTime": "15:20" },
  421. { "number": 8, "startTime": "15:30", "endTime": "16:20" },
  422. { "number": 9, "startTime": "16:30", "endTime": "17:20" },
  423. { "number": 10, "startTime": "17:20", "endTime": "18:00" },
  424. { "number": 11, "startTime": "18:30", "endTime": "19:20" },
  425. { "number": 12, "startTime": "19:30", "endTime": "20:20" },
  426. { "number": 13, "startTime": "20:30", "endTime": "21:20" }
  427. ]
  428. },
  429. {
  430. name: `${endYear}春夏作息`,
  431. startDate: `${endYear}-05-01`,
  432. endDate: `${endYear}-09-30`,
  433. timeSlots: [
  434. { "number": 5, "startTime": "13:10", "endTime": "14:00" },
  435. { "number": 6, "startTime": "14:00", "endTime": "14:50" },
  436. { "number": 7, "startTime": "15:00", "endTime": "15:50" },
  437. { "number": 8, "startTime": "16:00", "endTime": "16:50" },
  438. { "number": 9, "startTime": "17:00", "endTime": "17:50" },
  439. { "number": 10, "startTime": "17:50", "endTime": "18:30" },
  440. { "number": 11, "startTime": "19:00", "endTime": "19:50" },
  441. { "number": 12, "startTime": "20:00", "endTime": "20:50" },
  442. { "number": 13, "startTime": "21:00", "endTime": "21:50" }
  443. ]
  444. }
  445. ]
  446. };
  447. }
  448. // 保存作息方案
  449. try {
  450. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(baseTimeSlots));
  451. await window.shiguangBridgePromise.saveComboSchedule(JSON.stringify(comboSchedule));
  452. return true;
  453. } catch (error) {
  454. window.shiguangBridge.showToast("作息方案导入失败: " + error.message);
  455. return false;
  456. }
  457. }
  458. // 流程编排
  459. async function runImportFlow() {
  460. try {
  461. // 1. 用户确认
  462. const confirmed = await window.shiguangBridgePromise.showAlert(
  463. "提示", "请确保已成功登录教务系统。是否开始导入?", "开始"
  464. );
  465. if (!confirmed) return;
  466. // 2. 获取学期列表
  467. window.shiguangBridge.showToast("正在获取学期列表...");
  468. const { list: semesters, defaultIndex } = await fetchSemesterList();
  469. if (!semesters || semesters.length === 0) {
  470. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  471. return;
  472. }
  473. // 3. 用户选择学期
  474. const labels = semesters.map(s => s.label);
  475. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  476. "选择学期", JSON.stringify(labels), defaultIndex
  477. );
  478. if (selectedIndex === null) return;
  479. const semesterId = semesters[selectedIndex].value;
  480. // 4. 获取开学日期
  481. window.shiguangBridge.showToast("正在获取学期信息...");
  482. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  483. // 5. 获取课程
  484. window.shiguangBridge.showToast("正在请求课程数据...");
  485. const finalCourses = await fetchCourses(semesterId);
  486. if (finalCourses.length === 0) {
  487. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  488. return;
  489. }
  490. // 6. 保存配置(含开学日期 + 最大周次(最大限制为 20))/ 作息 / 课程
  491. await saveAppConfig(semesterStartDate, Math.min(totalWeeks, 20));
  492. await saveAppTimeSlots(semesterId);
  493. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  494. // 7. 完成
  495. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  496. window.shiguangBridge.notifyTaskCompletion();
  497. } catch (error) {
  498. window.shiguangBridge.showToast("异常: " + error.message);
  499. }
  500. }
  501. // 启动
  502. runImportFlow();