hueb.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // 湖北工程学院(vpn.hueb.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配
  3. // 出现问题请提issues或者提交pr更改
  4. /**
  5. * 节次与周次合并去重函数
  6. * @param {Array<Object>} courses 原始解析课程数组
  7. * @returns {Array<Object>} 合并去重后的课程数组
  8. */
  9. function mergeAndDistinctCourses(courses) {
  10. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  11. const list = courses.map(c => ({
  12. ...c,
  13. name: c.name || '',
  14. teacher: c.teacher || '',
  15. position: c.position || '',
  16. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  17. }));
  18. list.sort((a, b) => {
  19. return a.name.localeCompare(b.name) ||
  20. a.teacher.localeCompare(b.teacher) ||
  21. a.position.localeCompare(b.position) ||
  22. (a.day || 0) - (b.day || 0) ||
  23. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  24. (a.startSection || 0) - (b.startSection || 0);
  25. });
  26. const step1Merged = [];
  27. let current = list[0];
  28. for (let i = 1; i < list.length; i++) {
  29. const next = list[i];
  30. const isSameCourseAndWeeks =
  31. current.name === next.name &&
  32. current.teacher === next.teacher &&
  33. current.position === next.position &&
  34. current.day === next.day &&
  35. current.weeks.join(',') === next.weeks.join(',');
  36. const isContinuous = current.endSection + 1 === next.startSection;
  37. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  38. if (isSameCourseAndWeeks && isContinuous) {
  39. current.endSection = next.endSection;
  40. } else if (isSameCourseAndWeeks && isDuplicate) {
  41. continue;
  42. } else {
  43. step1Merged.push(current);
  44. current = next;
  45. }
  46. }
  47. step1Merged.push(current);
  48. step1Merged.sort((a, b) => {
  49. return a.name.localeCompare(b.name) ||
  50. a.teacher.localeCompare(b.teacher) ||
  51. a.position.localeCompare(b.position) ||
  52. (a.day || 0) - (b.day || 0) ||
  53. (a.startSection || 0) - (b.startSection || 0) ||
  54. (a.endSection || 0) - (b.endSection || 0);
  55. });
  56. const step2Merged = [];
  57. let cur = step1Merged[0];
  58. for (let i = 1; i < step1Merged.length; i++) {
  59. const nxt = step1Merged[i];
  60. const isSameCourseAndSection =
  61. cur.name === nxt.name &&
  62. cur.teacher === nxt.teacher &&
  63. cur.position === nxt.position &&
  64. cur.day === nxt.day &&
  65. cur.startSection === nxt.startSection &&
  66. cur.endSection === nxt.endSection;
  67. if (isSameCourseAndSection) {
  68. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  69. } else {
  70. step2Merged.push(cur);
  71. cur = nxt;
  72. }
  73. }
  74. step2Merged.push(cur);
  75. return step2Merged;
  76. }
  77. /**
  78. * 解析周次字符串,处理单双周和周次范围
  79. */
  80. function parseWeeks(weekStr) {
  81. if (!weekStr) return [];
  82. const weekSets = weekStr.split(',');
  83. let weeks = [];
  84. for (const set of weekSets) {
  85. const trimmedSet = set.trim();
  86. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  87. const singleMatch = trimmedSet.match(/^(\d+)周/);
  88. let start = 0;
  89. let end = 0;
  90. let processed = false;
  91. if (rangeMatch) {
  92. start = Number(rangeMatch[1]);
  93. end = Number(rangeMatch[2]);
  94. processed = true;
  95. } else if (singleMatch) {
  96. start = end = Number(singleMatch[1]);
  97. processed = true;
  98. }
  99. if (processed) {
  100. const isSingle = trimmedSet.includes('(单)');
  101. const isDouble = trimmedSet.includes('(双)');
  102. for (let w = start; w <= end; w++) {
  103. if (isSingle && w % 2 === 0) continue;
  104. if (isDouble && w % 2 !== 0) continue;
  105. weeks.push(w);
  106. }
  107. }
  108. }
  109. return [...new Set(weeks)].sort((a, b) => a - b);
  110. }
  111. /**
  112. * 解析 API 返回的 JSON 数据
  113. */
  114. function parseJsonData(jsonData) {
  115. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  116. return [];
  117. }
  118. const rawCourseList = jsonData.kbList;
  119. const initialCourseList = [];
  120. for (const rawCourse of rawCourseList) {
  121. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  122. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  123. continue;
  124. }
  125. const weeksArray = parseWeeks(rawCourse.zcd);
  126. if (weeksArray.length === 0) {
  127. continue;
  128. }
  129. const sectionParts = rawCourse.jcs.split('-');
  130. const startSection = Number(sectionParts[0]);
  131. const endSection = Number(sectionParts[sectionParts.length - 1]);
  132. const day = Number(rawCourse.xqj);
  133. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  134. day < 1 || day > 7 || startSection > endSection) {
  135. continue;
  136. }
  137. initialCourseList.push({
  138. name: rawCourse.kcmc.trim(),
  139. teacher: rawCourse.xm.trim(),
  140. position: rawCourse.cdmc.trim(),
  141. day: day,
  142. startSection: startSection,
  143. endSection: endSection,
  144. weeks: weeksArray
  145. });
  146. }
  147. return mergeAndDistinctCourses(initialCourseList);
  148. }
  149. async function promptUserToStart() {
  150. return await window.shiguangBridgePromise.showAlert(
  151. "教务系统课表导入",
  152. "导入前请确保您已在浏览器中成功登录教务系统",
  153. "好的,开始导入"
  154. );
  155. }
  156. /**
  157. * 从教务系统获取学年学期选项
  158. */
  159. async function fetchAcademicOptions() {
  160. const url = "https://202-206-194-100.vpn.hueb.edu.cn:8118/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151";
  161. try {
  162. const response = await fetch(url, {
  163. method: "GET",
  164. credentials: "include"
  165. });
  166. if (!response.ok) return null;
  167. const htmlText = await response.text();
  168. const parser = new DOMParser();
  169. const doc = parser.parseFromString(htmlText, "text/html");
  170. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  171. .filter(opt => opt.value !== "")
  172. .map(opt => ({
  173. value: opt.value,
  174. text: opt.textContent.trim(),
  175. selected: opt.selected
  176. }));
  177. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  178. .filter(opt => opt.value !== "")
  179. .map(opt => ({
  180. value: opt.value,
  181. text: opt.textContent.trim(),
  182. selected: opt.selected
  183. }));
  184. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  185. return null;
  186. }
  187. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  188. if (selectedIndex === -1) {
  189. return {
  190. yearOptions: allYearOptions.slice(0, 5),
  191. semesterOptions,
  192. defaultYearIndex: 0,
  193. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  194. ? semesterOptions.findIndex(opt => opt.selected)
  195. : 0
  196. };
  197. }
  198. const start = Math.max(0, selectedIndex - 2);
  199. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  200. const yearOptions = allYearOptions.slice(start, end);
  201. const newDefaultIndex = selectedIndex - start;
  202. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  203. return {
  204. yearOptions,
  205. semesterOptions,
  206. defaultYearIndex: newDefaultIndex,
  207. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  208. };
  209. } catch (e) {
  210. return null;
  211. }
  212. }
  213. /**
  214. * 提示用户选择学年和学期
  215. */
  216. async function selectAcademicYearAndSemester() {
  217. const optionsData = await fetchAcademicOptions();
  218. if (!optionsData) {
  219. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  220. return null;
  221. }
  222. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  223. const yearTexts = yearOptions.map(item => item.text);
  224. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  225. "选择学年",
  226. JSON.stringify(yearTexts),
  227. defaultYearIndex
  228. );
  229. if (yearIndex === null || yearIndex === -1) return null;
  230. const selectedYearCode = yearOptions[yearIndex].value;
  231. const semesterTexts = semesterOptions.map(item => item.text);
  232. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  233. "选择学期",
  234. JSON.stringify(semesterTexts),
  235. defaultSemesterIndex
  236. );
  237. if (semesterIndex === null || semesterIndex === -1) return null;
  238. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  239. return {
  240. academicYear: selectedYearCode,
  241. semesterCode: selectedSemesterCode
  242. };
  243. }
  244. /**
  245. * 获取学期开学日期
  246. */
  247. async function fetchSemesterStartDate(academicYear, semesterCode) {
  248. const url = "https://202-206-194-100.vpn.hueb.edu.cn:8118/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  249. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  250. try {
  251. const response = await fetch(url, {
  252. method: "POST",
  253. headers: {
  254. "accept": "application/json, text/javascript, */*; q=0.01",
  255. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  256. "x-requested-with": "XMLHttpRequest"
  257. },
  258. body: requestBody,
  259. credentials: "include"
  260. });
  261. if (response.ok) {
  262. const json = await response.json();
  263. if (Array.isArray(json) && json.length > 0) {
  264. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  265. if (firstWeekObj.rq) {
  266. const startDateStr = firstWeekObj.rq.split('/')[0];
  267. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  268. return startDateStr;
  269. }
  270. }
  271. if (firstWeekObj.zcrq) {
  272. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  273. if (match) return match[1];
  274. }
  275. if (firstWeekObj.ksrq) {
  276. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  277. if (match) return match[1];
  278. }
  279. }
  280. }
  281. } catch (e) {
  282. // 获取失败不影响主流程
  283. }
  284. return null;
  285. }
  286. /**
  287. * 请求和解析课程数据
  288. */
  289. async function fetchAndParseCourses(academicYear, semesterCode) {
  290. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  291. const targetUrl = "https://202-206-194-100.vpn.hueb.edu.cn:8118/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  292. const [courseResponse, semesterStartDate] = await Promise.all([
  293. fetch(targetUrl, {
  294. method: "POST",
  295. headers: {
  296. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  297. },
  298. body: requestBody,
  299. credentials: "include"
  300. }),
  301. fetchSemesterStartDate(academicYear, semesterCode)
  302. ]);
  303. try {
  304. if (courseResponse.ok) {
  305. const jsonText = await courseResponse.text();
  306. const jsonData = JSON.parse(jsonText);
  307. if (jsonData && jsonData.kbList) {
  308. const parsedCourses = parseJsonData(jsonData);
  309. if (parsedCourses.length > 0) {
  310. return {
  311. courses: parsedCourses,
  312. config: {
  313. semesterStartDate: semesterStartDate,
  314. semesterTotalWeeks: 20
  315. }
  316. };
  317. }
  318. }
  319. }
  320. } catch (e) {
  321. // 请求失败
  322. }
  323. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  324. return null;
  325. }
  326. async function saveCourses(parsedCourses) {
  327. try {
  328. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  329. return true;
  330. } catch (error) {
  331. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  332. return false;
  333. }
  334. }
  335. const TimeSlots = [
  336. { number: 1, startTime: "08:00", endTime: "08:45" },
  337. { number: 2, startTime: "08:45", endTime: "09:30" },
  338. { number: 3, startTime: "09:45", endTime: "10:30" },
  339. { number: 4, startTime: "10:30", endTime: "11:15" },
  340. { number: 5, startTime: "11:25", endTime: "12:10" },
  341. { number: 6, startTime: "14:00", endTime: "14:45" },
  342. { number: 7, startTime: "14:45", endTime: "15:30" },
  343. { number: 8, startTime: "15:45", endTime: "16:30" },
  344. { number: 9, startTime: "16:30", endTime: "17:15" },
  345. { number: 10, startTime: "17:25", endTime: "18:10" },
  346. { number: 11, startTime: "19:00", endTime: "19:45" },
  347. { number: 12, startTime: "19:45", endTime: "20:30" },
  348. { number: 13, startTime: "20:40", endTime: "21:25" }
  349. ];
  350. async function importPresetTimeSlots(timeSlots) {
  351. if (timeSlots.length === 0) return;
  352. try { await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots)); } catch (e) {}
  353. }
  354. async function runImportFlow() {
  355. const alertConfirmed = await promptUserToStart();
  356. if (!alertConfirmed) {
  357. window.shiguangBridge.showToast("用户取消了导入。");
  358. return;
  359. }
  360. const selection = await selectAcademicYearAndSemester();
  361. if (!selection) {
  362. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  363. return;
  364. }
  365. const { academicYear, semesterCode } = selection;
  366. const result = await fetchAndParseCourses(academicYear, semesterCode);
  367. if (result === null) {
  368. return;
  369. }
  370. const { courses, config } = result;
  371. const saveResult = await saveCourses(courses);
  372. if (!saveResult) {
  373. return;
  374. }
  375. try {
  376. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  377. let configMsg = "课表配置更新成功!";
  378. if (config.semesterStartDate) {
  379. configMsg += ` 开学日期:${config.semesterStartDate}`;
  380. }
  381. window.shiguangBridge.showToast(configMsg);
  382. } catch (error) {
  383. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  384. }
  385. await importPresetTimeSlots(TimeSlots);
  386. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  387. window.shiguangBridge.notifyTaskCompletion();
  388. }
  389. runImportFlow();