swu.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // 西南大学(swu.edu.cn) 拾光课程表适配脚本
  2. // 基于正方新一代教务系统接口适配
  3. // 维护者:小漫君(xiaomanjun233)
  4. // 出现问题请提issues或者提交pr更改,这更加快速
  5. //
  6. // 通过正方接口 xskbcx_cxXsgrkb 拉取个人课表 JSON(kbList),解析课程名、教师、教室、
  7. // 星期、节次和周次(含单双周)。集中实践课(军训、毕业设计等)无星期节次,直接忽略不导入。
  8. // 交互上自动读取教务系统的学年/学期下拉列表,用户只需依次点选即可,无需手动输入。
  9. // 通过 xskbcx_cxXskbcxIndex 读取学年学期选项、xskbcxZccx_cxZcByXnxq 取所选学期开学日期;
  10. // 导入课程、课表配置与西南大学 14 节节次时间。
  11. //
  12. // 使用方式:从办事大厅(i.swu.edu.cn)登录后进入教务系统(jw.swu.edu.cn/jwglxt)课表查询页面,再执行导入。
  13. /**
  14. * 解析周次字符串,处理单双周和周次范围。
  15. */
  16. function parseWeeks(weekStr) {
  17. if (!weekStr) return [];
  18. const weekSets = weekStr.split(',');
  19. let weeks = [];
  20. for (const set of weekSets) {
  21. const trimmedSet = set.trim();
  22. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  23. const singleMatch = trimmedSet.match(/^(\d+)周/); // 匹配以数字周结束的
  24. let start = 0;
  25. let end = 0;
  26. let processed = false;
  27. if (rangeMatch) { // 范围, 如 "1-5周"
  28. start = Number(rangeMatch[1]);
  29. end = Number(rangeMatch[2]);
  30. processed = true;
  31. } else if (singleMatch) { // 单个周, 如 "6周"
  32. start = end = Number(singleMatch[1]);
  33. processed = true;
  34. }
  35. if (processed) {
  36. // 确定单双周
  37. const isSingle = trimmedSet.includes('(单)');
  38. const isDouble = trimmedSet.includes('(双)');
  39. for (let w = start; w <= end; w++) {
  40. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  41. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  42. weeks.push(w);
  43. }
  44. }
  45. }
  46. // 去重并排序
  47. return [...new Set(weeks)].sort((a, b) => a - b);
  48. }
  49. /**
  50. * 拼接教务系统接口地址。
  51. * 西南大学教务(jw.swu.edu.cn)的正方新一代部署在 /jwglxt 子路径下,
  52. * 接口路径必须带上该前缀;校外经 WebVPN 访问时路径还带有 /http/<hex> 前缀,需保留。
  53. */
  54. function buildApiUrl(path) {
  55. const prefixMatch = window.location.pathname.match(/^\/http\/[0-9a-f]+/i);
  56. const webvpnPrefix = prefixMatch ? prefixMatch[0] : "";
  57. return window.location.origin + webvpnPrefix + "/jwglxt" + path;
  58. }
  59. /**
  60. * 拼装课程备注。
  61. * xm 只有姓名,kcmc 只有课程名,以下信息只存在于原始字段里,
  62. * 放进备注方便用户核对:重修标记、选课备注(体育项目、微专业等)、周次原文。
  63. */
  64. function buildCourseRemark(rawCourse) {
  65. const parts = [];
  66. const retakeFlag = String(rawCourse.cxbjmc || "").trim();
  67. if (retakeFlag) {
  68. parts.push(retakeFlag);
  69. }
  70. const selectionNote = String(rawCourse.xkbz || "").trim();
  71. if (selectionNote) {
  72. parts.push(selectionNote);
  73. }
  74. const weekDesc = String(rawCourse.zcd || "").trim();
  75. if (weekDesc) {
  76. parts.push(weekDesc);
  77. }
  78. return parts.join(" | ");
  79. }
  80. /**
  81. * 解析 API 返回的 JSON 数据。
  82. */
  83. function parseJsonData(jsonData) {
  84. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  85. // 检查JSON结构:新的数据在 kbList 字段中
  86. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  87. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  88. return [];
  89. }
  90. const rawCourseList = jsonData.kbList;
  91. const finalCourseList = [];
  92. for (const rawCourse of rawCourseList) {
  93. // 关键字段检查:只有 kcmc(课名), xqj(星期), jcs(节次范围), zcd(周次描述) 是排课必需的。
  94. // xm(教师) 与 cdmc(教室) 在实践课、线上课、未排地点的课程上可能为空,
  95. // 缺这两项不影响排课,不能因此丢弃整门课程。
  96. if (!rawCourse.kcmc || !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  97. continue;
  98. }
  99. const weeksArray = parseWeeks(rawCourse.zcd);
  100. // 周次有效性检查
  101. if (weeksArray.length === 0) {
  102. continue;
  103. }
  104. // 解析节次范围,例如 "1-2"
  105. const sectionParts = rawCourse.jcs.split('-');
  106. const startSection = Number(sectionParts[0]);
  107. const endSection = Number(sectionParts[sectionParts.length - 1]);
  108. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  109. // 数字有效性检查
  110. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) || day < 1 || day > 7 || startSection > endSection) {
  111. continue;
  112. }
  113. const remark = buildCourseRemark(rawCourse);
  114. const course = {
  115. name: String(rawCourse.kcmc).trim(),
  116. teacher: String(rawCourse.xm || "").trim(),
  117. position: String(rawCourse.cdmc || "").trim(),
  118. day: day,
  119. startSection: startSection,
  120. endSection: endSection,
  121. weeks: weeksArray
  122. };
  123. if (remark) {
  124. course.remark = remark;
  125. }
  126. finalCourseList.push(course);
  127. }
  128. finalCourseList.sort((a, b) =>
  129. a.day - b.day ||
  130. a.startSection - b.startSection ||
  131. a.name.localeCompare(b.name)
  132. );
  133. console.log(`JS: JSON 数据解析完成,共找到 ${finalCourseList.length} 门课程。`);
  134. return finalCourseList;
  135. }
  136. async function promptUserToStart() {
  137. return await window.shiguangBridgePromise.showAlert(
  138. "西南大学课表导入",
  139. "导入前请确保您已从办事大厅(i.swu.edu.cn)登录并进入教务系统(jw.swu.edu.cn)课表查询页面。",
  140. "好的,开始导入"
  141. );
  142. }
  143. /**
  144. * 从教务系统课表查询页读取学年与学期下拉选项。
  145. * 学年以选中的一项为中心,取前 2 年 + 后 2 年,最多 5 项,避免列表过长。
  146. */
  147. async function fetchAcademicOptions() {
  148. const url = buildApiUrl("/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151");
  149. try {
  150. const response = await fetch(url, {
  151. method: "GET",
  152. credentials: "include"
  153. });
  154. if (!response.ok) {
  155. return null;
  156. }
  157. const htmlText = await response.text();
  158. const doc = new DOMParser().parseFromString(htmlText, "text/html");
  159. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  160. .filter((opt) => opt.value !== "")
  161. .map((opt) => ({
  162. value: opt.value,
  163. text: opt.textContent.trim(),
  164. selected: opt.selected
  165. }));
  166. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  167. .filter((opt) => opt.value !== "")
  168. .map((opt) => ({
  169. value: opt.value,
  170. text: opt.textContent.trim(),
  171. selected: opt.selected
  172. }));
  173. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  174. return null;
  175. }
  176. const defaultSemesterIndex = (() => {
  177. const i = semesterOptions.findIndex((opt) => opt.selected);
  178. return i !== -1 ? i : 0;
  179. })();
  180. const selectedIndex = allYearOptions.findIndex((opt) => opt.selected);
  181. if (selectedIndex === -1) {
  182. return {
  183. yearOptions: allYearOptions.slice(0, 5),
  184. semesterOptions,
  185. defaultYearIndex: 0,
  186. defaultSemesterIndex
  187. };
  188. }
  189. const start = Math.max(0, selectedIndex - 2);
  190. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  191. return {
  192. yearOptions: allYearOptions.slice(start, end),
  193. semesterOptions,
  194. defaultYearIndex: selectedIndex - start,
  195. defaultSemesterIndex
  196. };
  197. } catch (e) {
  198. return null;
  199. }
  200. }
  201. /**
  202. * 让用户依次点选学年与学期(带默认选中项),返回 API 所需的 xnm/xqm 代码。
  203. * 无需手动输入,用户一路点下一步即可。
  204. */
  205. async function selectAcademicYearAndSemester() {
  206. const optionsData = await fetchAcademicOptions();
  207. if (!optionsData) {
  208. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确认登录状态有效。");
  209. return null;
  210. }
  211. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  212. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  213. "选择学年",
  214. JSON.stringify(yearOptions.map((item) => item.text)),
  215. defaultYearIndex
  216. );
  217. if (yearIndex === null || yearIndex === -1) {
  218. return null;
  219. }
  220. const academicYear = yearOptions[yearIndex].value;
  221. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  222. "选择学期",
  223. JSON.stringify(semesterOptions.map((item) => item.text)),
  224. defaultSemesterIndex
  225. );
  226. if (semesterIndex === null || semesterIndex === -1) {
  227. return null;
  228. }
  229. return {
  230. academicYear,
  231. semesterCode: semesterOptions[semesterIndex].value
  232. };
  233. }
  234. /**
  235. * 获取所选学期的开学日期(第 1 周的日期)。
  236. * 该接口按用户所选 xnm/xqm 返回对应学期的周历,能拿到比当前学期更准确的开班日期。
  237. */
  238. async function fetchSemesterStartDate(academicYear, semesterCode) {
  239. const url = buildApiUrl("/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154");
  240. try {
  241. const response = await fetch(url, {
  242. method: "POST",
  243. headers: {
  244. "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
  245. },
  246. body: `xnm=${academicYear}&xqm=${semesterCode}`,
  247. credentials: "include"
  248. });
  249. if (response.ok) {
  250. const json = await response.json();
  251. if (Array.isArray(json) && json.length > 0) {
  252. const firstWeekObj = json.find((item) => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  253. const matchStr = String(firstWeekObj.rq || firstWeekObj.zcrq || firstWeekObj.ksrq || "").match(/(\d{4}-\d{2}-\d{2})/);
  254. if (matchStr) {
  255. return matchStr[1];
  256. }
  257. }
  258. }
  259. } catch (e) {
  260. // 获取失败不影响主流程
  261. }
  262. return null;
  263. }
  264. /**
  265. * 计算课表配置。
  266. *
  267. * 应用侧的 saveCourseConfig 是整体覆盖而非字段级合并:没有传入的字段会被写成模型默认值,
  268. * 其中 semesterStartDate 的默认值是 null,会把用户已经设置好的开学日期清空。
  269. * 所以拿不到真实开学日期时返回 null,由调用方跳过整个配置保存,宁可不写也不要写坏。
  270. */
  271. function buildCourseConfig(courses, startDate, firstDayOfWeek) {
  272. if (!startDate) {
  273. return null;
  274. }
  275. let maxWeek = 0;
  276. for (const course of courses) {
  277. for (const week of course.weeks) {
  278. if (week > maxWeek) {
  279. maxWeek = week;
  280. }
  281. }
  282. }
  283. return {
  284. semesterStartDate: startDate,
  285. // 只增不减:默认 20 周,课表里出现更大的周次时才扩展。
  286. semesterTotalWeeks: Math.max(maxWeek, 20),
  287. firstDayOfWeek: firstDayOfWeek
  288. };
  289. }
  290. /**
  291. * 请求和解析课程数据。
  292. * 并行拉取课表 JSON 与所选学期开学日期。
  293. */
  294. async function fetchAndParseCourses(academicYear, semesterCode) {
  295. window.shiguangBridge.showToast("正在请求课表数据...");
  296. const body = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  297. const url = buildApiUrl("/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151");
  298. const [courseResponse, startDate] = await Promise.all([
  299. fetch(url, {
  300. method: "POST",
  301. headers: {
  302. "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
  303. },
  304. body,
  305. credentials: "include"
  306. }),
  307. fetchSemesterStartDate(academicYear, semesterCode)
  308. ]);
  309. try {
  310. if (!courseResponse.ok) {
  311. throw new Error(`网络请求失败。状态码: ${courseResponse.status} (${courseResponse.statusText})`);
  312. }
  313. const jsonText = await courseResponse.text();
  314. let jsonData;
  315. try {
  316. jsonData = JSON.parse(jsonText);
  317. } catch (e) {
  318. console.error('JS: JSON 解析失败:', e);
  319. window.shiguangBridge.showToast("数据返回格式错误,请确认已进入教务系统(jw.swu.edu.cn)课表查询页面(而非停留在办事大厅门户页),且登录状态有效。");
  320. return null;
  321. }
  322. const courses = parseJsonData(jsonData);
  323. if (courses.length === 0) {
  324. window.shiguangBridge.showToast("未找到任何课程数据,请检查所选学年学期是否正确或本学期无课。");
  325. return null;
  326. }
  327. console.log(`JS: 课程数据解析成功,共找到 ${courses.length} 门课程。`);
  328. // qsxqj: 教务系统设置的一周起始星期几,缺失时按周一处理。
  329. const rawFirstDay = Number(jsonData.qsxqj);
  330. const firstDayOfWeek = (rawFirstDay >= 1 && rawFirstDay <= 7) ? rawFirstDay : 1;
  331. return {
  332. courses,
  333. startDate,
  334. firstDayOfWeek
  335. };
  336. } catch (error) {
  337. window.shiguangBridge.showToast(`请求或解析失败: ${error.message}`);
  338. console.error('JS: Fetch/Parse Error:', error);
  339. return null;
  340. }
  341. }
  342. async function saveCourses(parsedCourses) {
  343. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  344. try {
  345. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  346. return true;
  347. } catch (error) {
  348. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  349. console.error('JS: Save Courses Error:', error);
  350. return false;
  351. }
  352. }
  353. /**
  354. * 只在能拿到真实开学日期时写入课表配置。
  355. * 拿不到就完全不调用 saveCourseConfig —— 应用侧是整体覆盖,
  356. * 传入不含 semesterStartDate 的配置会把用户已设置的开学日期清空。
  357. */
  358. async function saveCourseConfigIfPossible(courses, startDate, firstDayOfWeek) {
  359. const config = buildCourseConfig(courses, startDate, firstDayOfWeek);
  360. if (!config) {
  361. window.shiguangBridge.showToast("未取到本学期开学日期,已跳过课表配置,请在应用内手动设置开学日期。");
  362. console.log("JS: 无可用开学日期,跳过 saveCourseConfig 以保留用户现有配置。");
  363. return;
  364. }
  365. try {
  366. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  367. window.shiguangBridge.showToast(
  368. `课表配置更新成功!开学日期 ${config.semesterStartDate},总周数 ${config.semesterTotalWeeks} 周。`
  369. );
  370. } catch (error) {
  371. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  372. console.error('JS: Save Config Error:', error);
  373. }
  374. }
  375. // 西南大学统一作息时间(14 节,第 5 节 12:10 从中午开始,傍晚 17:50 后为第 11 节)
  376. const SWU_TIME_SLOTS = [
  377. { number: 1, startTime: "08:00", endTime: "08:45" },
  378. { number: 2, startTime: "08:55", endTime: "09:40" },
  379. { number: 3, startTime: "10:00", endTime: "10:45" },
  380. { number: 4, startTime: "10:55", endTime: "11:40" },
  381. { number: 5, startTime: "12:10", endTime: "12:55" },
  382. { number: 6, startTime: "13:05", endTime: "13:50" },
  383. { number: 7, startTime: "14:00", endTime: "14:45" },
  384. { number: 8, startTime: "14:55", endTime: "15:40" },
  385. { number: 9, startTime: "15:50", endTime: "16:35" },
  386. { number: 10, startTime: "16:55", endTime: "17:40" },
  387. { number: 11, startTime: "17:50", endTime: "18:35" },
  388. { number: 12, startTime: "19:20", endTime: "20:05" },
  389. { number: 13, startTime: "20:15", endTime: "21:00" },
  390. { number: 14, startTime: "21:10", endTime: "21:55" },
  391. ];
  392. async function importPresetTimeSlots(timeSlots) {
  393. if (timeSlots.length > 0) {
  394. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  395. try {
  396. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  397. window.shiguangBridge.showToast("预设时间段导入成功!");
  398. } catch (error) {
  399. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  400. console.error('JS: Save Time Slots Error:', error);
  401. }
  402. } else {
  403. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  404. }
  405. }
  406. async function runImportFlow() {
  407. const alertConfirmed = await promptUserToStart();
  408. if (!alertConfirmed) {
  409. window.shiguangBridge.showToast("用户取消了导入。");
  410. return;
  411. }
  412. const selection = await selectAcademicYearAndSemester();
  413. if (selection === null) {
  414. window.shiguangBridge.showToast("导入已取消。");
  415. return;
  416. }
  417. console.log(`JS: 已选择学年学期: ${selection.academicYear}/${selection.semesterCode}`);
  418. const result = await fetchAndParseCourses(selection.academicYear, selection.semesterCode);
  419. if (result === null) {
  420. console.log("JS: 课程获取或解析失败,流程终止。");
  421. return;
  422. }
  423. const { courses, startDate, firstDayOfWeek } = result;
  424. const saveResult = await saveCourses(courses);
  425. if (!saveResult) {
  426. console.log("JS: 课程保存失败,流程终止。");
  427. return;
  428. }
  429. await saveCourseConfigIfPossible(courses, startDate, firstDayOfWeek);
  430. await importPresetTimeSlots(SWU_TIME_SLOTS);
  431. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  432. console.log("JS: 整个导入流程执行完毕并成功。");
  433. window.shiguangBridge.notifyTaskCompletion();
  434. }
  435. runImportFlow();