xhkjzyxy_01.js 18 KB

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