school.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. // 湖北经济学院(hbue.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配(v9 / jwglxt),参考官方推荐案例 JSEI 的接口式方案
  3. // 登录后无需进入课表页面,任意页面点击导入即可,支持选择学年学期、
  4. // 自动获取开学日期与作息时间
  5. // 出现问题请提 issues 或者提交 PR 更改
  6. /**
  7. * 基础域名配置
  8. * 湖北经济学院教务系统(新版正方 v9)
  9. */
  10. const BASE_URL = "https://jwxt.hbue.edu.cn/jwglxt";
  11. function getBaseUrl() {
  12. return BASE_URL;
  13. }
  14. /**
  15. * 节次与周次合并去重函数
  16. * @param {Array<Object>} courses 原始解析课程数组
  17. * @returns {Array<Object>} 合并去重后的课程数组
  18. */
  19. function mergeAndDistinctCourses(courses) {
  20. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  21. // 1. 深拷贝并规范周次数据,过滤无效项
  22. const list = courses.map(c => ({
  23. ...c,
  24. name: c.name || '',
  25. teacher: c.teacher || '',
  26. position: c.position || '',
  27. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  28. }));
  29. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  30. list.sort((a, b) => {
  31. return a.name.localeCompare(b.name) ||
  32. a.teacher.localeCompare(b.teacher) ||
  33. a.position.localeCompare(b.position) ||
  34. (a.day || 0) - (b.day || 0) ||
  35. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  36. (a.startSection || 0) - (b.startSection || 0);
  37. });
  38. const step1Merged = [];
  39. let current = list[0];
  40. for (let i = 1; i < list.length; i++) {
  41. const next = list[i];
  42. const isSameCourseAndWeeks =
  43. current.name === next.name &&
  44. current.teacher === next.teacher &&
  45. current.position === next.position &&
  46. current.day === next.day &&
  47. current.weeks.join(',') === next.weeks.join(',');
  48. const isContinuous = current.endSection + 1 === next.startSection;
  49. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  50. if (isSameCourseAndWeeks && isContinuous) {
  51. // 节次连续:延长结束节次 (如 1-2 节 + 3-4 节 -> 1-4 节)
  52. current.endSection = next.endSection;
  53. } else if (isSameCourseAndWeeks && isDuplicate) {
  54. // 完全重复:跳过
  55. continue;
  56. } else {
  57. step1Merged.push(current);
  58. current = next;
  59. }
  60. }
  61. step1Merged.push(current);
  62. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  63. step1Merged.sort((a, b) => {
  64. return a.name.localeCompare(b.name) ||
  65. a.teacher.localeCompare(b.teacher) ||
  66. a.position.localeCompare(b.position) ||
  67. (a.day || 0) - (b.day || 0) ||
  68. (a.startSection || 0) - (b.startSection || 0) ||
  69. (a.endSection || 0) - (b.endSection || 0);
  70. });
  71. const step2Merged = [];
  72. let cur = step1Merged[0];
  73. for (let i = 1; i < step1Merged.length; i++) {
  74. const nxt = step1Merged[i];
  75. const isSameCourseAndSection =
  76. cur.name === nxt.name &&
  77. cur.teacher === nxt.teacher &&
  78. cur.position === nxt.position &&
  79. cur.day === nxt.day &&
  80. cur.startSection === nxt.startSection &&
  81. cur.endSection === nxt.endSection;
  82. if (isSameCourseAndSection) {
  83. // 周次合并去重 (如 1-8 周 + 9-16 周 -> 1-16 周)
  84. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  85. } else {
  86. step2Merged.push(cur);
  87. cur = nxt;
  88. }
  89. }
  90. step2Merged.push(cur);
  91. return step2Merged;
  92. }
  93. /**
  94. * 解析周次字符串,处理单双周和周次范围
  95. */
  96. function parseWeeks(weekStr) {
  97. if (!weekStr) return [];
  98. const cleaned = weekStr
  99. .replace(/周数[::]/g, '')
  100. .replace(/第/g, '')
  101. .replace(/周/g, '')
  102. .replace(/共\s*\d+\s*.*$/g, '');
  103. const segments = cleaned.split(/[,,、;;]/);
  104. const weeks = [];
  105. const segRegex = /(\d+)(?:\s*[-~]\s*(\d+))?\s*(?:[((]?\s*([单双])\s*周?\s*[))]?)?/g;
  106. for (const seg of segments) {
  107. const s = seg.trim();
  108. if (!s) continue;
  109. segRegex.lastIndex = 0;
  110. let m;
  111. while ((m = segRegex.exec(s)) !== null) {
  112. if (m[0] === '') {
  113. segRegex.lastIndex++;
  114. continue;
  115. }
  116. const start = parseInt(m[1], 10);
  117. const end = m[2] ? parseInt(m[2], 10) : start;
  118. const flagStr = m[3] || '';
  119. let flag = 0;
  120. if (flagStr.includes('单')) flag = 1;
  121. else if (flagStr.includes('双')) flag = 2;
  122. for (let w = start; w <= end; w++) {
  123. if (flag === 1 && w % 2 === 0) continue;
  124. if (flag === 2 && w % 2 !== 0) continue;
  125. weeks.push(w);
  126. }
  127. }
  128. }
  129. return [...new Set(weeks)].sort((a, b) => a - b);
  130. }
  131. /**
  132. * 解析 API 返回的 JSON 数据
  133. * kbList 字段:kcmc 课程名 / xm 教师 / cdmc 地点 / xqj 星期 / jcs 节次 / zcd 周次
  134. */
  135. function parseJsonData(jsonData) {
  136. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  137. return [];
  138. }
  139. const rawCourseList = jsonData.kbList;
  140. const initialCourseList = [];
  141. for (const rawCourse of rawCourseList) {
  142. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  143. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  144. continue;
  145. }
  146. const weeksArray = parseWeeks(rawCourse.zcd);
  147. if (weeksArray.length === 0) {
  148. continue;
  149. }
  150. const sectionParts = rawCourse.jcs.split('-');
  151. const startSection = Number(sectionParts[0]);
  152. const endSection = Number(sectionParts[sectionParts.length - 1]);
  153. const day = Number(rawCourse.xqj);
  154. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  155. day < 1 || day > 7 || startSection > endSection) {
  156. continue;
  157. }
  158. initialCourseList.push({
  159. name: rawCourse.kcmc.trim(),
  160. teacher: rawCourse.xm.trim(),
  161. position: rawCourse.cdmc.trim(),
  162. day: day,
  163. startSection: startSection,
  164. endSection: endSection,
  165. weeks: weeksArray
  166. });
  167. }
  168. return mergeAndDistinctCourses(initialCourseList);
  169. }
  170. async function promptUserToStart() {
  171. return await window.shiguangBridgePromise.showAlert(
  172. "教务系统课表导入",
  173. "导入前请确保您已在浏览器中成功登录教务系统",
  174. "好的,开始导入"
  175. );
  176. }
  177. /**
  178. * 从教务系统获取学年学期选项
  179. * 学年:以选中项为中心,取前2年+后2年,共5个选项
  180. */
  181. async function fetchAcademicOptions() {
  182. const url = `${getBaseUrl()}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
  183. try {
  184. const response = await fetch(url, {
  185. method: "GET",
  186. credentials: "include"
  187. });
  188. if (!response.ok) return null;
  189. const htmlText = await response.text();
  190. const parser = new DOMParser();
  191. const doc = parser.parseFromString(htmlText, "text/html");
  192. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  193. .filter(opt => opt.value !== "")
  194. .map(opt => ({
  195. value: opt.value,
  196. text: opt.textContent.trim(),
  197. selected: opt.selected
  198. }));
  199. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  200. .filter(opt => opt.value !== "")
  201. .map(opt => ({
  202. value: opt.value,
  203. text: opt.textContent.trim(),
  204. selected: opt.selected
  205. }));
  206. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  207. return null;
  208. }
  209. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  210. if (selectedIndex === -1) {
  211. return {
  212. yearOptions: allYearOptions.slice(0, 5),
  213. semesterOptions,
  214. defaultYearIndex: 0,
  215. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  216. ? semesterOptions.findIndex(opt => opt.selected)
  217. : 0
  218. };
  219. }
  220. const start = Math.max(0, selectedIndex - 2);
  221. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  222. const yearOptions = allYearOptions.slice(start, end);
  223. const newDefaultIndex = selectedIndex - start;
  224. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  225. return {
  226. yearOptions,
  227. semesterOptions,
  228. defaultYearIndex: newDefaultIndex,
  229. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  230. };
  231. } catch (e) {
  232. return null;
  233. }
  234. }
  235. /**
  236. * 提示用户选择学年和学期
  237. */
  238. async function selectAcademicYearAndSemester() {
  239. const optionsData = await fetchAcademicOptions();
  240. if (!optionsData) {
  241. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  242. return null;
  243. }
  244. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  245. const yearTexts = yearOptions.map(item => item.text);
  246. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  247. "选择学年",
  248. JSON.stringify(yearTexts),
  249. defaultYearIndex
  250. );
  251. if (yearIndex === null || yearIndex === -1) return null;
  252. const selectedYearCode = yearOptions[yearIndex].value;
  253. const semesterTexts = semesterOptions.map(item => item.text);
  254. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  255. "选择学期",
  256. JSON.stringify(semesterTexts),
  257. defaultSemesterIndex
  258. );
  259. if (semesterIndex === null || semesterIndex === -1) return null;
  260. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  261. return {
  262. academicYear: selectedYearCode,
  263. semesterCode: selectedSemesterCode
  264. };
  265. }
  266. /**
  267. * 获取学期开学日期
  268. */
  269. async function fetchSemesterStartDate(academicYear, semesterCode) {
  270. const url = `${getBaseUrl()}/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154`;
  271. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  272. try {
  273. const response = await fetch(url, {
  274. method: "POST",
  275. headers: {
  276. "accept": "application/json, text/javascript, */*; q=0.01",
  277. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  278. "x-requested-with": "XMLHttpRequest"
  279. },
  280. body: requestBody,
  281. credentials: "include"
  282. });
  283. if (response.ok) {
  284. const json = await response.json();
  285. if (Array.isArray(json) && json.length > 0) {
  286. // 优先找第1周,否则取第一项
  287. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  288. if (firstWeekObj.rq) {
  289. const startDateStr = firstWeekObj.rq.split('/')[0];
  290. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  291. return startDateStr;
  292. }
  293. }
  294. if (firstWeekObj.zcrq) {
  295. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  296. if (match) return match[1];
  297. }
  298. // 某些系统用 ksrq 字段
  299. if (firstWeekObj.ksrq) {
  300. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  301. if (match) return match[1];
  302. }
  303. }
  304. }
  305. } catch (e) {
  306. // 获取失败不影响主流程
  307. }
  308. return null;
  309. }
  310. /**
  311. * 从教务系统获取作息时间表(节次时间)
  312. * @param {string} academicYear 学年
  313. * @param {string} semesterCode 学期代码
  314. * @returns {Promise<Array<{number: number, startTime: string, endTime: string}>>}
  315. */
  316. async function fetchTimeSlots(academicYear, semesterCode) {
  317. const url = `${getBaseUrl()}/jzgl/skxxMobile_cxRsdjc.html?gnmkdm=N2154`;
  318. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&xqh_id=1`;
  319. try {
  320. const response = await fetch(url, {
  321. method: "POST",
  322. headers: {
  323. "accept": "*/*",
  324. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  325. "x-requested-with": "XMLHttpRequest"
  326. },
  327. body: requestBody,
  328. credentials: "include"
  329. });
  330. if (!response.ok) return null;
  331. const json = await response.json();
  332. if (!Array.isArray(json) || json.length === 0) {
  333. return null;
  334. }
  335. const seen = {};
  336. const timeSlots = [];
  337. for (let i = 0; i < json.length; i++) {
  338. const item = json[i];
  339. if (!item || !item.jcmc || !item.qssj || !item.jssj) {
  340. continue;
  341. }
  342. const num = Number(item.jcmc);
  343. if (isNaN(num) || seen[num]) {
  344. continue;
  345. }
  346. seen[num] = true;
  347. timeSlots.push({
  348. number: num,
  349. startTime: String(item.qssj).substring(0, 5),
  350. endTime: String(item.jssj).substring(0, 5)
  351. });
  352. }
  353. Array.prototype.sort.call(timeSlots, (a, b) => a.number - b.number);
  354. console.log("[作息] 解析到", timeSlots.length, "条:", timeSlots);
  355. return timeSlots.length > 0 ? timeSlots : null;
  356. } catch (e) {
  357. console.error("[作息] 异常:", e);
  358. return null;
  359. }
  360. }
  361. /**
  362. * 请求和解析课程数据
  363. */
  364. async function fetchAndParseCourses(academicYear, semesterCode) {
  365. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  366. const targetUrl = `${getBaseUrl()}/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151`;
  367. // 并行获取课程数据、开学日期、作息时间
  368. const [courseResponse, semesterStartDate, fetchedTimeSlots] = await Promise.all([
  369. fetch(targetUrl, {
  370. method: "POST",
  371. headers: {
  372. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  373. },
  374. body: requestBody,
  375. credentials: "include"
  376. }),
  377. fetchSemesterStartDate(academicYear, semesterCode),
  378. fetchTimeSlots(academicYear, semesterCode)
  379. ]);
  380. try {
  381. if (courseResponse.ok) {
  382. const jsonText = await courseResponse.text();
  383. const jsonData = JSON.parse(jsonText);
  384. if (jsonData && jsonData.kbList) {
  385. const parsedCourses = parseJsonData(jsonData);
  386. if (parsedCourses.length > 0) {
  387. return {
  388. courses: parsedCourses,
  389. config: {
  390. semesterStartDate: semesterStartDate,
  391. semesterTotalWeeks: 20
  392. },
  393. timeSlots: fetchedTimeSlots
  394. };
  395. }
  396. }
  397. }
  398. } catch (e) {
  399. // 请求失败
  400. }
  401. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  402. return null;
  403. }
  404. async function saveCourses(parsedCourses) {
  405. try {
  406. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  407. return true;
  408. } catch (error) {
  409. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  410. return false;
  411. }
  412. }
  413. // 优先使用从教务系统接口动态获取的作息时间,获取失败时回退到此表
  414. // 湖北经济学院作息时间表(依据学校官方校历卡,共 12 节)
  415. const FALLBACK_TIME_SLOTS = [
  416. { number: 1, startTime: "08:00", endTime: "08:45" },
  417. { number: 2, startTime: "08:50", endTime: "09:35" },
  418. { number: 3, startTime: "09:50", endTime: "10:35" },
  419. { number: 4, startTime: "10:40", endTime: "11:25" },
  420. { number: 5, startTime: "11:30", endTime: "12:15" },
  421. { number: 6, startTime: "14:00", endTime: "14:45" },
  422. { number: 7, startTime: "14:50", endTime: "15:35" },
  423. { number: 8, startTime: "15:50", endTime: "16:35" },
  424. { number: 9, startTime: "16:40", endTime: "17:25" },
  425. { number: 10, startTime: "18:30", endTime: "19:15" },
  426. { number: 11, startTime: "19:20", endTime: "20:05" },
  427. { number: 12, startTime: "20:10", endTime: "20:55" }
  428. ];
  429. async function importPresetTimeSlots(timeSlots) {
  430. let finalTimeSlots = timeSlots;
  431. let usedFallback = false;
  432. if (!finalTimeSlots || finalTimeSlots.length === 0) {
  433. // 动态获取失败,回退到硬编码保底方案
  434. finalTimeSlots = FALLBACK_TIME_SLOTS;
  435. usedFallback = true;
  436. }
  437. try {
  438. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(finalTimeSlots));
  439. if (usedFallback) {
  440. window.shiguangBridge.showToast("未获取到教务系统作息,已使用内置保底作息时间导入。");
  441. } else {
  442. window.shiguangBridge.showToast("预设时间段导入成功!");
  443. }
  444. } catch (error) {
  445. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  446. }
  447. }
  448. async function runImportFlow() {
  449. const alertConfirmed = await promptUserToStart();
  450. if (!alertConfirmed) {
  451. window.shiguangBridge.showToast("用户取消了导入。");
  452. return;
  453. }
  454. const selection = await selectAcademicYearAndSemester();
  455. if (!selection) {
  456. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  457. return;
  458. }
  459. const { academicYear, semesterCode } = selection;
  460. const result = await fetchAndParseCourses(academicYear, semesterCode);
  461. if (result === null) {
  462. return;
  463. }
  464. const { courses, config, timeSlots } = result;
  465. const saveResult = await saveCourses(courses);
  466. if (!saveResult) {
  467. return;
  468. }
  469. try {
  470. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  471. let configMsg = "课表配置更新成功!";
  472. if (config.semesterStartDate) {
  473. configMsg += ` 开学日期:${config.semesterStartDate}`;
  474. }
  475. window.shiguangBridge.showToast(configMsg);
  476. } catch (error) {
  477. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  478. }
  479. await importPresetTimeSlots(timeSlots);
  480. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  481. window.shiguangBridge.notifyTaskCompletion();
  482. }
  483. runImportFlow();