zsc_01.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // 电子科技大学中山学院(jwgln.zsc.edu.cn) 拾光课程表适配脚本
  2. // 出现问题请联系维护者 Lanjunyee,或提交 issue / PR 反馈。
  3. const BASE_URL = "https://jwgln.zsc.edu.cn";
  4. const URL_SEMESTER = `${BASE_URL}/jsxsd/jxzl/jxzl_query`;
  5. const URL_COURSE = `${BASE_URL}/jsxsd/xskb/xskb_list.do`;
  6. const WEEKDAY_LABELS = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
  7. function parseWeeks(weekStr) {
  8. const weeks = [];
  9. if (!weekStr) return weeks;
  10. const pureWeekData = String(weekStr).split("(")[0].split("(")[0];
  11. pureWeekData.split(/[,,、]/).forEach(seg => {
  12. seg = seg.trim();
  13. if (!seg) return;
  14. if (seg.includes("-")) {
  15. const [s, e] = seg.split("-").map(Number);
  16. if (!isNaN(s) && !isNaN(e)) {
  17. for (let i = Math.min(s, e); i <= Math.max(s, e); i++) {
  18. if (i > 0) weeks.push(i);
  19. }
  20. }
  21. } else {
  22. const w = parseInt(seg, 10);
  23. if (!isNaN(w) && w > 0) weeks.push(w);
  24. }
  25. });
  26. return [...new Set(weeks)].sort((a, b) => a - b);
  27. }
  28. function mergeAndDistinctCourses(courses) {
  29. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  30. const list = courses.map(c => ({
  31. ...c,
  32. name: c.name || "",
  33. teacher: c.teacher || "",
  34. position: c.position || "",
  35. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  36. }));
  37. list.sort((a, b) => {
  38. return a.name.localeCompare(b.name) ||
  39. a.teacher.localeCompare(b.teacher) ||
  40. a.position.localeCompare(b.position) ||
  41. (a.day || 0) - (b.day || 0) ||
  42. a.weeks.join(",").localeCompare(b.weeks.join(",")) ||
  43. (a.startSection || 0) - (b.startSection || 0);
  44. });
  45. const step1Merged = [];
  46. let current = list[0];
  47. for (let i = 1; i < list.length; i++) {
  48. const next = list[i];
  49. const isSameCourseAndWeeks =
  50. current.name === next.name &&
  51. current.teacher === next.teacher &&
  52. current.position === next.position &&
  53. current.day === next.day &&
  54. current.weeks.join(",") === next.weeks.join(",");
  55. const isContinuous = current.endSection + 1 === next.startSection;
  56. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  57. if (isSameCourseAndWeeks && isContinuous) {
  58. current.endSection = next.endSection;
  59. } else if (isSameCourseAndWeeks && isDuplicate) {
  60. continue;
  61. } else {
  62. step1Merged.push(current);
  63. current = next;
  64. }
  65. }
  66. step1Merged.push(current);
  67. step1Merged.sort((a, b) => {
  68. return a.name.localeCompare(b.name) ||
  69. a.teacher.localeCompare(b.teacher) ||
  70. a.position.localeCompare(b.position) ||
  71. (a.day || 0) - (b.day || 0) ||
  72. (a.startSection || 0) - (b.startSection || 0) ||
  73. (a.endSection || 0) - (b.endSection || 0);
  74. });
  75. const step2Merged = [];
  76. let cur = step1Merged[0];
  77. for (let i = 1; i < step1Merged.length; i++) {
  78. const nxt = step1Merged[i];
  79. const isSameCourseAndSection =
  80. cur.name === nxt.name &&
  81. cur.teacher === nxt.teacher &&
  82. cur.position === nxt.position &&
  83. cur.day === nxt.day &&
  84. cur.startSection === nxt.startSection &&
  85. cur.endSection === nxt.endSection;
  86. if (isSameCourseAndSection) {
  87. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  88. } else {
  89. step2Merged.push(cur);
  90. cur = nxt;
  91. }
  92. }
  93. step2Merged.push(cur);
  94. return step2Merged;
  95. }
  96. function parseTimetableToModel(doc) {
  97. const timetable = doc.getElementById("kbtable");
  98. if (!timetable) return [];
  99. const rows = Array.from(timetable.querySelectorAll("tr"));
  100. const headerRow = rows[0];
  101. if (!headerRow) return [];
  102. const headerCells = Array.from(headerRow.querySelectorAll("th, td"));
  103. const columnDays = [];
  104. headerCells.forEach(cell => {
  105. const text = (cell.textContent || "").replace(/\s/g, "");
  106. const index = WEEKDAY_LABELS.findIndex(label => text === label || text.includes(label));
  107. if (index >= 0) columnDays.push(index + 1);
  108. });
  109. if (columnDays.length !== 7) return [];
  110. const rawCourses = [];
  111. rows.slice(1).forEach(row => {
  112. const labelCell = row.querySelector("th");
  113. if (!labelCell) return;
  114. const label = (labelCell.textContent || "").replace(/\s/g, "");
  115. const sectionMatch = label.match(/^第(\d+)[,,](\d+)节$/);
  116. if (!sectionMatch) return;
  117. const startSection = Number(sectionMatch[1]);
  118. const endSection = Number(sectionMatch[2]);
  119. const cells = Array.from(row.querySelectorAll("td"));
  120. if (cells.length < 7) return;
  121. for (let index = 0; index < 7; index++) {
  122. const day = columnDays[index];
  123. const cell = cells[index];
  124. if (!cell) continue;
  125. Array.from(cell.querySelectorAll("div.kbcontent")).forEach(div => {
  126. const rawHtml = div.innerHTML.trim();
  127. if (!rawHtml || rawHtml === "&nbsp;") return;
  128. const blocks = rawHtml.split(/-{10,}/);
  129. blocks.forEach(block => {
  130. if (!block.trim()) return;
  131. const tempDiv = doc.createElement("div");
  132. tempDiv.innerHTML = block;
  133. let name = "";
  134. for (const node of tempDiv.childNodes) {
  135. if (node.nodeType === 3 && node.textContent.trim() !== "") {
  136. name = node.textContent.trim();
  137. break;
  138. }
  139. }
  140. if (!name) return;
  141. const teacherRaw = tempDiv.querySelector('font[title="老师"], font[title="教师"]')?.textContent || "";
  142. const teacher = teacherRaw.replace(/任课教师[::]/, "").trim();
  143. const positionRaw = tempDiv.querySelector('font[title="教室"]')?.textContent || "";
  144. const position = positionRaw.trim();
  145. const weekStr = tempDiv.querySelector('font[title="周次(节次)"]')?.textContent || "";
  146. const weeks = parseWeeks(weekStr);
  147. if (weeks.length === 0) return;
  148. rawCourses.push({
  149. name: name,
  150. teacher: teacher,
  151. position: position,
  152. day: day,
  153. startSection: startSection,
  154. endSection: endSection,
  155. weeks: weeks
  156. });
  157. });
  158. });
  159. }
  160. });
  161. return mergeAndDistinctCourses(rawCourses);
  162. }
  163. async function requestSemesterPage() {
  164. const response = await fetch(URL_SEMESTER, {
  165. method: "GET",
  166. credentials: "include"
  167. });
  168. return await response.text();
  169. }
  170. async function requestSemesterDetailPage(semesterId) {
  171. const response = await fetch(URL_SEMESTER, {
  172. method: "POST",
  173. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  174. body: `xnxq01id=${encodeURIComponent(semesterId)}`,
  175. credentials: "include"
  176. });
  177. return await response.text();
  178. }
  179. async function requestCoursePage(semesterId) {
  180. const response = await fetch(URL_COURSE, {
  181. method: "POST",
  182. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  183. body: `jx0404id=&cj0701id=&zc=&demo=&xnxq01id=${encodeURIComponent(semesterId)}`,
  184. credentials: "include"
  185. });
  186. return await response.text();
  187. }
  188. async function fetchSemesterList() {
  189. const html = await requestSemesterPage();
  190. const doc = new DOMParser().parseFromString(html, "text/html");
  191. const select = doc.getElementById("xnxq01id");
  192. if (!select) return { list: [], defaultIndex: -1 };
  193. const allOptions = Array.from(select.querySelectorAll("option"))
  194. .map(opt => ({
  195. value: opt.value,
  196. label: opt.textContent.trim(),
  197. selected: opt.hasAttribute("selected")
  198. }))
  199. .filter(opt => /^\d{4}-\d{4}-[12]$/.test(opt.value));
  200. if (allOptions.length === 0) return { list: [], defaultIndex: -1 };
  201. let selectedIndex = allOptions.findIndex(o => o.selected);
  202. if (selectedIndex === -1) selectedIndex = 0;
  203. const start = Math.max(0, selectedIndex - 3);
  204. const end = Math.min(allOptions.length, selectedIndex + 4);
  205. const list = allOptions.slice(start, end);
  206. return { list: list, defaultIndex: selectedIndex - start };
  207. }
  208. async function fetchSemesterInfo(semesterId) {
  209. const html = await requestSemesterDetailPage(semesterId);
  210. const doc = new DOMParser().parseFromString(html, "text/html");
  211. const timetable = doc.getElementById("kbtable");
  212. if (!timetable) return { startDate: null, totalWeeks: null };
  213. const rows = Array.from(timetable.querySelectorAll("tr")).filter(r => r.querySelector("td"));
  214. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  215. let startDate = null;
  216. for (const row of rows) {
  217. const dateCell = row.querySelector("td[title]");
  218. if (!dateCell) continue;
  219. const title = dateCell.getAttribute("title") || "";
  220. const match = title.match(/^(\d{4})年(\d{1,2})月(\d{1,2})$/);
  221. if (match) {
  222. startDate = `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
  223. break;
  224. }
  225. }
  226. let totalWeeks = null;
  227. for (const row of rows) {
  228. const firstTd = row.querySelector("td");
  229. if (!firstTd) continue;
  230. const n = parseInt((firstTd.textContent || "").trim(), 10);
  231. if (!isNaN(n) && n > 0) {
  232. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  233. }
  234. }
  235. if (totalWeeks !== null && totalWeeks < 8) totalWeeks = null;
  236. return { startDate: startDate, totalWeeks: totalWeeks };
  237. }
  238. async function fetchCourses(semesterId) {
  239. const html = await requestCoursePage(semesterId);
  240. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  241. }
  242. async function saveAppConfig(semesterStartDate, totalWeeks) {
  243. try {
  244. const config = {
  245. "semesterTotalWeeks": totalWeeks || 20,
  246. "firstDayOfWeek": 1
  247. };
  248. if (semesterStartDate) {
  249. config.semesterStartDate = semesterStartDate;
  250. }
  251. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  252. return true;
  253. } catch (error) {
  254. window.shiguangBridge.showToast("课表配置导入失败,已跳过。");
  255. return false;
  256. }
  257. }
  258. async function saveAppTimeSlots() {
  259. const slots = [
  260. { "number": 1, "startTime": "08:00", "endTime": "08:45" },
  261. { "number": 2, "startTime": "08:55", "endTime": "09:40" },
  262. { "number": 3, "startTime": "10:00", "endTime": "10:45" },
  263. { "number": 4, "startTime": "10:55", "endTime": "11:40" },
  264. { "number": 5, "startTime": "14:30", "endTime": "15:15" },
  265. { "number": 6, "startTime": "15:25", "endTime": "16:10" },
  266. { "number": 7, "startTime": "16:20", "endTime": "17:05" },
  267. { "number": 8, "startTime": "17:15", "endTime": "18:00" },
  268. { "number": 9, "startTime": "18:40", "endTime": "19:25" },
  269. { "number": 10, "startTime": "19:35", "endTime": "20:20" },
  270. { "number": 11, "startTime": "20:30", "endTime": "21:15" },
  271. { "number": 12, "startTime": "21:25", "endTime": "22:10" }
  272. ];
  273. try {
  274. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
  275. return true;
  276. } catch (error) {
  277. window.shiguangBridge.showToast("作息导入失败,已跳过。");
  278. return false;
  279. }
  280. }
  281. async function runImportFlow() {
  282. try {
  283. const confirmed = await window.shiguangBridgePromise.showAlert(
  284. "提示",
  285. "请确保已成功登录教务系统。是否开始导入?",
  286. "开始"
  287. );
  288. if (!confirmed) return;
  289. window.shiguangBridge.showToast("正在获取学期列表...");
  290. const { list: semesters, defaultIndex } = await fetchSemesterList();
  291. if (!semesters || semesters.length === 0) {
  292. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  293. return;
  294. }
  295. const labels = semesters.map(s => s.label);
  296. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  297. "选择学期", JSON.stringify(labels), defaultIndex
  298. );
  299. if (selectedIndex === null || selectedIndex === undefined || selectedIndex < 0) return;
  300. const semesterId = semesters[selectedIndex].value;
  301. window.shiguangBridge.showToast("正在获取学期信息...");
  302. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  303. window.shiguangBridge.showToast("正在请求课程数据...");
  304. const finalCourses = await fetchCourses(semesterId);
  305. if (finalCourses.length === 0) {
  306. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  307. return;
  308. }
  309. await saveAppConfig(semesterStartDate, totalWeeks);
  310. await saveAppTimeSlots();
  311. let saved = false;
  312. try {
  313. saved = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  314. } catch (saveError) {
  315. saved = false;
  316. }
  317. if (saved !== true) {
  318. window.shiguangBridge.showToast("课程导入失败,请重试。");
  319. return;
  320. }
  321. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  322. window.shiguangBridge.notifyTaskCompletion();
  323. } catch (error) {
  324. window.shiguangBridge.showToast("异常: " + (error && error.message ? error.message : error));
  325. }
  326. }
  327. runImportFlow();