xhsysu.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // 广州新华学院 (xhsysu.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统V9标准接口适配(CAS SSO版)
  3. // 课表 POST /kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151 校历 POST /kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154
  4. // 校内直连前缀为空;经 WebVPN 时路径带 /http/<hex> 前缀,需保留
  5. // 校内统一作息(14 节,40 分钟一节,08:20 起),来源:教务处「上课时间段一览表」
  6. const XHSYSU_TIME_SLOTS = [
  7. { number: 1, startTime: "08:20", endTime: "09:00" },
  8. { number: 2, startTime: "09:10", endTime: "09:50" },
  9. { number: 3, startTime: "10:10", endTime: "10:50" },
  10. { number: 4, startTime: "11:00", endTime: "11:40" },
  11. { number: 5, startTime: "11:50", endTime: "12:30" },
  12. { number: 6, startTime: "12:40", endTime: "13:20" },
  13. { number: 7, startTime: "13:30", endTime: "14:10" },
  14. { number: 8, startTime: "14:20", endTime: "15:00" },
  15. { number: 9, startTime: "15:10", endTime: "15:50" },
  16. { number: 10, startTime: "16:10", endTime: "16:50" },
  17. { number: 11, startTime: "17:00", endTime: "17:40" },
  18. { number: 12, startTime: "19:00", endTime: "19:40" },
  19. { number: 13, startTime: "19:50", endTime: "20:30" },
  20. { number: 14, startTime: "20:40", endTime: "21:20" }
  21. ];
  22. // 校内直连前缀为空,WebVPN 需保留 /http/<hex>,否则变成跨域请求
  23. function apiUrl(path) {
  24. const prefix = window.location.pathname.match(/^\/http\/[0-9a-f]+/i);
  25. return window.location.origin + (prefix ? prefix[0] : "") + path;
  26. }
  27. function mergeAndDistinctCourses(courses) {
  28. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  29. const list = courses.map(c => ({
  30. ...c,
  31. name: c.name || '',
  32. teacher: c.teacher || '',
  33. position: c.position || '',
  34. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  35. }));
  36. // 排序键里 weeks 必须先于 startSection,否则同节次不同周次的记录会插进来打断连续节次
  37. list.sort((a, b) => a.name.localeCompare(b.name) || a.teacher.localeCompare(b.teacher) ||
  38. a.position.localeCompare(b.position) || (a.day || 0) - (b.day || 0) ||
  39. a.weeks.join(',').localeCompare(b.weeks.join(',')) || (a.startSection || 0) - (b.startSection || 0));
  40. const step1 = [];
  41. let cur = list[0];
  42. for (let i = 1; i < list.length; i++) {
  43. const nxt = list[i];
  44. const same = cur.name === nxt.name && cur.teacher === nxt.teacher && cur.position === nxt.position &&
  45. cur.day === nxt.day && cur.weeks.join(',') === nxt.weeks.join(',');
  46. if (same && cur.endSection + 1 === nxt.startSection) cur.endSection = nxt.endSection;
  47. else if (same && cur.startSection === nxt.startSection && cur.endSection === nxt.endSection) continue;
  48. else { step1.push(cur); cur = nxt; }
  49. }
  50. step1.push(cur);
  51. // 再按节次排序,把同节次不同周次的记录并到一起
  52. step1.sort((a, b) => a.name.localeCompare(b.name) || a.teacher.localeCompare(b.teacher) ||
  53. a.position.localeCompare(b.position) || (a.day || 0) - (b.day || 0) ||
  54. (a.startSection || 0) - (b.startSection || 0) || (a.endSection || 0) - (b.endSection || 0));
  55. const step2 = [];
  56. cur = step1[0];
  57. for (let i = 1; i < step1.length; i++) {
  58. const nxt = step1[i];
  59. if (cur.name === nxt.name && cur.teacher === nxt.teacher && cur.position === nxt.position &&
  60. cur.day === nxt.day && cur.startSection === nxt.startSection && cur.endSection === nxt.endSection) {
  61. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  62. } else { step2.push(cur); cur = nxt; }
  63. }
  64. step2.push(cur);
  65. return step2.sort((a, b) => a.day - b.day || a.startSection - b.startSection || a.name.localeCompare(b.name));
  66. }
  67. function parseWeeks(weekStr) {
  68. if (!weekStr) return [];
  69. const text = String(weekStr);
  70. const keepOdd = text.includes("单");
  71. const keepEven = text.includes("双");
  72. const weeks = [];
  73. // "周/单/双/第"与括号统一换成分隔符,剩下的就是纯数字或"起-止"
  74. for (const part of text.replace(/[单双第周()()]/g, ",").split(",")) {
  75. const [from, to] = part.split("-").map(Number);
  76. if (!from) continue;
  77. for (let w = from; w <= (to || from); w++) {
  78. if (keepOdd && w % 2 === 0) continue;
  79. if (keepEven && w % 2 !== 0) continue;
  80. weeks.push(w);
  81. }
  82. }
  83. return [...new Set(weeks)].sort((a, b) => a - b);
  84. }
  85. function parseJsonData(jsonData) {
  86. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  87. const list = [];
  88. for (const c of jsonData.kbList) {
  89. if (!c.kcmc || !c.xqj || !c.jcs || !c.zcd) continue;
  90. const weeks = parseWeeks(c.zcd);
  91. if (!weeks.length) continue;
  92. const parts = c.jcs.split('-');
  93. const startSection = Number(parts[0]);
  94. const endSection = Number(parts[parts.length - 1]);
  95. const day = Number(c.xqj);
  96. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) || day < 1 || day > 7 || startSection > endSection) continue;
  97. // cdmc 返回"未排地点"时不是真实教室,置空
  98. const position = String(c.cdmc || "").trim();
  99. list.push({
  100. name: c.kcmc.trim(),
  101. teacher: String(c.xm || "").trim(),
  102. position: position === "未排地点" ? "" : position,
  103. day, startSection, endSection, weeks
  104. });
  105. }
  106. return mergeAndDistinctCourses(list);
  107. }
  108. // CAS 入口为 /lyuapServer/login,登录后跳 /sso/lyiotlogin,WebVPN 下路径含 /http/<hex>
  109. function isLoginPage() {
  110. return window.location.href.includes("lyuapServer/login") ||
  111. window.location.pathname.endsWith("/sso/lyiotlogin");
  112. }
  113. async function promptUserToStart() {
  114. return await window.shiguangBridgePromise.showAlert(
  115. "教务系统课表导入", "导入前请确保您已在浏览器中成功登录广州新华学院教务系统", "好的,开始导入");
  116. }
  117. async function fetchAcademicOptions() {
  118. try {
  119. const resp = await fetch(apiUrl("/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151"), { method: "GET", credentials: "include" });
  120. if (!resp.ok) return null;
  121. const doc = new DOMParser().parseFromString(await resp.text(), "text/html");
  122. const read = sel => Array.from(doc.querySelectorAll(sel + " option")).filter(o => o.value !== "")
  123. .map(o => ({ value: o.value, text: o.textContent.trim(), selected: o.hasAttribute("selected") }));
  124. const years = read("#xnm"), semesters = read("#xqm");
  125. if (!years.length || !semesters.length) return null;
  126. // 学年过多,只取当前选中项前后各 2 项
  127. const selIdx = years.findIndex(o => o.selected);
  128. const start = Math.max(0, (selIdx === -1 ? 0 : selIdx) - 2);
  129. return {
  130. yearOptions: years.slice(start, Math.min(years.length, (selIdx === -1 ? 0 : selIdx) + 3)),
  131. semesterOptions: semesters,
  132. defaultYearIndex: selIdx === -1 ? 0 : selIdx - start,
  133. defaultSemesterIndex: Math.max(0, semesters.findIndex(o => o.selected))
  134. };
  135. } catch (e) { return null; }
  136. }
  137. async function selectAcademicYearAndSemester() {
  138. const data = await fetchAcademicOptions();
  139. if (!data) { window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保已登录。"); return null; }
  140. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = data;
  141. const yearIdx = await window.shiguangBridgePromise.showSingleSelection(
  142. "选择学年", JSON.stringify(yearOptions.map(o => o.text)), defaultYearIndex);
  143. if (yearIdx === null || yearIdx === -1) return null;
  144. const semIdx = await window.shiguangBridgePromise.showSingleSelection(
  145. "选择学期", JSON.stringify(semesterOptions.map(o => o.text)), defaultSemesterIndex);
  146. if (semIdx === null || semIdx === -1) return null;
  147. return { academicYear: yearOptions[yearIdx].value, semesterCode: semesterOptions[semIdx].value };
  148. }
  149. // 校历接口:按周返回数组,zs=周次,rq=该周起止("2026-08-31/2026-09-06")
  150. // 第 1 周周一即开学日期,数组长度为该学期总周数
  151. async function fetchSemesterWeeks(academicYear, semesterCode) {
  152. try {
  153. const resp = await fetch(apiUrl("/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154"), {
  154. method: "POST",
  155. headers: {
  156. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  157. "x-requested-with": "XMLHttpRequest"
  158. },
  159. body: `xnm=${academicYear}&xqm=${semesterCode}`,
  160. credentials: "include"
  161. });
  162. if (!resp.ok) return null;
  163. const json = JSON.parse(await resp.text());
  164. if (!Array.isArray(json) || !json.length) return null;
  165. const first = json.find(i => Number(i.zs) === 1) || json[0];
  166. const startDate = String(first.rq || "").split("/")[0].trim();
  167. if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate)) return null;
  168. return { startDate, totalWeeks: json.length };
  169. } catch (e) { return null; }
  170. }
  171. async function fetchAndParseCourses(academicYear, semesterCode) {
  172. window.shiguangBridge.showToast("正在请求课表数据...");
  173. const [resp, weeks] = await Promise.all([
  174. fetch(apiUrl("/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151"), {
  175. method: "POST",
  176. headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
  177. body: `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`,
  178. credentials: "include"
  179. }),
  180. fetchSemesterWeeks(academicYear, semesterCode)
  181. ]);
  182. try {
  183. if (!resp.ok) throw new Error("状态码 " + resp.status);
  184. const courses = parseJsonData(JSON.parse(await resp.text()));
  185. if (!courses.length) throw new Error("未找到课程数据,请确认所选学年学期正确或教务需要二次登录。");
  186. // 校历周数可能少于课程实际最大周次(实测达 18 周),取较大者避免高位周次被截断
  187. const maxWeek = Math.max(...courses.flatMap(c => c.weeks));
  188. return {
  189. courses,
  190. config: weeks ? {
  191. semesterStartDate: weeks.startDate,
  192. semesterTotalWeeks: Math.max(weeks.totalWeeks, maxWeek)
  193. } : null
  194. };
  195. } catch (e) {
  196. window.shiguangBridge.showToast("导入失败:" + e.message);
  197. console.error("JS: Import Error", e);
  198. return null;
  199. }
  200. }
  201. async function saveCourses(courses) {
  202. try {
  203. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  204. return true;
  205. } catch (e) {
  206. window.shiguangBridge.showToast("课程保存失败: " + e.message);
  207. return false;
  208. }
  209. }
  210. // 应用侧 saveCourseConfig 是整体覆盖,不传 semesterStartDate 会清空用户已设的开学日期,所以只在拿到校历时写入
  211. async function saveConfig(config) {
  212. if (!config) {
  213. window.shiguangBridge.showToast("未取到开学日期,已跳过课表配置,请在应用内手动设置。");
  214. return;
  215. }
  216. try {
  217. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  218. window.shiguangBridge.showToast(`开学日期 ${config.semesterStartDate},共 ${config.semesterTotalWeeks} 周。`);
  219. } catch (e) {
  220. window.shiguangBridge.showToast("课表配置保存失败: " + e.message);
  221. }
  222. }
  223. async function runImportFlow() {
  224. if (isLoginPage()) {
  225. window.shiguangBridge.showToast("导入失败:请先登录教务系统!");
  226. return;
  227. }
  228. if (!await promptUserToStart()) { window.shiguangBridge.showToast("用户取消了导入。"); return; }
  229. const sel = await selectAcademicYearAndSemester();
  230. if (!sel) { window.shiguangBridge.showToast("未选择学年学期,导入终止。"); return; }
  231. const result = await fetchAndParseCourses(sel.academicYear, sel.semesterCode);
  232. if (!result) return;
  233. if (!await saveCourses(result.courses)) return;
  234. await saveConfig(result.config);
  235. try { await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(XHSYSU_TIME_SLOTS)); } catch (e) {}
  236. window.shiguangBridge.showToast("课程导入成功,共导入 " + result.courses.length + " 门课程!");
  237. window.shiguangBridge.notifyTaskCompletion();
  238. }
  239. runImportFlow();