ujs_yjs_v1.0.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. // 江苏大学(ujs.edu.cn)研究生管理系统 拾光课程表适配脚本
  2. // 基于正方研究生管理系统(研究生版 Gmis / pyxx)适配
  3. // 出现问题请联系作者或者提交直接pr更改,这更加快速
  4. // 作者:洛初 Github@gongfuture
  5. // 2026.09.10 第一版
  6. // 研究生系统没有对外直连入口,需先经统一身份认证(ehall 门户或 http://yjsgll.ujs.edu.cn/pyxx/)登录。
  7. // 课表从学生课表查询页 pygl/kbcx_xs.aspx 的 DataGrid 里解析:
  8. // 单元格文本自带「第3-18周 单双周:星期二 上3,4 星期五 上1,2」,星期、节次、周次都能直接取到。
  9. // 作息时间取自课表页下方的作息表(上午/下午/晚上),由服务端按当前令时渲染,脚本原样导入,
  10. // 因此不再像本科脚本那样询问夏令时/冬令时,也不做楼栋匹配(研究生系统全校一套作息)。(后续看十一再调整)
  11. // 开学日期:研究生系统没有校历接口,改用「我的课表」接口 App_Ajax/GetkcHandler.ashx 逐周回查,
  12. // 找到某门课第一次出现的日期,再按(起始周-1)*7+(星期-1)反推开学日期;反推不到则跳过配置保存。
  13. /**
  14. * 数组过滤(原生实现)。
  15. * 部分教务页面会改写 Array.prototype.filter,这里用普通循环自行实现,不依赖被改写过的数组方法。
  16. */
  17. function arrayFilter(arr, predicate) {
  18. const result = [];
  19. for (let i = 0; i < arr.length; i++) {
  20. if (predicate(arr[i], i, arr)) {
  21. result.push(arr[i]);
  22. }
  23. }
  24. return result;
  25. }
  26. /**
  27. * 拼接教务系统接口地址。
  28. * 校内直连时 location.origin 就是教务域名,前缀为空;
  29. * 校外经 WebVPN 访问时路径带有 /http/<hex> 前缀,必须保留,否则会变成跨域请求。
  30. */
  31. function buildApiUrl(path) {
  32. const prefixMatch = window.location.pathname.match(/^\/http\/[0-9a-f]+/i);
  33. const prefix = prefixMatch ? prefixMatch[0] : "";
  34. return window.location.origin + prefix + path;
  35. }
  36. /**
  37. * 当前是否在研究生管理系统内。
  38. * 校内直连域名是 yjsgll.ujs.edu.cn,校外经 WebVPN 时是 webvpn.ujs.edu.cn/http/<hex>/pyxx/。
  39. */
  40. function isGraduateSystemPage() {
  41. const host = window.location.hostname;
  42. if (host.indexOf("yjsgll.ujs.edu.cn") !== -1) return true;
  43. return /\/http\/[0-9a-f]+\/pyxx\//i.test(window.location.pathname);
  44. }
  45. /**
  46. * 是否停在登录页。
  47. * 未登录访问会被重定向到统一身份认证 https://pass.ujs.edu.cn/cas/login?service=.../pyxx/loginCAS.aspx。
  48. */
  49. function isLoginPage() {
  50. const host = window.location.hostname;
  51. if (host.indexOf("pass.ujs.edu.cn") !== -1) return true;
  52. return window.location.pathname.indexOf("/cas/login") !== -1;
  53. }
  54. /**
  55. * 解析周次文本,返回周次数组。
  56. * 研究生系统的写法是「第3-18周」,也可能出现「第3周」;
  57. * 单双周标记要先把「单双周」这个词本身剔掉,否则会被误判成单周。
  58. */
  59. function parseWeeks(weekText) {
  60. if (!weekText) return [];
  61. const cleaned = String(weekText).replace(/单双周/g, "");
  62. const oddOnly = cleaned.indexOf("单") !== -1;
  63. const evenOnly = cleaned.indexOf("双") !== -1;
  64. const weeks = [];
  65. const rangePattern = /(\d+)\s*-\s*(\d+)\s*周|(\d+)\s*周/g;
  66. let match;
  67. while ((match = rangePattern.exec(cleaned)) !== null) {
  68. const start = Number(match[1] || match[3]);
  69. const end = match[2] ? Number(match[2]) : start;
  70. for (let week = start; week <= end; week++) {
  71. if (oddOnly && week % 2 === 0) continue;
  72. if (evenOnly && week % 2 !== 0) continue;
  73. weeks.push(week);
  74. }
  75. }
  76. return Array.from(new Set(weeks)).sort((a, b) => a - b);
  77. }
  78. /**
  79. * 节次与周次合并去重(参考官方 wiki 课程合并与去重函数)。
  80. * 课表里同一门课的每个上课时段都会重复一份完整文本,
  81. * 解析后会得到多条完全相同的记录,这里统一合并/去重。
  82. */
  83. function mergeAndDistinctCourses(courses) {
  84. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  85. const list = courses.map(c => ({
  86. ...c,
  87. name: c.name || "",
  88. teacher: c.teacher || "",
  89. position: c.position || "",
  90. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  91. }));
  92. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  93. list.sort((a, b) => {
  94. return a.name.localeCompare(b.name) ||
  95. a.teacher.localeCompare(b.teacher) ||
  96. a.position.localeCompare(b.position) ||
  97. (a.day || 0) - (b.day || 0) ||
  98. a.weeks.join(",").localeCompare(b.weeks.join(",")) ||
  99. (a.startSection || 0) - (b.startSection || 0);
  100. });
  101. const step1Merged = [];
  102. let current = list[0];
  103. for (let i = 1; i < list.length; i++) {
  104. const next = list[i];
  105. const isSameCourseAndWeeks =
  106. current.name === next.name &&
  107. current.teacher === next.teacher &&
  108. current.position === next.position &&
  109. current.day === next.day &&
  110. current.weeks.join(",") === next.weeks.join(",");
  111. const isContinuous = current.endSection + 1 === next.startSection;
  112. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  113. if (isSameCourseAndWeeks && isContinuous) {
  114. current.endSection = next.endSection;
  115. } else if (isSameCourseAndWeeks && isDuplicate) {
  116. continue;
  117. } else {
  118. step1Merged.push(current);
  119. current = next;
  120. }
  121. }
  122. step1Merged.push(current);
  123. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  124. step1Merged.sort((a, b) => {
  125. return a.name.localeCompare(b.name) ||
  126. a.teacher.localeCompare(b.teacher) ||
  127. a.position.localeCompare(b.position) ||
  128. (a.day || 0) - (b.day || 0) ||
  129. (a.startSection || 0) - (b.startSection || 0) ||
  130. (a.endSection || 0) - (b.endSection || 0);
  131. });
  132. const step2Merged = [];
  133. let cur = step1Merged[0];
  134. for (let i = 1; i < step1Merged.length; i++) {
  135. const nxt = step1Merged[i];
  136. const isSameCourseAndSection =
  137. cur.name === nxt.name &&
  138. cur.teacher === nxt.teacher &&
  139. cur.position === nxt.position &&
  140. cur.day === nxt.day &&
  141. cur.startSection === nxt.startSection &&
  142. cur.endSection === nxt.endSection;
  143. if (isSameCourseAndSection) {
  144. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  145. } else {
  146. step2Merged.push(cur);
  147. cur = nxt;
  148. }
  149. }
  150. step2Merged.push(cur);
  151. return step2Merged;
  152. }
  153. /**
  154. * 取单元格文本。
  155. * 课表每个格子里是 <br> 分行的文本,DOMParser 解析出来的文档没有 innerText,
  156. * 先把 <br> 换成换行再取 textContent。
  157. */
  158. function readCellText(cell) {
  159. const clone = cell.cloneNode(true);
  160. Array.from(clone.querySelectorAll("br")).forEach(br => br.replaceWith("\n"));
  161. return clone.textContent.replace(/ /g, " ").replace(/\r/g, "");
  162. }
  163. /**
  164. * 把「上3,4」「晚9,10,11」里的节次换算成全天连续节次。
  165. * 研究生系统文本里的节次就是全天连续编号(晚上从 9 开始),
  166. * 但个别部署可能写成段内编号(下1,2 / 晚1,2,3),这里两种写法都兼容。
  167. */
  168. function normalizeSection(periodPrefix, number) {
  169. if (periodPrefix === "下") return number <= 4 ? number + 4 : number;
  170. if (periodPrefix === "晚") return number <= 3 ? number + 8 : number;
  171. return number;
  172. }
  173. const CHINESE_WEEKDAY_MAP = {
  174. "一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "日": 7, "天": 7
  175. };
  176. /**
  177. * 解析一个课表单元格的文本。
  178. * 典型内容:
  179. * 课程:ESP(专门用途英语)
  180. * 班级:ESP(专门用途英语)5班理工
  181. * (Y206(M) )
  182. * 第3-18周 单双周:星期二 上3,4 星期五 上1,2
  183. * 主讲教师:史莹娟
  184. * 一门课在同一格里会列出全部上课时段(上面的例子就是周二 + 周五两段),
  185. * 所以一个单元格可能产出多条课程记录。
  186. */
  187. function parseCourseCellText(text) {
  188. const lines = String(text).split("\n").map(line => line.trim()).filter(line => line.length > 0);
  189. let name = "";
  190. let className = "";
  191. let teacher = "";
  192. let position = "";
  193. let scheduleLine = "";
  194. for (const line of lines) {
  195. if (/^课程[::]/.test(line)) {
  196. name = line.replace(/^课程[::]\s*/, "").trim();
  197. continue;
  198. }
  199. if (/^班级[::]/.test(line)) {
  200. className = line.replace(/^班级[::]\s*/, "").trim();
  201. continue;
  202. }
  203. if (/^主讲教师[::]/.test(line)) {
  204. teacher = line.replace(/^主讲教师[::]\s*/, "").trim();
  205. continue;
  206. }
  207. if (/^[((].*[))]$/.test(line)) {
  208. // 教室整行被括号包住,去掉最外层括号(教室内名可能自带括号,如 Y206(M))
  209. position = line.replace(/^[((]/, "").replace(/[))]$/, "").trim();
  210. continue;
  211. }
  212. if (line.indexOf("周") !== -1) {
  213. scheduleLine = scheduleLine ? `${scheduleLine} ${line}` : line;
  214. }
  215. }
  216. // 名称、周次、上课时段是排课必需的,缺一不可
  217. if (!name || !scheduleLine) return [];
  218. const weeks = parseWeeks(scheduleLine);
  219. if (weeks.length === 0) return [];
  220. const sessionPattern = /星期([一二三四五六日天])\s*([上下晚])\s*([0-9,,、\s]+)/g;
  221. const records = [];
  222. let match;
  223. while ((match = sessionPattern.exec(scheduleLine)) !== null) {
  224. const day = CHINESE_WEEKDAY_MAP[match[1]];
  225. if (!day) continue;
  226. const numbers = arrayFilter(
  227. match[3].split(/[^0-9]+/).map(item => Number(item)),
  228. (item) => !isNaN(item) && item > 0
  229. );
  230. if (numbers.length === 0) continue;
  231. const sections = numbers.map(number => normalizeSection(match[2], number)).sort((a, b) => a - b);
  232. const startSection = sections[0];
  233. const endSection = sections[sections.length - 1];
  234. if (startSection < 1 || endSection > 20) continue;
  235. const remarkParts = [];
  236. if (className) remarkParts.push(`班级:${className}`);
  237. if (scheduleLine) remarkParts.push(scheduleLine.trim());
  238. records.push({
  239. name: name,
  240. teacher: teacher,
  241. position: position,
  242. day: day,
  243. startSection: startSection,
  244. endSection: endSection,
  245. weeks: weeks,
  246. remark: remarkParts.join(" | ")
  247. });
  248. }
  249. return records;
  250. }
  251. /**
  252. * 解析课表页 #MainWork_DataGrid1 里的全部课程。
  253. * 每个单元格自带完整文本(含星期、节次、周次),不必按表格行列还原,
  254. * 重复出现的记录交给 mergeAndDistinctCourses 去重。
  255. */
  256. function parseCoursesFromGrid(doc) {
  257. const grid = doc.querySelector("#MainWork_DataGrid1");
  258. if (!grid) return [];
  259. const courses = [];
  260. for (const cell of Array.from(grid.querySelectorAll("td"))) {
  261. const text = readCellText(cell);
  262. if (text.indexOf("课程") === -1) continue;
  263. courses.push(...parseCourseCellText(text));
  264. }
  265. return mergeAndDistinctCourses(courses);
  266. }
  267. /**
  268. * 解析课表页下方的作息表,得到按全天连续编号的预设时间段。
  269. * 上午 dgListSw / 下午 dgListXw / 晚上 dgListWs 三张表,
  270. * 每行形如「第一节课 8:00-8:45」;编号按上午、下午、晚上依次顺延,
  271. * 与课表文本里的连续节次编号一致。
  272. */
  273. function parseTimeSlots(doc) {
  274. const groups = [
  275. { id: "#MainWork_dgListSw", label: "上午" },
  276. { id: "#MainWork_dgListXw", label: "下午" },
  277. { id: "#MainWork_dgListWs", label: "晚上" }
  278. ];
  279. const slots = [];
  280. let number = 1;
  281. for (const group of groups) {
  282. const table = doc.querySelector(group.id);
  283. if (!table) continue;
  284. for (const cell of Array.from(table.querySelectorAll("td"))) {
  285. // 作息表是「单元格里再套一层表」的结构,外层单元格的 textContent 也含时间,
  286. // 这里只取最内层单元格,避免同一条时间被重复计数。
  287. if (cell.querySelector("table")) continue;
  288. const match = cell.textContent.match(/(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})/);
  289. if (!match) continue;
  290. const pad = (value) => String(value).padStart(2, "0");
  291. slots.push({
  292. number: number,
  293. startTime: `${pad(match[1])}:${match[2]}`,
  294. endTime: `${pad(match[3])}:${match[4]}`
  295. });
  296. number += 1;
  297. }
  298. }
  299. return slots;
  300. }
  301. /**
  302. * 读取下拉框当前选中项的值。
  303. * DOMParser 解析出的文档不一定支持 select.value,这里按 selected 属性自行判断。
  304. */
  305. function getSelectedOptionValue(select) {
  306. if (!select || !select.options || select.options.length === 0) return "";
  307. for (const option of Array.from(select.options)) {
  308. if (option.hasAttribute("selected")) return option.value;
  309. }
  310. return select.options[0].value;
  311. }
  312. /**
  313. * 收集表单里可提交的字段,模拟一次完整回发。
  314. * ASP.NET 的 __VIEWSTATE 等方法不能少,逐个手写容易漏,这里整体搬运后按需覆盖。
  315. */
  316. function collectPostbackFields(doc, overrides) {
  317. const params = new URLSearchParams();
  318. const form = doc.querySelector("#form1") || doc.querySelector("form");
  319. if (!form) return params;
  320. for (const el of Array.from(form.querySelectorAll("input[name], select[name], textarea[name]"))) {
  321. const tag = el.tagName.toLowerCase();
  322. const name = el.getAttribute("name");
  323. if (!name) continue;
  324. if (tag === "select") {
  325. params.set(name, getSelectedOptionValue(el));
  326. continue;
  327. }
  328. const type = (el.getAttribute("type") || "text").toLowerCase();
  329. if (type === "submit" || type === "image" || type === "button" || type === "reset") {
  330. // 图片按钮/提交按钮需要 .x / .y,或者完全不提交,这里跳过由调用方补充
  331. continue;
  332. }
  333. if (type === "checkbox" || type === "radio") {
  334. if (!el.hasAttribute("checked")) continue;
  335. }
  336. params.set(name, el.getAttribute("value") || "");
  337. }
  338. Object.keys(overrides || {}).forEach(key => params.set(key, overrides[key]));
  339. return params;
  340. }
  341. /**
  342. * 以 form 表单方式回发并返回响应 HTML。
  343. */
  344. async function postForm(url, params) {
  345. const response = await fetch(url, {
  346. method: "POST",
  347. headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
  348. body: params.toString(),
  349. credentials: "include"
  350. });
  351. if (!response.ok) {
  352. throw new Error(`回发失败,状态码 ${response.status}`);
  353. }
  354. return await response.text();
  355. }
  356. /**
  357. * 读取指定学期的课表页文档。
  358. * 课表页默认渲染系统当前学期;要查历史/其它学期得按页面自身的逻辑回发两次:
  359. * 先把学期下拉框回发一次(换出新的 __VIEWSTATE),再点一次「查询」按钮重新绑定课表。
  360. * @param {string} semesterValue 学期下拉框的 value,为空表示用默认(当前)学期
  361. */
  362. async function fetchTimetableDocument(semesterValue) {
  363. const url = buildApiUrl("/pyxx/pygl/kbcx_xs.aspx");
  364. const pageResponse = await fetch(url, { method: "GET", credentials: "include" });
  365. const pageDoc = new DOMParser().parseFromString(await pageResponse.text(), "text/html");
  366. const semesterSelect = pageDoc.querySelector("#MainWork_drpxq");
  367. if (!semesterSelect) {
  368. throw new Error("NOT_LOGGED_IN");
  369. }
  370. const currentValue = getSelectedOptionValue(semesterSelect);
  371. if (!semesterValue || semesterValue === currentValue) {
  372. return pageDoc;
  373. }
  374. // 第一步:学期下拉框回发,拿到与新选中项对应的 __VIEWSTATE
  375. const firstParams = collectPostbackFields(pageDoc, {
  376. "__EVENTTARGET": "ctl00$MainWork$drpxq",
  377. "__EVENTARGUMENT": "",
  378. "ctl00$MainWork$drpxq": semesterValue
  379. });
  380. const afterChangeDoc = new DOMParser().parseFromString(await postForm(url, firstParams), "text/html");
  381. // 第二步:点「查询」按钮,课表才按新学期的选项重新绑定
  382. const secondParams = collectPostbackFields(afterChangeDoc, {
  383. "__EVENTTARGET": "",
  384. "__EVENTARGUMENT": "",
  385. "ctl00$MainWork$drpxq": semesterValue,
  386. "ctl00$MainWork$btnSearch.x": "5",
  387. "ctl00$MainWork$btnSearch.y": "5"
  388. });
  389. const resultDoc = new DOMParser().parseFromString(await postForm(url, secondParams), "text/html");
  390. if (!resultDoc.querySelector("#MainWork_DataGrid1")) {
  391. throw new Error("POSTBACK_FAILED");
  392. }
  393. return resultDoc;
  394. }
  395. /**
  396. * 读取学期下拉框的全部选项。
  397. */
  398. function readSemesterOptions(doc) {
  399. const select = doc.querySelector("#MainWork_drpxq");
  400. if (!select) return null;
  401. const options = Array.from(select.options)
  402. .map(option => ({
  403. value: option.value,
  404. text: option.textContent.trim(),
  405. selected: option.hasAttribute("selected")
  406. }))
  407. .filter(option => option.text);
  408. if (options.length === 0) return null;
  409. let defaultIndex = options.findIndex(option => option.selected);
  410. if (defaultIndex === -1) defaultIndex = 0;
  411. return { options: options, defaultIndex: defaultIndex };
  412. }
  413. function formatDate(date) {
  414. const pad = (value) => String(value).padStart(2, "0");
  415. return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
  416. }
  417. function addDays(date, days) {
  418. const result = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  419. result.setDate(result.getDate() + days);
  420. return result;
  421. }
  422. /**
  423. * 查询某天「我的课表」接口,判断目标课程当天是否上课。
  424. * App_Ajax/GetkcHandler.ashx 是首页「我的课表」按日期查询用的接口,
  425. * 传入日期就返回当天课程,可以用来反推开学日期。
  426. */
  427. async function hasCourseOn(date, courseName, studentId) {
  428. const url = buildApiUrl(
  429. `/pyxx/App_Ajax/GetkcHandler.ashx?kcdate=${formatDate(date)}&xh=${encodeURIComponent(studentId)}`
  430. );
  431. const response = await fetch(url, { method: "GET", credentials: "include" });
  432. if (!response.ok) return false;
  433. const doc = new DOMParser().parseFromString(await response.text(), "text/html");
  434. const text = (doc.body ? doc.body.textContent : "").replace(/\s+/g, "");
  435. return text.indexOf(String(courseName).replace(/\s+/g, "")) !== -1;
  436. }
  437. /**
  438. * 找到参照日期:距离今天最近的一个「目标星期」的日期(今天或之前)。
  439. * 星期编号 1-7 对应周一到周日。
  440. */
  441. function findReferenceDate(day) {
  442. const today = new Date();
  443. const jsDay = today.getDay(); // 0=周日
  444. const todayDay = jsDay === 0 ? 7 : jsDay;
  445. let diff = todayDay - day;
  446. if (diff < 0) diff += 7;
  447. return addDays(today, -diff);
  448. }
  449. /**
  450. * 挑选用于探测的课程:起始周最早、周次跨度最短的那门,
  451. * 跨度短意味着要核对的周次少。
  452. */
  453. function pickProbeCourse(courses) {
  454. let best = null;
  455. for (const course of courses) {
  456. if (!course.weeks || course.weeks.length === 0) continue;
  457. const weeks = course.weeks;
  458. const span = weeks[weeks.length - 1] - weeks[0];
  459. if (!best ||
  460. weeks[0] < best.weeks[0] ||
  461. (weeks[0] === best.weeks[0] && span < best.span)) {
  462. best = { name: course.name, day: course.day, weeks: weeks, span: span };
  463. }
  464. }
  465. return best;
  466. }
  467. /**
  468. * 反推本学期开学日期。
  469. *
  470. * 研究生系统没有校历接口,只能借「我的课表」接口逐周回查:
  471. * 以目标课程所在星期的最近一个日期为参照,按周展开探测(区间大约覆盖前后一个学期),
  472. * 再把每个命中日期当作「该课第一次上课的那天」,用课程自己的周次表去核对:
  473. * 前一周必须没课,且课程周次表里的每一周都应当对得上。
  474. * 核对通过后,开学日期 = 首次上课日期 - ((起始周 - 1) * 7 + (星期 - 1)),按周一为一周之始。
  475. *
  476. * 校验通过多个候选时取离今天最近的那个,避免把上一学年的同名课程认成本学期。
  477. * 任何一步拿不到结果就返回 null,由调用方跳过配置保存。
  478. */
  479. async function deriveSemesterStartDate(courses, studentId) {
  480. if (!studentId) {
  481. console.warn("JS: 未取到学号,跳过开学日期推算。");
  482. return null;
  483. }
  484. const target = pickProbeCourse(courses);
  485. if (!target) {
  486. console.warn("JS: 没有可用于探测的课程,跳过开学日期推算。");
  487. return null;
  488. }
  489. const reference = findReferenceDate(target.day);
  490. const maxBackWeeks = 40;
  491. const maxForwardWeeks = 12;
  492. const offsets = [0];
  493. for (let week = 1; week <= maxBackWeeks; week++) {
  494. offsets.push(-week);
  495. if (week <= maxForwardWeeks) offsets.push(week);
  496. }
  497. const observed = new Map();
  498. const batchSize = 2;
  499. let hitBatchIndex = -1;
  500. for (let index = 0; index < offsets.length; index += batchSize) {
  501. const batch = offsets.slice(index, index + batchSize);
  502. const results = await Promise.all(
  503. batch.map(async offset => ({
  504. offset: offset,
  505. hit: await hasCourseOn(addDays(reference, offset * 7), target.name, studentId)
  506. }))
  507. );
  508. for (const item of results) {
  509. observed.set(item.offset, item.hit);
  510. }
  511. if (hitBatchIndex === -1 && results.some(item => item.hit)) {
  512. hitBatchIndex = index / batchSize;
  513. }
  514. // 找到命中后再多探一批,够核对课程周次就够了,不必把整个区间探完
  515. if (hitBatchIndex !== -1 && index / batchSize > hitBatchIndex) {
  516. break;
  517. }
  518. // 稍作等待防止风控
  519. const delay = 300 + Math.floor(Math.random() * 200);
  520. await new Promise(resolve => setTimeout(resolve, delay));
  521. }
  522. const hitOffsets = Array.from(observed.keys())
  523. .filter(offset => observed.get(offset))
  524. .sort((a, b) => Math.abs(a) - Math.abs(b) || a - b);
  525. if (hitOffsets.length === 0) {
  526. console.warn(`JS: 前后约一个学期内未探到课程「${target.name}」,跳过开学日期推算。`);
  527. return null;
  528. }
  529. const firstWeek = target.weeks[0];
  530. // 单双周课程每隔一周才上课,用课程自己的周次间隔做「上一次课」的核对距离,
  531. // 否则会把「课程中途的某一次课」误判成起始周(相邻一周本来就该没课)。
  532. const weekStep = target.weeks.length > 1 ? target.weeks[1] - target.weeks[0] : 1;
  533. for (const candidate of hitOffsets) {
  534. // 起始周之前的那一次课必须没有课,否则这个候选只是课程中途的一次课
  535. if (observed.get(candidate - weekStep) === true) continue;
  536. // 用课程自己的周次表核对:课程上课的每一周都应探到课
  537. let consistent = true;
  538. let checked = 0;
  539. for (const week of target.weeks) {
  540. const offset = candidate + (week - firstWeek);
  541. const seen = observed.get(offset);
  542. if (seen === undefined) continue;
  543. checked += 1;
  544. if (!seen) {
  545. consistent = false;
  546. break;
  547. }
  548. }
  549. if (!consistent || checked < 1) continue;
  550. const firstClassDate = addDays(reference, candidate * 7);
  551. const startDate = addDays(firstClassDate, -((firstWeek - 1) * 7 + (target.day - 1)));
  552. // 推算出的开学日期必须是周一,否则说明数据对不上,宁可不写
  553. if (startDate.getDay() !== 1) continue;
  554. console.log(`JS: 探测课程「${target.name}」首次上课日期 ${formatDate(firstClassDate)}(第 ${firstWeek} 周),推算开学日期 ${formatDate(startDate)}。`);
  555. return formatDate(startDate);
  556. }
  557. console.warn(`JS: 课程「${target.name}」的探测结果与周次表对不上,跳过开学日期推算。`);
  558. return null;
  559. }
  560. /**
  561. * 计算本学期总周数:取所有课程周次的最大值。
  562. * 研究生系统没有校历,这个值只是课表的周次上限,多算几周无空白无妨,少算会截断课程。
  563. */
  564. function calculateTotalWeeks(courses) {
  565. let maxWeek = 0;
  566. for (const course of courses) {
  567. for (const week of course.weeks) {
  568. if (week > maxWeek) maxWeek = week;
  569. }
  570. }
  571. return maxWeek;
  572. }
  573. async function promptUserToStart() {
  574. return await window.shiguangBridgePromise.showAlert(
  575. "研究生系统课表导入",
  576. "导入前请确保您已在浏览器中登录江苏大学研究生管理系统(可从综合服务门户点「研究生管理系统」进入,或直接访问 http://yjsgll.ujs.edu.cn/pyxx/)。",
  577. "好的,开始导入"
  578. );
  579. }
  580. async function saveCourses(parsedCourses) {
  581. try {
  582. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  583. return true;
  584. } catch (error) {
  585. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  586. console.error("JS: Save Courses Error:", error);
  587. return false;
  588. }
  589. }
  590. /**
  591. * 只在能拿到真实开学日期时写入课表配置。
  592. * 应用侧的 saveCourseConfig 是整体覆盖而非字段级合并:没有传入的字段会被写成模型默认值,
  593. * 其中 semesterStartDate 的默认值是 null,会把用户已经设置好的开学日期清空。
  594. * 所以拿不到开学日期时返回 null,宁可不写也不要写坏。
  595. */
  596. async function saveCourseConfigIfPossible(config) {
  597. if (!config) {
  598. window.shiguangBridge.showToast("未取到本学期开学日期,已跳过课表配置,请在应用内手动设置开学日期。");
  599. console.log("JS: 无可用开学日期,跳过 saveCourseConfig 以保留用户现有配置。");
  600. return;
  601. }
  602. try {
  603. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  604. window.shiguangBridge.showToast(
  605. `课表配置更新成功!开学日期 ${config.semesterStartDate},总周数 ${config.semesterTotalWeeks} 周。`
  606. );
  607. } catch (error) {
  608. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  609. console.error("JS: Save Config Error:", error);
  610. }
  611. }
  612. async function importPresetTimeSlots(timeSlots) {
  613. if (timeSlots.length === 0) {
  614. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  615. return;
  616. }
  617. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  618. try {
  619. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  620. } catch (error) {
  621. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  622. console.error("JS: Save Time Slots Error:", error);
  623. }
  624. }
  625. async function runImportFlow() {
  626. if (!isGraduateSystemPage()) {
  627. window.shiguangBridge.showToast("导入失败:请先进入江苏大学研究生管理系统!");
  628. console.log("JS: 当前不在研究生管理系统页面,终止导入。");
  629. return;
  630. }
  631. if (isLoginPage()) {
  632. window.shiguangBridge.showToast("导入失败:请先登录研究生管理系统!");
  633. console.log("JS: 检测到当前在登录页面,终止导入。");
  634. return;
  635. }
  636. const alertConfirmed = await promptUserToStart();
  637. if (!alertConfirmed) {
  638. window.shiguangBridge.showToast("用户取消了导入。");
  639. return;
  640. }
  641. window.shiguangBridge.showToast("正在读取课表数据...");
  642. // 先取一次默认(当前)学期,用于学期列表与课表
  643. let defaultDoc;
  644. try {
  645. defaultDoc = await fetchTimetableDocument("");
  646. } catch (error) {
  647. if (error.message === "NOT_LOGGED_IN") {
  648. window.shiguangBridge.showToast("未登录或登录已过期,请先登录研究生管理系统。");
  649. } else {
  650. window.shiguangBridge.showToast(`读取课表失败: ${error.message}`);
  651. }
  652. console.error("JS: 读取课表页失败:", error);
  653. return;
  654. }
  655. const semesterData = readSemesterOptions(defaultDoc);
  656. if (!semesterData) {
  657. window.shiguangBridge.showToast("未能读取学期列表,请确认已登录并停留在研究生管理系统。");
  658. return;
  659. }
  660. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  661. "选择学期",
  662. JSON.stringify(semesterData.options.map(item => item.text)),
  663. semesterData.defaultIndex
  664. );
  665. if (semesterIndex === null || semesterIndex === -1) {
  666. window.shiguangBridge.showToast("导入已取消。");
  667. return;
  668. }
  669. const semesterValue = semesterData.options[semesterIndex].value;
  670. const semesterText = semesterData.options[semesterIndex].text;
  671. let timetableDoc = defaultDoc;
  672. if (semesterIndex !== semesterData.defaultIndex) {
  673. window.shiguangBridge.showToast(`正在切换到 ${semesterText} ...`);
  674. try {
  675. timetableDoc = await fetchTimetableDocument(semesterValue);
  676. } catch (error) {
  677. window.shiguangBridge.showToast(`切换学期失败: ${error.message}`);
  678. console.error("JS: 切换学期失败:", error);
  679. return;
  680. }
  681. }
  682. const courses = parseCoursesFromGrid(timetableDoc);
  683. if (courses.length === 0) {
  684. window.shiguangBridge.showToast(`${semesterText} 未找到任何课程,请确认所选学期是否正确。`);
  685. console.log("JS: 课表为空,终止导入。");
  686. return;
  687. }
  688. const timeSlots = parseTimeSlots(timetableDoc);
  689. console.log(`JS: 解析到 ${courses.length} 门课程,${timeSlots.length} 个时间段。`);
  690. // 学号取自课表页隐藏域,用来查「我的课表」接口
  691. const studentId = (timetableDoc.querySelector("#MainWork_WUCpyjhdy_HFfilename") || {}).value || "";
  692. window.shiguangBridge.showToast("正在推算开学日期...");
  693. const semesterStartDate = await deriveSemesterStartDate(courses, studentId);
  694. const totalWeeks = calculateTotalWeeks(courses);
  695. const config = semesterStartDate
  696. ? {
  697. semesterStartDate: semesterStartDate,
  698. semesterTotalWeeks: totalWeeks,
  699. firstDayOfWeek: 1
  700. }
  701. : null;
  702. const saveResult = await saveCourses(courses);
  703. if (!saveResult) {
  704. console.log("JS: 课程保存失败,流程终止。");
  705. return;
  706. }
  707. await saveCourseConfigIfPossible(config);
  708. await importPresetTimeSlots(timeSlots);
  709. await window.shiguangBridgePromise.showAlert(
  710. "导入完成",
  711. `已导入 ${semesterText} 共 ${courses.length} 门课程。\n\n` +
  712. `作息时间取自研究生系统课表页当前显示的作息(全天 ${timeSlots.length} 节),` +
  713. "学校切换夏令时/冬令时后请重新导入,或在应用内手动修改时间段。\n\n" +
  714. (semesterStartDate
  715. ? `开学日期由课表数据反推得到:${semesterStartDate},请在应用内核对。`
  716. : "未能反推开学日期,请在应用内手动设置。"),
  717. "我知道了"
  718. );
  719. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  720. console.log("JS: 整个导入流程执行完毕并成功。");
  721. window.shiguangBridge.notifyTaskCompletion();
  722. }
  723. runImportFlow();