xhkjzyxy_01.js 18 KB

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