xhkjzyxy_01.js 18 KB

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