yssdufe_01.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // 山东财经大学燕山学院(ys.sdufe.edu.cn) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请提联系开发者或者提交pr更改,这更加快速
  4. const BASE_URL = "https://ysjw.sdufe.edu.cn:8081";
  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('kbtable');
  104. if (!timetable) return [];
  105. let rawCourses = [];
  106. const rows = Array.from(timetable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  107. rows.forEach(row => {
  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 === 3 && 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 = 0;
  132. let endSection = 0;
  133. if (weekStr) {
  134. const sectionPart = weekStr.match(/\[(.*?)节\]/);
  135. if (sectionPart && sectionPart[1]) {
  136. const sections = sectionPart[1].split('-').map(Number).filter(n => !isNaN(n));
  137. if (sections.length > 0) {
  138. startSection = sections[0];
  139. endSection = sections[sections.length - 1];
  140. }
  141. }
  142. }
  143. if (name && startSection > 0) {
  144. rawCourses.push({
  145. "name": name,
  146. "teacher": teacher || "未知教师",
  147. "weeks": parseWeeks(weekStr),
  148. "position": position,
  149. "day": day,
  150. "startSection": startSection,
  151. "endSection": endSection
  152. });
  153. }
  154. });
  155. });
  156. });
  157. });
  158. return mergeAndDistinctCourses(rawCourses);
  159. }
  160. // 网络请求封装
  161. /**
  162. * GET 教学周历页面(用于获取学期列表)
  163. */
  164. async function requestSemesterPage() {
  165. const response = await fetch(URL_SEMESTER, {
  166. method: "GET",
  167. credentials: "include"
  168. });
  169. return await response.text();
  170. }
  171. /**
  172. * POST 教学周历页面(用于获取指定学期的开学日期与最大周次)
  173. * @param {string} semesterId 形如 "2025-2026-2"
  174. */
  175. async function requestSemesterDetailPage(semesterId) {
  176. const response = await fetch(URL_SEMESTER, {
  177. method: "POST",
  178. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  179. body: `xnxq01id=${semesterId}`,
  180. credentials: "include"
  181. });
  182. return await response.text();
  183. }
  184. /**
  185. * POST 课表页面(用于获取课程数据)
  186. * @param {string} semesterId 形如 "2025-2026-2"
  187. */
  188. async function requestCoursePage(semesterId) {
  189. const response = await fetch(URL_COURSE, {
  190. method: "POST",
  191. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  192. body: `jx0404id=&cj0701id=&zc=&demo=&xnxq01id=${semesterId}`,
  193. credentials: "include"
  194. });
  195. return await response.text();
  196. }
  197. // 业务逻辑
  198. /**
  199. * 获取学期列表,以 selected 为原点上下各取 3 个
  200. * @returns {Promise<{list: Array<{value:string,label:string}>, defaultIndex:number}>}
  201. */
  202. async function fetchSemesterList() {
  203. const html = await requestSemesterPage();
  204. const doc = new DOMParser().parseFromString(html, "text/html");
  205. const select = doc.getElementById("xnxq01id");
  206. if (!select) return { list: [], defaultIndex: -1 };
  207. const allOptions = Array.from(select.querySelectorAll("option")).map(opt => ({
  208. value: opt.value,
  209. label: opt.textContent.trim(),
  210. selected: opt.hasAttribute("selected")
  211. }));
  212. let selectedIndex = allOptions.findIndex(o => o.selected);
  213. if (selectedIndex === -1) selectedIndex = 0;
  214. const start = Math.max(0, selectedIndex - 3);
  215. const end = Math.min(allOptions.length, selectedIndex + 4);
  216. const list = allOptions.slice(start, end);
  217. const defaultIndex = selectedIndex - start;
  218. return { list, defaultIndex };
  219. }
  220. /**
  221. * 获取指定学期的开学日期 + 最大周次
  222. * @param {string} semesterId 形如 "2025-2026-2"
  223. * @returns {Promise<{startDate: string|null, totalWeeks: number|null}>}
  224. */
  225. async function fetchSemesterInfo(semesterId) {
  226. const html = await requestSemesterDetailPage(semesterId);
  227. const doc = new DOMParser().parseFromString(html, "text/html");
  228. const timetable = doc.getElementById("kbtable");
  229. if (!timetable) return { startDate: null, totalWeeks: null };
  230. const rows = Array.from(timetable.querySelectorAll("tr")).filter(r => r.querySelector("td"));
  231. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  232. const firstDateCell = rows[0].querySelector("td[title]");
  233. const title = firstDateCell?.getAttribute("title") || "";
  234. const match = title.match(/^(\d{4})年(\d{2})月(\d{2})$/);
  235. const startDate = match ? `${match[1]}-${match[2]}-${match[3]}` : null;
  236. // 最大周次:所有行第一个 td 中能解析为整数的最大值
  237. let totalWeeks = null;
  238. for (const row of rows) {
  239. const firstTd = row.querySelector("td");
  240. if (!firstTd) continue;
  241. const n = parseInt(firstTd.textContent.trim(), 10);
  242. if (!isNaN(n) && n > 0) {
  243. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  244. }
  245. }
  246. return { startDate, totalWeeks };
  247. }
  248. /**
  249. * 获取并解析指定学期的课程
  250. * @param {string} semesterId 形如 "2025-2026-2"
  251. * @returns {Promise<Array<Object>>}
  252. */
  253. async function fetchCourses(semesterId) {
  254. const html = await requestCoursePage(semesterId);
  255. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  256. }
  257. // 配置保存
  258. async function saveAppConfig(semesterStartDate, totalWeeks) {
  259. const config = {
  260. "semesterTotalWeeks": totalWeeks || 20,
  261. "firstDayOfWeek": 1
  262. };
  263. if (semesterStartDate) {
  264. config.semesterStartDate = semesterStartDate;
  265. }
  266. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  267. }
  268. /**
  269. * 统一作息
  270. */
  271. async function saveAppTimeSlots() {
  272. const unifiedSlots = [
  273. { "number": 1, "startTime": "08:30", "endTime": "09:15" },
  274. { "number": 2, "startTime": "09:15", "endTime": "10:00" },
  275. { "number": 3, "startTime": "10:20", "endTime": "11:05" },
  276. { "number": 4, "startTime": "11:05", "endTime": "11:50" },
  277. { "number": 5, "startTime": "13:30", "endTime": "14:15" },
  278. { "number": 6, "startTime": "14:15", "endTime": "15:00" },
  279. { "number": 7, "startTime": "15:20", "endTime": "16:05" },
  280. { "number": 8, "startTime": "16:05", "endTime": "16:50" },
  281. { "number": 9, "startTime": "18:30", "endTime": "19:15" },
  282. { "number": 10, "startTime": "19:15", "endTime": "20:00" },
  283. { "number": 11, "startTime": "20:10", "endTime": "21:50" }
  284. ];
  285. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(unifiedSlots));
  286. }
  287. // 流程编排
  288. async function runImportFlow() {
  289. try {
  290. // 1. 用户确认
  291. const confirmed = await window.shiguangBridgePromise.showAlert(
  292. "提示", "请确保已成功登录教务系统。是否开始导入?", "开始"
  293. );
  294. if (!confirmed) return;
  295. // 2. 获取学期列表
  296. window.shiguangBridge.showToast("正在获取学期列表...");
  297. const { list: semesters, defaultIndex } = await fetchSemesterList();
  298. if (!semesters || semesters.length === 0) {
  299. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  300. return;
  301. }
  302. // 3. 用户选择学期
  303. const labels = semesters.map(s => s.label);
  304. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  305. "选择学期", JSON.stringify(labels), defaultIndex
  306. );
  307. if (selectedIndex === null) return;
  308. const semesterId = semesters[selectedIndex].value;
  309. // 4. 获取开学日期 + 最大周次
  310. window.shiguangBridge.showToast("正在获取学期信息...");
  311. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  312. // 5. 获取课程
  313. window.shiguangBridge.showToast("正在请求课程数据...");
  314. const finalCourses = await fetchCourses(semesterId);
  315. if (finalCourses.length === 0) {
  316. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  317. return;
  318. }
  319. // 6. 保存配置(含开学日期 + 最大周次)/ 作息 / 课程
  320. await saveAppConfig(semesterStartDate, totalWeeks);
  321. await saveAppTimeSlots();
  322. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  323. // 7. 完成
  324. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  325. window.shiguangBridge.notifyTaskCompletion();
  326. } catch (error) {
  327. window.shiguangBridge.showToast("异常: " + error.message);
  328. }
  329. }
  330. // 启动
  331. runImportFlow();